<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="1000"
    :closeOnOverlayClick="false"
    attach="body"
    @close="emit('update:visible', false)"
    @opened="dialogOpened"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" labelWidth="120px">
      <t-row :gutter="[0, 20]">
        <t-col :span="4">
          <t-form-item label="人员档案编号">
            <span v-if="isEdit">{{ formData.code }}</span>
            <span v-else>系统生成</span>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="姓名" name="name">
            <t-input v-model="formData.name"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="身份证号" name="identity">
            <t-input
              v-model="formData.identity"
              @change="identityChange"
            ></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="性别" name="gender">
            <t-select v-model="formData.gender">
              <t-option
                v-for="(val, key) in GENDER_TYPE"
                :key="key"
                :label="val"
                :value="key"
              ></t-option>
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="学历" name="education">
            <t-select v-model="formData.education">
              <t-option
                v-for="(val, key) in EDUCATION_TYPE"
                :key="key"
                :label="val"
                :value="key"
              ></t-option>
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="手机号" name="mobileNumber">
            <t-input v-model="formData.mobileNumber"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="8">
          <t-form-item label="常住区域" name="city">
            <select-area
              v-model="areaInfo"
              value-type="full"
              @change="areaChange"
            ></select-area>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="电子邮箱" name="email">
            <t-input v-model="formData.email"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="上传照片" name="basePhotoPath">
            <t-upload
              ref="uploadRef"
              v-model="photos"
              theme="image"
              tips="请上传近期清晰免冠一寸登记照，图片格式：JPEG、JPG、PNG格式，文件大小不超过2M，推荐尺寸大小：295*412，上传不符合要求的照片将影响现场服务人员正常的打卡签到。"
              accept="image/jpg,image/jpeg,image/png"
              :locale="{
                triggerUploadText: {
                  image: '请选择图片',
                },
              }"
              :size-limit="{ size: 2, unit: 'MB' }"
              :request-method="requestMethod"
              @change="fileChange"
            >
            </t-upload>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="所属供应商" name="supplierId">
            <select-supplier
              v-model="formData.supplierId"
              type="HUMAN"
            ></select-supplier>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="入档时间" name="archivesTime">
            <t-date-picker
              v-model="formData.archivesTime"
              value-type="time-stamp"
              enable-time-picker
              format="YYYY/MM/DD HH:mm"
              :time-picker-props="{ format: 'HH:mm' }"
            />
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="认证项目角色" name="roleIds">
            <t-checkbox-group v-model="formData.roleIds" :max="1">
              <t-checkbox
                v-for="item in roleList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></t-checkbox>
            </t-checkbox-group>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="认证时间">
            <t-date-picker
              v-model="formData.authenticationTime"
              value-type="time-stamp"
              enable-time-picker
              format="YYYY/MM/DD HH:mm"
              :time-picker-props="{ format: 'HH:mm' }"
              :disable-date="{ after: formData.examEndTime || undefined }"
            />
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="认证成绩">
            <t-input-number
              v-model="formData.authenticationScore"
              theme="column"
              :decimalPlaces="1"
              :max="1000"
              :min="0"
              style="width: 100px"
            ></t-input-number>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item label="认证有效期">
            <t-date-picker
              v-model="formData.authenticationValidTime"
              value-type="time-stamp"
              enable-time-picker
              format="YYYY/MM/DD HH:mm"
              :time-picker-props="{ format: 'HH:mm' }"
              :disable-date="{
                before: formData.authenticationTime || undefined,
              }"
            />
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="备注">
            <t-textarea v-model="formData.remark" :maxlength="100"></t-textarea>
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="AddPersonFileDialog">
import { ref, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import useClearDialog from '@/hooks/useClearDialog';
import useAuthenRole from '@/hooks/useAuthenRole';
import { personFilesEditApi } from '@/api/resource-guard';
import { fileUploadApi } from '@/api/user';
import { GENDER_TYPE, EDUCATION_TYPE } from '@/config/constants';
import { getFileMD5 } from '@/utils/crypto';

const emit = defineEmits(['update:visible']);
const props = defineProps({
  visible: Boolean,
  curRow: Object,
});

const formRef = ref(null);
const title = computed(() => {
  return (isEdit.value ? '编辑' : '新增') + '人员档案';
});
let areaInfo = ref(['', '']);
let photos = ref([]);

const { roleList, getRoleList } = useAuthenRole();

const { formData, isEdit } = useClearDialog(
  {
    code: '',
    name: '',
    province: '',
    city: '',
    area: '',
    identity: '',
    gender: '',
    education: '',
    mobileNumber: '',
    email: '',
    basePhotoPath: '',
    supplierId: '',
    archivesTime: '',
    roleIds: [],
    authenticationTime: '',
    authenticationScore: '',
    authenticationValidTime: '',
    remark: '',
  },
  props,
  formRef,
  () => {
    for (let key in formData) {
      formData[key] = props.curRow[key];
    }
    formData.id = props.curRow.userArchivesId;
    formData.roleIds = props.curRow.roleInfoList.map((item) => item.roleId);
  }
);

const rules = {
  name: [
    { required: true, message: '姓名必填', type: 'error', trigger: 'change' },
    {
      max: 50,
      message: '至多50个字',
      type: 'error',
      trigger: 'change',
    },
  ],
  city: [
    {
      required: true,
      message: '常住区域必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  identity: [
    {
      required: true,
      message: '身份证号必填',
      type: 'error',
      trigger: 'change',
    },
    {
      idcard: true,
      message: '请输入正确的身份证号码',
      type: 'error',
      trigger: 'change',
    },
  ],
  gender: [
    {
      required: true,
      message: '性别必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  education: [
    {
      required: true,
      message: '学历必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  mobileNumber: [
    {
      required: true,
      message: '手机号必填',
      type: 'error',
      trigger: 'change',
    },
    {
      telnumber: true,
      message: '请输入合适的手机号码',
      type: 'error',
      trigger: 'change',
    },
  ],
  email: [
    {
      required: true,
      message: '电子邮箱必填',
      type: 'error',
      trigger: 'change',
    },
    {
      email: true,
      message: '请输入正确的邮箱地址',
      type: 'error',
      trigger: 'change',
    },
  ],
  basePhotoPath: [
    {
      required: true,
      message: '照片必传',
      type: 'error',
      trigger: 'change',
    },
  ],
  supplierId: [
    {
      required: true,
      message: '所属供应商必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  archivesTime: [
    {
      required: true,
      message: '入档时间必填',
      type: 'error',
      trigger: 'change',
    },
  ],
  roleIds: [
    {
      required: true,
      message: '认证项目角色必选',
      type: 'error',
      trigger: 'change',
    },
  ],
};

const requestMethod = async (file) => {
  const md5Str = await getFileMD5(file.raw);
  let data = new FormData();
  data.append('file', file.raw);
  data.append('md5', md5Str);
  data.append('type', 'FILE');

  const res = await fileUploadApi(data).catch(() => {});
  if (!res) return { status: 'fail', error: '上传失败' };

  formData.basePhotoPath = res.url;
  return { status: 'success', response: { url: res.previewUrl } };
};

const identityChange = () => {
  if (!formData.identity || formData.identity.length !== 18) return;

  const genderCode = formData.identity[16] * 1;

  formData.gender = genderCode % 2 ? 'MAN' : 'WOMAN';
};

const areaChange = (data) => {
  formData.province = data[0];
  formData.city = data[1];
  formData.area = data[2];
};

const fileChange = (data) => {
  if (!data.length) formData.basePhotoPath = '';
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  const res = await personFilesEditApi(formData).catch(() => {});
  if (!res) return;

  MessagePlugin.success('保存成功');
  emit('update:visible', false);
  emit('success');
};

const dialogOpened = async () => {
  if (!props.curRow) {
    areaInfo.value = ['', '', ''];
    photos.value = [];
    formData.code = undefined;
  } else {
    areaInfo.value = [formData.province, formData.city, formData.area];
    photos.value = props.curRow.basePhotoPreviewPath
      ? [{ url: props.curRow.basePhotoPreviewPath }]
      : [];
  }
  getRoleList();
};
</script>
