<template>
  <el-dialog
    v-model="props.visible"
    :title="props.userId ? '编辑' : '新增'"
    width="750"
    :close-on-click-modal="false"
    :before-close="dialogClose"
  >
    <el-form ref="formRef" :model="formData" label-width="84px">
      <el-form-item
        label="头像"
        prop="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="20"
                    :cropper="true"
                    v-model:image-url="formData.avatar">
          <template v-slot:tip>支持扩展名: jpg png jpeg;文件大小不超过20M</template>
        </UploadImg> -->
        <Cropper
          ref="cropperCircled"
          :src="formData.avatar"
          :uploadApi="upload"
          name="user"
          title="头像上传"
          @uploadSuccess="uploadSuccess"
        >
          <template #avatar> </template>
        </Cropper>
      </el-form-item>
      <div class="flex">
        <el-form-item
          label="账号"
          prop="username"
          class="flex-1"
          :rules="{ required: true, message: '请输入账号', trigger: 'blur' }"
        >
          <el-input
            :disabled="props.userId"
            v-model="formData.username"
            placeholder="请输入账号"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          class="flex-1"
          :rules="{ required: props.userId ? false : true, message: '请输入密码', trigger: 'blur' }"
        >
          <el-input
            v-model.trim="formData.password"
            show-password
            autocomplete="new-password"
            clearable
            placeholder="请输入密码"
          />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item
          label="名称"
          prop="realname"
          class="flex-1"
          :rules="{ required: true, message: '请输入名称', trigger: 'blur' }"
        >
          <el-input v-model="formData.realname" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="性别" prop="gender" class="flex-1">
          <el-radio-group v-model="formData.gender" name="gender">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
            <el-radio :value="3">保密</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item
          label="角色"
          prop="roles"
          class="flex-1"
          :rules="{ required: true, message: '请选择角色', trigger: 'change' }"
        >
          <el-select
            v-model="formData.roles"
            multiple
            class="flex-1"
            clearable
            placeholder="请选择角色"
          >
            <el-option
              v-for="(item, index) in optionData.roleList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门"
          prop="deptId"
          class="flex-1"
          :rules="{ required: true, message: '请选择部门', trigger: 'change' }"
        >
          <el-tree-select
            v-model="formData.deptId"
            :data="optionData.deptList"
            :render-after-expand="false"
            :props="{ value: 'id', label: 'name' }"
          />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item
          label="职级"
          prop="levelId"
          class="flex-1"
          :rules="{ required: true, message: '请选择职级', trigger: 'change' }"
        >
          <el-select v-model="formData.levelId" class="flex-1" clearable placeholder="请选择职级">
            <el-option
              v-for="(item, index) in optionData.levelList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="岗位"
          prop="positionId"
          class="flex-1"
          :rules="{ required: true, message: '请选择岗位', trigger: 'change' }"
        >
          <el-select
            v-model="formData.positionId"
            class="flex-1"
            clearable
            placeholder="请选择岗位"
          >
            <el-option
              v-for="(item, index) in optionData.positionList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item
          label="手机号码"
          prop="mobile"
          class="flex-1"
          :rules="[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: rule.validatePhone, trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" clearable />
        </el-form-item>
        <el-form-item
          label="邮箱地址"
          prop="email"
          class="flex-1"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确邮箱地址', trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.email" placeholder="请输入邮箱地址" clearable />
        </el-form-item>
      </div>

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

  const formRef = shallowRef<FormInstance>();
  import { useLockFn } from '@/utils/useLockFn';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserStore } from '@/store/modules/user';
  const globSetting = useGlobSetting();

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    userId: {
      type: Number,
      required: true,
      default: 0,
    },
  });
  const cropperCircled = ref();
  const emit = defineEmits(['success', 'update:visible']);

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: 0,
    avatarName: '',
    email: '',
    username: '',
    realname: '',
    mobile: '',
    gender: 1,
    roles: [],
    deptId: '',
    levelId: '',
    positionId: '',
    address: '',
    status: 1,
    note: '',
    intro: '',
    sort: 0,
    city: [],
    avatar: '',
    password: '',
    passwordConfirm: '',
  });
  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?.validateField('avatar');
  };

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

  /**
   * 设置表单数据
   * @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) {
        if (key == 'city') {
          if (data.city.length > 0) {
            formData[key] = [
              parseInt(data.city[0]),
              parseInt(data.city[1]),
              parseInt(data.city[2]),
              parseInt(data.city[3]),
            ];
          } else {
            formData[key] = '';
          }
        } else {
          formData[key] = data[key];
        }
      }
    }
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    await formRef.value?.validate();
    props.userId ? await userUpdate(formData) : await userAdd(formData);
    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>
