<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="userForm"
        :rules="userRules"
        :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">
            <UploadOss v-if="item.type === 'oss'" :ref="el=>{ossRefs[item.refIndex] = el}" :default-list="userForm[item.file]" @upload-status="handleUploadStatus" />
            <n-input v-if="item.type === 'input'" v-model:value="userForm[item.key]" v-bind="item.props" />
            <n-select v-if="item.type === 'select'" v-model:value="userForm[item.key]" v-bind="item.props" />
            <n-radio-group v-if="item.type === 'radio'" v-model:value="userForm[item.key]" :name="item.key">
              <n-space>
                <n-radio v-for="(cItem,cIndex) in item.options" :key="`${item.key}_${cIndex}`" :value="cItem.value"> {{ cItem.label }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </template>
      </n-form>
    </template>
  </Modal>
</template>

<script>
import { form, getDeptOptions, getRoleOptions } from '../tools/form.js'
import { defineComponent, ref, reactive, computed, toRefs } from 'vue'
import Modal from '@/components/Modal/index.vue'
import UploadOss from '@/components/UploadOss/index.vue'
import { addUser, editUser } from '@/api/system/user/index'
export default defineComponent({
  name: 'UserModal',
  components: { Modal, UploadOss },
  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 }) {
    const MODAL_TYPE = {
      'create': '新建用户',
      'preview': '用户详情',
      'update': '编辑用户'
    }
    getDeptOptions()
    getRoleOptions()
    const { userForm, userRules } = form
    const formRef = ref()
    const ossRefs = ref([])
    const data = reactive({
      userForm: {
        ...userForm,
        ...props.data,
        roleIds: props?.data?.roles.map((item) => { return item.id }) || []
      },
      userRules: {
        ...userRules
      },
      disabled: props.type === 'preview'
    })
    const getModalOptions = computed(() => {
      return {
        show: props.visible,
        title: MODAL_TYPE[props.type],
        negativeText: '取消',
        positiveText: '确认'
      }
    })

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

    function handleUploadStatus(status) {
      data.userForm.imageStatus = status
    }

    function handleConfirm() {
      formRef.value?.validate((errors) => {
        if (!errors) {
          const uploads = ossRefs.value.map((item, index) => {
            return item.startUpload()
          })
          Promise.all(uploads)
            .then(response => {
              const isError = response.map((item) => {
                return item.includes('error')
              })
              if (!isError.includes(true)) {
                const imageStr = response.join()
                const params = {
                  ...data.userForm,
                  // avatar: imageStr
                  avatar: '/imagedir/2uim2hpl94u_1655380018696.png'
                }
                if (params.id) {
                  /* 编辑 */
                  editUser(params)
                    .then(res => {
                      if (res.code === 0) {
                        emit('reload')
                        handleClose()
                      }
                    })
                } else {
                  /* 新增 */
                  addUser(params)
                    .then(res => {
                      if (res.code === 0) {
                        emit('reload')
                        handleClose()
                      }
                    })
                }
              } else {
                $message.error('文件上传失败，请稍后重试')
              }
            })
        } else {
          $message.error('请完善必填信息')
        }
      })
    }

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