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

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 { apiAdd, apiDetail, apiUpdate } from '#/api/hr/partTimeInfo';
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 loading = ref(false);
const isUpdate = ref(false);

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
    label: 'id',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'plate',
    label: '板块',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'firstLevelDepartment',
    label: '一级部门',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'secondLevelDepartment',
    label: '二级部门',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'thirdLevelDepartment',
    label: '三级部门',
  },
  {
    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: 'position',
    label: '主岗位',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_POSITION_TYPE),
      getVxePopupContainer,
    },
    fieldName: 'positionType',
    label: '岗位类型',
    // rules: 'selectRequired',
  },
  {
    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: 'ossId',
    label: '照片',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'phoneNumber',
    label: '手机号码',
    rules: z
      .string()
      .regex(/^1[3-9]\d{9}$/, { message: '请输入正确的联系电话' }),
  },
  {
    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: 'homeAddress',
    label: '家庭地址',
    rules: 'required',
  },
  // {
  //   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: 'householdRegistrationAddress',
  //   label: '户口所在地',
  //   // rules: 'required',
  // },
  {
    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: '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: '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: 'entryDate',
    label: '入职时间',
    // rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(HrDictEnum.HR_EMPLOYMENT_FORM),
    },
    defaultValue: '4',
    fieldName: 'employmentForm',
    label: '用工形式',
    // rules: 'selectRequired',
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '合同信息',
    }),
  },

  // {
  //   component: 'Input',
  //   fieldName: 'partTimeFlag',
  //   label: '是否兼职',
  //   rules: 'required',
  // },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_YES_NO),
    },
    fieldName: 'partTimeAgreement',
    label: '签订兼职协议',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'agreementEntity',
    label: '协议主体',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'agreementPeriod',
    label: '协议期限',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'agreementStartDate',
    label: '协议开始时间',
    // rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'agreementEndDate',
    label: '协议截止时间',
    // rules: 'required',
  },
  {
    component: 'Divider',
    componentProps: {
      orientation: 'center',
    },
    fieldName: 'divider1',
    formItemClass: 'col-span-2',
    hideLabel: true,
    renderComponentContent: () => ({
      default: () => '其他信息',
    }),
  },
  {
    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: 'introducerRelation',
    label: '介绍人关系',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'salaryLocation',
    label: '工资发放地',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'costOfDept',
    label: '成本费用所属',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'remarks',
    label: '备注',
    // rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-1',
    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',
    },
  ]);
}

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();
    if (isUpdate.value && id) {
      const data = await apiDetail(id);
      data.ossId = data.ossId ? `${data.ossId}` : data.ossId;
      await formApi.setValues(data);
    } else {
      await formApi.resetForm();
    }
    await markInitialized();
    drawerApi.drawerLoading(false);
    loading.value = false;
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<PartTimeInfoApi.PartTimeInfo>();
    try {
      await (isUpdate.value ? apiUpdate(data) : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

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

const getDrawerTitle = computed(() =>
  isUpdate.value ? '修改兼职员工信息' : '新增兼职员工信息',
);
</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>
