<template>
  <MDialog
    :visible="visible"
    title="创建数据订单"
    widthType="0"
    @update:visible="handleVisibleChange"
    @submit="handleSubmit"
  >
    <MForm ref="form" :items="formItems" v-model="formValues"></MForm>
  </MDialog>
</template>

<script>
import MDialog from '@/components/Dialog'
import MForm from '@/components/MForm'
import { api } from '@/api/dataOrder'

export default {
  name: 'CreateOrderDialog',
  components: {
    MDialog,
    MForm
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      formValues: {
        title: '',
        description: '',
        created_by: ''
      }
    }
  },
  computed: {
    formItems () {
      return [
        {
          type: 'text',
          key: 'title',
          label: '订单标题 *',
          placeholder: '请输入订单标题，例如：员工与部门关联数据',
          rules: [
            v => !!v || '请输入订单标题',
            v => (v && v.length <= 200) || '标题不能超过200个字符'
          ],
          maxlength: 200,
          counter: true,
          outlined: true,
          dense: true,
          hideDetails: 'auto'
        },
        {
          type: 'textarea',
          key: 'description',
          label: '需求描述 *',
          placeholder: '请详细描述需要什么数据，包括： 1. 涉及的业务领域（如员工、部门、项目等） 2. 需要的具体字段 3. 数据用途',
          rules: [
            v => !!v || '请输入需求描述',
            v => (v && v.length >= 10) || '描述至少需要10个字符'
          ],
          maxlength: 2000,
          counter: true,
          outlined: true,
          rows: 8,
          hideDetails: 'auto'
        },
        {
          type: 'text',
          key: 'created_by',
          label: '创建人',
          outlined: true,
          dense: true,
          hideDetails: 'auto'
        }
      ]
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.resetForm()
      }
    }
  },
  methods: {
    handleVisibleChange (val) {
      this.$emit('update:visible', val)
    },
    resetForm () {
      this.formValues = {
        title: '',
        description: '',
        created_by: ''
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetValidation()
        }
      })
    },
    async handleSubmit () {
      if (!this.$refs.form.validate()) {
        return
      }
      try {
        const data = {
          title: this.formValues.title,
          description: this.formValues.description
        }
        if (this.formValues.created_by) {
          data.created_by = this.formValues.created_by
        }
        await api.createOrder(data)
        this.$snackbar.success('订单创建成功')
        this.$emit('update:visible', false)
        this.$emit('success')
      } catch (error) {
        this.$snackbar.error(error)
      }
    }
  }
}
</script>
