<template>
  <a-modal
    v-model:visible="props.visible"
    :title="props.userId ? '编辑' : '新增'"
    width="800px"
    style="top: 20px"
    @cancel="dialogClose"
  >
    <a-form ref="formRef" :model="formData" :label-col="{ style: { width: '85px' } }">
      <a-form-item
        label="头像"
        name="avatar"
        :rules="{ required: true, message: '请上传头像', trigger: 'blur' }"
      >
        <!-- <UploadImg @changeFileName="(name)=>formData.avatarName=name"
                       :fileType=" ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
                       name="user"
                       :fileSize="200"
                       :cropper="true"
                       v-model:image-url="formData.avatar">
              <template v-slot:tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
            </UploadImg> -->
        <Cropper
          ref="cropperCircled"
          :src="formData.avatar"
          :uploadApi="upload"
          name="user"
          title="头像上传"
          @upload-success="uploadSuccess"
        >
          <template #avatar> </template>
        </Cropper>
      </a-form-item>
      <div class="flex">
        <a-form-item
          label="账号"
          name="username"
          class="flex-1"
          :rules="{ required: true, message: '请输入账号', trigger: 'blur' }"
        >
          <a-input
            :disabled="props.userId ? true : false"
            v-model:value="formData.username"
            placeholder="请输入账号"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="密码"
          name="password"
          class="flex-1"
          :rules="{ required: props.userId ? false : true, message: '请输入密码', trigger: 'blur' }"
        >
          <a-input-password
            v-model:value.trim="formData.password"
            allow-clear
            placeholder="请输入密码"
          />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="名称"
          name="realname"
          class="flex-1"
          :rules="{ required: true, message: '请输入名称', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.realname" placeholder="请输入名称" allow-clear />
        </a-form-item>
        <a-form-item label="性别" name="sex" class="flex-1">
          <a-radio-group v-model:value="formData.gender" name="gender">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="2">女</a-radio>
            <a-radio :value="3">保密</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="角色"
          name="roles"
          class="flex-1"
          :rules="{ required: true, message: '请选择角色', trigger: 'change' }"
        >
          <a-select
            v-model:value="formData.roles"
            mode="multiple"
            class="flex-1"
            allow-clear
            placeholder="请选择角色"
          >
            <a-select-option
              v-for="(item, index) in optionData.roleList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          label="部门"
          name="deptId"
          class="flex-1"
          :rules="{ required: true, message: '请选择部门', trigger: 'change' }"
        >
          <a-tree-select
            v-model:value="formData.deptId"
            :tree-data="optionData.deptList"
            placeholder="请选择部门"
            :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
          />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="职级"
          name="levelId"
          class="flex-1"
          :rules="{ required: true, message: '请选择职级', trigger: 'change' }"
        >
          <a-select
            v-model:value="formData.levelId"
            class="flex-1"
            allow-clear
            placeholder="请选择职级"
          >
            <a-select-option
              v-for="(item, index) in optionData.levelList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          label="岗位"
          name="positionId"
          class="flex-1"
          :rules="{ required: true, message: '请选择岗位', trigger: 'change' }"
        >
          <a-select
            v-model:value="formData.positionId"
            class="flex-1"
            allow-clear
            placeholder="请选择岗位"
          >
            <a-select-option
              v-for="(item, index) in optionData.positionList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="手机号码"
          name="mobile"
          class="flex-1"
          :rules="[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: rule.validatePhone, trigger: 'blur' },
          ]"
        >
          <a-input v-model:value="formData.mobile" placeholder="请输入手机号码" allow-clear />
        </a-form-item>
        <a-form-item
          label="邮箱地址"
          name="email"
          class="flex-1"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确邮箱地址', trigger: 'blur' },
          ]"
        >
          <a-input v-model:value="formData.email" placeholder="请输入邮箱地址" allow-clear />
        </a-form-item>
      </div>

      <div class="flex">
        <a-form-item
          label="所属区域"
          class="flex-1"
          name="city"
          :rules="{ required: true, message: '请选择所属区域', trigger: 'change' }"
        >
          <chinaArea style="width: 100%" v-model="formData.city" />
        </a-form-item>
        <a-form-item
          label="详细地址"
          class="flex-1"
          name="address"
          :rules="{ required: true, message: '请输入详细地址', trigger: 'blur' }"
        >
          <a-textarea v-model:value="formData.address" placeholder="请输入详细地址" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item label="用户状态" name="status" class="flex-1">
          <a-radio-group v-model:value="formData.status" name="status">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="排序"
          name="sort"
          class="flex-1"
          :rules="{ required: true, message: '请输入排序', trigger: 'blur' }"
        >
          <a-input-number v-model:value="formData.sort" :max="9999" />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item label="简介" name="intro" class="flex-1">
          <a-textarea v-model:value="formData.intro" placeholder="请输入简介" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item label="备注" name="note" class="flex-1">
          <a-textarea v-model:value="formData.note" placeholder="请输入备注" allow-clear />
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <span class="dialog-footer">
        <a-button @click="dialogClose">取消</a-button>
        <a-button :loading="subLoading" type="primary" @click="submit"> 确定 </a-button>
      </span>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { getUserDetail, userAdd, userUpdate } from '@/api/system/user';
  import UploadImg from '@/components/Upload/Image.vue';
  import { upload } from '@/api/common';
  import { Cropper } from '@/components/Cropper';
  import chinaArea from '@/components/ChinaArea/index.vue';
  import type { FormInstance } from 'ant-design-vue';
  import { ref, onMounted, reactive, shallowRef } 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 { message } from 'ant-design-vue';
  import { useLockFn } from '@/utils/useLockFn';
  import { useUserStore } from '@/store/modules/user';

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

  /**
   * 定义参数变量
   */
  const emit = defineEmits(['success', 'update:visible']);
  const uploadHeaders = reactive({
    authorization: useUserStore().getToken,
  });
  const formRef = shallowRef<FormInstance>();

  /**
   * 定义接收的参数
   */
  const formData = reactive({
    id: 0,
    avatarName: '',
    email: '',
    username: '',
    realname: '',
    mobile: '',
    gender: 1,
    roles: [],
    deptId: undefined,
    levelId: undefined,
    positionId: undefined,
    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();
  };

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    emit('update:visible', false);
  };

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

  /**
   * 设置表单数据
   * @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 = async () => {
    await formRef.value?.validate();
    props.userId ? await userUpdate(formData) : await userAdd(formData);
    message.success('操作成功');
    emit('update:visible', false);
    emit('success');
  };

  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

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

  function uploadChange(data: string[]) {
    formData.avatar = data.fileUrl;
    formData.avatarName = data.fileName;
  }
  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 });
    }
  });
</script>
