<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { EmployeeInfoApi } from '#/api/hr/employeeModel';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { addFullName, getVxePopupContainer } from '@vben/utils';

import { Skeleton } from 'ant-design-vue';

import { useVbenForm, z } from '#/adapter/form';
import { treeList } from '#/api/auth/dept';
import { apiDetail } from '#/api/hr/employeeInfo';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { idCardSchema } from '../../../utils/validator';
import { HrDictEnum } from '../dict-enum';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<EmployeeInfoApi.Employee>();
const loading = ref(false);
const isUpdate = ref(false);

// function genDeptTree(deptList: SysDeptApi.Dept[]): SysDeptApi.Dept[] {
//   const top: SysDeptApi.Dept = {
//     children: [],
//     id: 0,
//     name: '顶级部门',
//     label: '顶级部门',
//     parentId: -1,
//     nodePath: '/',
//     orderNum: 0,
//     status: 1,
//   };
//   deptList.forEach((item) => {
//     if (item.parentId === 0) {
//       top.children?.push(item);
//     }
//   });
//   return [top];
// }

const formSchema: VbenFormSchema[] = [
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '部门信息',
    }),
  },
  {
    component: 'TreeSelect',
    // 在onOpenChange里更新 这里不需要默认的componentProps
    defaultValue: undefined,
    fieldName: 'deptId',
    label: '所属部门',
    rules: 'selectRequired',
  },
  {
    component: 'Input',
    fieldName: 'employeeNo',
    label: '工号',
    // rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'jobLevel',
    label: '职级',
    rules: z.number().gt(0).lt(10).optional(),
  },
  {
    component: 'Input',
    fieldName: 'position',
    label: '主岗位',
    // rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      options: getDictOptions(HrDictEnum.HR_SEQUENCE),
    },
    fieldName: 'sequence',
    label: '序列',
    // rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      getVxePopupContainer,
      options: getDictOptions(HrDictEnum.HR_POSITION_TYPE),
    },
    fieldName: 'positionType',
    label: '岗位类型',
    // rules: 'selectRequired',
  },
  {
    component: 'TreeSelect',
    // 在onOpenChange里更新 这里不需要默认的componentProps
    defaultValue: undefined,
    fieldName: 'partDeptId',
    label: '兼职部门',
  },
  {
    component: 'Input',
    fieldName: 'partTimePosition',
    label: '兼职岗位',
    // rules: 'required',
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '员工信息',
    }),
  },
  {
    component: 'Input',
    fieldName: 'name',
    label: '姓名',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_USER_SEX),
    },
    defaultValue: '1',
    fieldName: 'gender',
    label: '性别',
    rules: 'required',
  },
  {
    component: 'ImageUpload',
    componentProps: {
      maxCount: 1,
    },
    fieldName: 'photo',
    label: '照片',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'idCardNumber',
    label: '身份证号码',
    rules: idCardSchema,
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'birthDate',
    label: '出生日期',
    rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'age',
    label: '年龄',
    rules: z.number().gt(0, '年龄不能小于0').lt(100, '年龄不能大于100'),
  },
  // {
  //   component: 'Input',
  //   fieldName: 'ageGroup',
  //   label: '年龄段',
  //   rules: 'required',
  // },
  {
    component: 'Input',
    fieldName: 'ethnicity',
    label: '民族',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'nativePlace',
    label: '籍贯',
    // rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_MARITAL_STATUS),
    },
    fieldName: 'maritalStatus',
    label: '婚姻状况',
    // rules: 'selectRequired',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_POLITICAL_STATUS),
    },
    fieldName: 'politicalStatus',
    label: '政治面貌',
    // rules: 'selectRequired',
  },
  {
    component: 'Input',
    fieldName: 'phoneNumber',
    label: '手机号码',
    rules: z
      .string()
      .regex(/^1[3-9]\d{9}$/, { message: '请输入正确的联系电话' }),
  },
  {
    component: 'Input',
    fieldName: 'emergencyContact',
    label: '紧急联系人',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'emergencyContactPhone',
    label: '紧急联系人电话',
    rules: z
      .string()
      .regex(/^1[3-9]\d{9}$/, '请输入正确的手机号码')
      .optional()
      .or(z.literal('')),
  },
  {
    component: 'Input',
    fieldName: 'homeAddress',
    label: '家庭地址',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'householdRegistrationAddress',
    label: '户口所在地',
    // rules: 'required',
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '教育信息',
    }),
  },
  {
    component: 'Input',
    fieldName: 'fulltimeEducation',
    label: '全日制学历',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'fulltimeSchool',
    label: '全日制毕业院校',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'fulltimeMajor',
    label: '全日制专业',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'fulltimeGraduationDate',
    label: '全日制毕业日期',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'fulltimeDegree',
    label: '全日制学位',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'nonFulltimeEducation',
    label: '非全日制学历',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'nonFulltimeSchool',
    label: '非全日制毕业院校',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'nonFulltimeMajor',
    label: '非全日制专业',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'nonFulltimeGraduationDate',
    label: '非全日制毕业日期',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'nonFulltimeDegree',
    label: '非全日制学位',
    // rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_EDUCATION_CATEGORY),
    },
    fieldName: 'educationCategory',
    label: '学历分类',
    formItemClass: 'col-span-2',
    // rules: 'required',
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '职业信息',
    }),
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'workStartDate',
    label: '参加工作时间',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'entryDate',
    label: '入职时间',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'regularizationDate',
    label: '转正时间',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'yearsOfService',
    label: '工龄',
    // rules: 'required',
  },
  // {
  //   component: 'Input',
  //   fieldName: 'yearsOfServiceSegment',
  //   label: '工龄段',
  //   rules: 'required',
  // },
  {
    component: 'Select',
    componentProps: {
      options: getDictOptions(HrDictEnum.HR_EMPLOYEE_TYPE),
    },
    fieldName: 'employeeType',
    label: '员工类型',
    // rules: 'selectRequired',
  },
  {
    component: 'Input',
    fieldName: 'professionalTitle',
    label: '职称情况',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'certificateStatus',
    label: '证书情况',
    formItemClass: 'col-span-2',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'externalResume',
    label: '外部个人履历',
    formItemClass: 'col-span-2',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'internalResume',
    label: '内部个人履历',
    formItemClass: 'col-span-2',
    // rules: 'required',
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '合同信息',
    }),
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_EMPLOYMENT_FORM),
    },
    fieldName: 'employmentForm',
    label: '用工形式',
    // rules: 'selectRequired',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_CONTRACT_FORM),
    },
    fieldName: 'contractForm',
    label: '合同形式',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'contractTerm',
    label: '劳动合同期限',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'contractStartDate',
    label: '劳动合同开始时间',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'contractEndDate',
    label: '劳动合同截止时间',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'contractExpirationReminder',
    label: '合同到期提醒',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'contractEntity',
    label: '合同主体',
    // rules: 'required',
  },
  {
    component: 'Input',
    // componentProps: {
    //   buttonStyle: 'solid',
    //   optionType: 'button',
    // },
    fieldName: 'contractSigningStatus',
    label: '劳动合同签订情况',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'socialSecurityEntity',
    label: '社保主体',
    // rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_YES_NO),
    },
    fieldName: 'hasSocialSecurityPaid',
    label: '是否缴纳社保',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'providentFundEntity',
    label: '公积金主体',
    // rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_YES_NO),
    },
    fieldName: 'hasProvidentFundPaid',
    label: '是否缴纳公积金',
    // rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'probationPeriod',
    label: '试用期(月数)',
    rules: z.number().optional(),
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '其他信息',
    }),
  },
  {
    component: 'Textarea',
    // componentProps: {
    //   buttonStyle: 'solid',
    //   optionType: 'button',
    // },
    fieldName: 'rewardStatus',
    formItemClass: 'col-span-2',
    label: '奖励情况',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    // componentProps: {
    //   buttonStyle: 'solid',
    //   optionType: 'button',
    // },
    fieldName: 'punishmentStatus',
    formItemClass: 'col-span-2',
    label: '处罚情况',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'remarks',
    formItemClass: 'col-span-2',
    label: '备注',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'officePhone',
    label: '办公电话',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'shortLine',
    label: '短线',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'bankCardNumber',
    label: '银行卡号',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'bankName',
    label: '开户行',
    // rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_YES_NO),
    },
    fieldName: 'hasRelativeInCompany',
    label: '是否有亲属关系',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'relativeName',
    label: '亲属姓名',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'introducer',
    label: '介绍人',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'salaryLocation',
    label: '工资发放地',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'performanceRatio',
    label: '绩效比例',
    // rules: 'required',
  },
  // {
  //   component: 'DatePicker',
  //   fieldName: 'resignationDate',
  //   label: '离职时间',
  //   rules: 'required',
  // },
  // {
  //   component: 'Textarea',
  //   fieldName: 'resignationReason',
  //   label: '离职原因',
  //   rules: 'required',
  // },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
      formItemClass: 'col-span-1',
    },
    // formItemClass: 'col-span-2',
    labelWidth: 130,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

async function setupDeptSelect() {
  const deptArray = await treeList();
  // const deptTree = genDeptTree(deptArray);
  addFullName(deptArray, 'label', ' / ');
  formApi.updateSchema([
    {
      componentProps: (formModel) => ({
        treeData: deptArray,
        async onSelect(deptId: number | string, node: Record<string, any>) {
          /** 根据部门Node获取部门等级数组 */
          const result = node.fullName
            .split('/')
            .map((item: string) => item.trim())
            .filter(Boolean);
          /** 变化后需要重新设置部门信息 */
          formModel.plate = result[0];
          formModel.firstLevelDepartment = result[1];
          formModel.secondLevelDepartment = result[2];
          formModel.thirdLevelDepartment = result[3];
        },
        class: 'w-full',
        treeLine: { showLeafIcon: false },
        treeIcon: false,
        // 筛选的字段
        treeNodeFilterProp: 'label',
        // 选中后显示在输入框的值
        treeNodeLabelProp: 'fullName',
        getVxePopupContainer,
        fieldNames: { label: 'label', value: 'id' },
        labelField: 'label',
        showSearch: true,
        treeDefaultExpandAll: true,
        valueField: 'id',
        childrenField: 'children',
      }),
      fieldName: 'deptId',
    },
    {
      componentProps: (formModel) => ({
        treeData: deptArray,
        async onSelect(deptId: number | string, node: Record<string, any>) {
          /** 根据部门Node获取部门等级数组 */
          const result = node.fullName
            .split('/')
            .map((item: string) => item.trim())
            .filter(Boolean);
          /** 变化后需要重新设置部门信息 */
          formModel.partTimePlate = result[0];
          formModel.partTimeFirstDept = result[1];
          formModel.partTimeSecondDept = result[2];
          formModel.partTimeThirdDept = result[3];
        },
        class: 'w-full',
        treeLine: { showLeafIcon: false },
        treeIcon: false,
        // 筛选的字段
        treeNodeFilterProp: 'label',
        // 选中后显示在输入框的值
        treeNodeLabelProp: 'fullName',
        getVxePopupContainer,
        fieldNames: { label: 'label', value: 'id' },
        labelField: 'label',
        showSearch: true,
        treeDefaultExpandAll: true,
        valueField: 'id',
        childrenField: 'children',
      }),
      fieldName: 'partDeptId',
    },
  ]);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);
    loading.value = true;
    const { id } = drawerApi.getData() as { id?: number };
    isUpdate.value = !!id;
    // 初始化
    await setupDeptSelect();
    // console.log('[id]', id);
    if (id) {
      const data = await apiDetail(id);
      formData.value = data;
      await formApi.setValues(formData.value!);
      // await setupDeptLevel2Options(data.firstLevelDepartment);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
    drawerApi.drawerLoading(false);
    loading.value = false;
  },
});

// async function setupDeptLevel2Options(name: string) {
//   const deptNameList: string[] = await selectDeptNamesByParent(name);
//   const options = deptNameList.map((item) => ({
//     label: item,
//     value: item,
//   }));
//   const placeholder = options.length > 0 ? '请选择' : '该部门下暂无岗位';
//   formApi.updateSchema([
//     {
//       componentProps: { options, placeholder },
//       fieldName: 'secondLevelDepartment',
//     },
//   ]);
// }

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<EmployeeInfoApi.Employee>();
    console.log('[data]', data);
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改员工信息' : '新增员工信息',
);
</script>
<template>
  <Drawer class="w-full max-w-[900px]" :title="getDrawerTitle">
    <Skeleton v-if="loading" active />
    <BasicForm v-show="!loading" class="mx-4" />
  </Drawer>
</template>
