<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="assignForm"
        :rules="assignRules"
        :label-width="80"
        label-placement="left"
        require-mark-placement="left"
        :disabled="disabled"
      >
        <template v-for="(item,index) in getFormOptions" :key="index">
          <n-form-item :label="item.label" :path="item.key">
            <n-select v-if="item.type === 'select'" v-model:value="assignForm[item.key]" v-bind="item.props" />
          </n-form-item>
        </template>
      </n-form>
    </template>
  </Modal>
</template>

<script>
import { form, getUserOptions } from '../tools/form.js'
import { defineComponent, ref, reactive, computed, toRefs } from 'vue'
import Modal from '@/components/Modal/index.vue'
import { assignOrder } from '@/api/order/index.js'
export default defineComponent({
  name: 'UserModal',
  components: { Modal },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'create'
    },
    data: {
      type: Object,
      default: () => null
    }
  },
  emits: {
    'update:visible': null,
    'reload': null
  },
  setup(props, { emit }) {
    getUserOptions()
    const { assignForm, assignRules } = form
    const formRef = ref()
    const data = reactive({
      assignForm: {
        ...assignForm
      },
      assignRules: {
        ...assignRules
      },
      disabled: props.type === 'preview'
    })
    const getModalOptions = computed(() => {
      return {
        show: props.visible,
        title: '分配用户',
        negativeText: '取消',
        positiveText: '确认'
      }
    })

    const getFormOptions = computed(() => {
      return {
        ...form.formItem
      }
    })

    function handleConfirm() {
      formRef.value?.validate((errors) => {
        if (!errors) {
          const params = {
            id: props.data.id,
            ...data.assignForm
            // handleUserList: data.assignForm.handleUserList.join(',')
          }
          assignOrder(params)
            .then(res => {
              if (res.code === 0) {
                emit('reload')
                handleClose()
              }
            })
        } else {
          $message.error('请完善必填信息')
        }
      })
    }

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }
    return {
      ...toRefs(data),
      formRef,
      getModalOptions,
      getFormOptions,
      handleConfirm,
      handleClose
    }
  }
})
</script>
<style scoped lang='scss'>
</style>
