<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form ref="formRef" :model="formData" label-placement="left" label-width="85px">
        <n-form-item
          label="头像"
          path="avatar"
          :rule="{ key: 'avatar', required: true, message: '请上传头像', trigger: 'blur' }"
        >
          <Cropper
            ref="cropperCircled"
            :src="formData.avatar"
            :uploadApi="upload"
            name="user"
            title="头像上传"
            @upload-success="uploadSuccess"
          >
            <template #avatar> </template>
          </Cropper>
        </n-form-item>
        <div class="flex">
          <n-form-item
            label="账号"
            path="username"
            class="flex-1"
            :rule="{ required: true, message: '请输入账号', trigger: 'blur' }"
          >
            <n-input
              :disabled="props.userId ? true : false"
              v-model:value="formData.username"
              placeholder="请输入账号"
              clearable
            />
          </n-form-item>
          <n-form-item
            label="密码"
            path="password"
            class="flex-1"
            :rule="{
              required: props.userId ? false : true,
              message: '请输入密码',
              trigger: 'blur',
            }"
          >
            <n-input
              v-model:value.trim="formData.password"
              clearable
              type="password"
              placeholder="请输入密码"
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="名称"
            path="realname"
            class="flex-1"
            :rule="{ required: true, message: '请输入名称', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.realname" placeholder="请输入名称" clearable />
          </n-form-item>
          <n-form-item label="性别" path="sex" class="flex-1">
            <n-radio-group v-model:value="formData.gender" path="gender">
              <n-radio :value="1">男</n-radio>
              <n-radio :value="2">女</n-radio>
              <n-radio :value="3">保密</n-radio>
            </n-radio-group>
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="角色"
            path="roles"
            class="flex-1"
            :rule="[
              { type: 'array', required: true, message: '请选择角色', trigger: ['blur', 'change'] },
            ]"
          >
            <n-select
              v-model:value="formData.roles"
              mode="multiple"
              class="flex-1"
              clearable
              multiple
              :options="optionData.roleList"
              label-field="name"
              value-field="id"
              placeholder="请选择角色"
            />
          </n-form-item>
          <n-form-item
            label="部门"
            path="deptId"
            class="flex-1"
            :rule="{
              type: 'number',
              required: true,
              message: '请选择部门',
              trigger: ['blur', 'change'],
            }"
          >
            <n-tree-select
              v-model:value="formData.deptId"
              :options="optionData.deptList"
              placeholder="请选择部门"
              label-field="name"
              key-field="id"
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="职级"
            path="levelId"
            class="flex-1"
            :rule="{
              type: 'number',
              required: true,
              message: '请选择职级',
              trigger: ['blur', 'change'],
            }"
          >
            <n-select
              v-model:value="formData.levelId"
              class="flex-1"
              placeholder="请选择职级"
              clearable
              :options="optionData.levelList"
              label-field="name"
              value-field="id"
            />
          </n-form-item>
          <n-form-item
            label="岗位"
            path="positionId"
            class="flex-1"
            :rule="{
              type: 'number',
              required: true,
              message: '请选择岗位',
              trigger: ['blur', 'change'],
            }"
          >
            <n-select
              v-model:value="formData.positionId"
              :options="optionData.positionList"
              label-field="name"
              value-field="id"
              class="flex-1"
              clearable
              placeholder="请选择岗位"
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="手机号码"
            path="mobile"
            class="flex-1"
            :rule="[
              { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator: rule.validatePhone, trigger: 'blur' },
            ]"
          >
            <n-input v-model:value="formData.mobile" placeholder="请输入手机号码" clearable />
          </n-form-item>
          <n-form-item
            label="邮箱地址"
            path="email"
            class="flex-1"
            :rule="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确邮箱地址', trigger: 'blur' },
            ]"
          >
            <n-input v-model:value="formData.email" placeholder="请输入邮箱地址" clearable />
          </n-form-item>
        </div>

        <div class="flex">
          <n-form-item
            label="所属区域"
            class="flex-1"
            path="city"
            :rule="{
              key: 'city',
              type: 'array',
              required: true,
              message: '请选择所属区域',
              trigger: ['blur', 'change'],
            }"
          >
            <chinaArea style="width: 100%" v-model="formData.city" />
          </n-form-item>
          <n-form-item
            label="详细地址"
            class="flex-1"
            path="address"
            :rule="{ required: true, message: '请输入详细地址', trigger: 'blur' }"
          >
            <n-input
              v-model:value="formData.address"
              type="textarea"
              placeholder="请输入详细地址"
              clearable
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item label="用户状态" path="status" class="flex-1">
            <n-radio-group v-model:value="formData.status">
              <n-radio :value="1">正常</n-radio>
              <n-radio :value="2">禁用</n-radio>
            </n-radio-group>
          </n-form-item>
          <n-form-item
            label="排序"
            path="sort"
            class="flex-1"
            :rule="{ type: 'number', required: true, message: '请输入排序', trigger: 'blur' }"
          >
            <n-input-number v-model:value="formData.sort" :max="9999" />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item label="简介" path="intro" class="flex-1">
            <n-input
              v-model:value="formData.intro"
              type="textarea"
              placeholder="请输入简介"
              clearable
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item label="备注" path="note" class="flex-1">
            <n-input
              v-model:value="formData.note"
              type="textarea"
              placeholder="请输入备注"
              clearable
            />
          </n-form-item>
        </div>
      </n-form>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { getUserDetail, userAdd, userUpdate } from '@/api/system/user';
  import { upload } from '@/api/common';
  import { Cropper } from '@/components/Cropper';
  import chinaArea from '@/components/ChinaArea/index.vue';
  import { ref, onMounted, reactive } from 'vue';
  import { getRoleAllList } from '@/api/system/role';
  import { getDeptList } from '@/api/system/dept';
  import { getLevelAllList } from '@/api/system/level';
  import { getPositionAllList } from '@/api/system/position';
  import { buildTree } from '@/utils/auth';
  import { rule } from '@/utils/validate';
  import { useMessage } from 'naive-ui';
  import { useUserStore } from '@/store/modules/user';
  import { useModal } from '@/components/Modal';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    userId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义参数变量
   */
  const emit = defineEmits(['success', 'update:visible']);

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.userId ? '编辑用户' : '添加用户',
    subBtuText: '确定',
    width: 800,
  });

  const message = useMessage();
  const uploadHeaders = reactive({
    authorization: useUserStore().getToken,
  });
  const formRef = ref();

  /**
   * 定义接收的参数
   */
  const formData = reactive({
    id: 0,
    avatarName: '',
    email: '',
    username: '',
    realname: '',
    mobile: '',
    gender: 1,
    roles: [],
    deptId: '',
    levelId: null,
    positionId: null,
    address: '',
    status: 1,
    note: '',
    intro: '',
    sort: 0,
    city: [],
    avatar: '',
    password: '',
    passwordConfirm: '',
  });
  const cropperCircled = ref();
  const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
      if (!value) callback(new Error('请再次输入密码'));
      if (value !== formData.password) callback(new Error('两次输入密码不一致!'));
    }
    callback();
  };

  /**
   * 上传成功回调
   * @param data 参数
   */
  const uploadSuccess = (data) => {
    formData.avatar = data.fileUrl;
    formRef.value?.validate(
      (errors) => {},
      (rule) => {
        return rule?.key === 'avatar';
      },
    );
    return;
  };

  /**
   * 设置表单数据
   * @param row 参数
   */
  const setFormData = async (row: any) => {
    const data = await getUserDetail(row.userId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = () => {
    console.log(formData);
    formRef.value
      .validate()
      .then(async () => {
        props.userId ? await userUpdate(formData) : await userAdd(formData);
        setSubLoading(false);
        message.success('操作成功');
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 定义选项数据
   */
  const optionData = reactive({
    roleList: [],
    deptList: [],
    levelList: [],
    positionList: [],
  });

  /**
   * 上传发生变化
   */
  function uploadChange(data: string[]) {
    formData.avatar = data.fileUrl;
    formData.avatarName = data.fileName;
  }

  /**
   * 执行删除
   * @param file 文件参数
   */
  const handleDelete = async (file) => {
    console.log(file);
  };

  /**
   * 获取全部字典数据
   */
  const getAllDict = async () => {
    let list = await getRoleAllList();
    optionData.roleList = list ? list : [];
    list = await getDeptList();
    optionData.deptList = list ? buildTree(list) : [];
    list = await getLevelAllList();
    optionData.levelList = list ? list : [];
    list = await getPositionAllList();
    optionData.positionList = list ? list : [];
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getAllDict();
    if (props.userId) {
      setFormData({ userId: props.userId });
    }
  });

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>
