<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="form"
        label-placement="left"
        :rules="rules"
        :on-positive-click="handleConfirm"
        :on-negative-click="handleClose"
      >
        <n-form-item
          label="头像:"
          path="avatar"
        >
          <uploadImage
            :options="{
              max:1,
              action: '/upload/uploadImage/demo',
            }"
          />
        </n-form-item>
        <n-form-item label="用户编号:" path="code">
          <n-input
            v-model:value="form.code"
            clearable
            :maxlength="20"
            placeholder="请输入用户编号"
          />
        </n-form-item>
        <n-form-item label="用户账号:" path="username">
          <n-input
            v-model:value="form.username"
            clearable
            :maxlength="20"
            placeholder="请输入用户账号"
          />
        </n-form-item>
        <n-form-item
          label="登录密码:"
          path="password"
        >
          <n-input
            v-model:value="form.password"
            type="password"
            :maxlength="20"
            placeholder="请输入登录密码"
          />
        </n-form-item>
        <n-form-item label="用户姓名:" path="realname">
          <n-input
            v-model:value="form.realname"
            clearable
            :maxlength="20"
            placeholder="请输入用户姓名"
          />
        </n-form-item>
        <n-form-item label="所属部门:" path="deptId">
          <n-select
            v-model:value="form.deptId"
            :options="deptOptions"
            placeholder="请选择所属部门"
          />
        </n-form-item>
        <n-form-item label="角色:" path="roleIds">
          <n-select
            v-model:value="form.roleIds"
            clearable
            :multiple="true"
            :options="rolesOptions"
            placeholder="请选择角色"
          />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group
            v-model:value="form.status"
          >
            <n-radio :value="1">正常</n-radio>
            <n-radio :value="2">禁用</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item
          label="备注:"
        >
          <n-input
            v-model:value="form.note"
            type="textarea"
            :rows="3"
            :maxlength="200"
            placeholder="请输入备注"
          />
        </n-form-item>
      </n-form>
    </template>
  </Modal>
</template>

<script>
import { defineComponent, computed, onMounted, reactive, toRefs } from 'vue'
import Modal from '@/components/Modal/index.vue'
import uploadImage from '@/components/ImgUpload/index.vue'
import { getDeptAll } from '@/api/system/dept/index'
import { getRoleAll } from '@/api/system/role/index'
import { addUser, editUser } from '@/api/system/user/index'
import { dataToSelect } from '@/utils/handleData.js'
export default defineComponent({
  name: 'UserModal',
  components: { Modal, uploadImage },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: () => {}
    }
  },
  emits: {
    'update:visible': null,
    'done': null
  },
  setup(props, { emit }) {
    const data = reactive({
      form: {
        avatar: '/images/user/20211011/20211011151447698.jpg',
        code: '',
        deptId: null,
        username: '',
        realname: '',
        password: '',
        roleIds: [],
        status: 1,
        note: ''

      },
      deptOptions: [],
      rolesOptions: [],
      rules: {
        avatar: [
          { required: true, message: '请选择头像', type: 'string', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入用户姓名', type: 'string', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择部门', type: 'number', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', type: 'number', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '请选择角色', type: 'array', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户账号', type: 'string', trigger: 'blur' }
        ]
      }
    })
    const getModalOptions = computed(() => {
      return {
        title: Object.keys(props.row).length === 0 ? '添加用户' : '编辑用户',
        show: props.visible,
        form: Object.assign(data.form, props.row),
        negativeText: '取消',
        positiveText: '确认'
      }
    })

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }

    // 获取部门列表
    async function getDeptOptions() {
      const res = await getDeptAll()
      data.deptOptions = dataToSelect(res.data, { label: 'name', value: 'id' })
    }

    // 获取角色列表
    async function getRoleOptions() {
      const res = await getRoleAll()
      data.rolesOptions = dataToSelect(res.data, { label: 'name', value: 'id' })
    }

    onMounted(() => {
      getDeptOptions()
      getRoleOptions()
    })

    // 上传文件
    const handleUpload = ({ file }) => {
      console.log(file)
      // data.form.avatar = file.url
    }

    return {
      ...toRefs(data),
      getModalOptions,
      handleClose,
      handleUpload
    }
  },
  methods: {
    // 表单提交
    handleConfirm() {
      const type = Object.keys(this.row).length === 0 ? 'add' : 'edit'
      this.$refs.formRef.validate((errors) => {
        if (!errors) {
          if (type === 'add') {
            addUser(this.form).then(res => {
              if (res.code === 0) {
                this.handleClose()
                this.$emit('done')
                $message.success(res.msg)
              } else {
                $message.error(res.msg)
              }
            }).catch(e => {
              console.log(e)
            })
          } else if (type === 'edit') {
            editUser(this.form).then(res => {
              if (res.code === 0) {
                this.handleClose()
                this.$emit('done')
                $message.success(res.msg)
              } else {
                $message.error(res.msg)
              }
            })
          }
        } else {
          $message.error('请完善必填信息')
        }
      })
    }
  }
})
</script>
<style scoped lang='scss'>
</style>
