<script lang="ts" setup>
import type { ExtendedModalApi } from '@vben/common-ui';

import type { VbenFormSchema } from '#/adapter/form';
import type { EmployeeInfoApi } from '#/api/hr/employeeModel';

import { computed, ref, shallowRef } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { apiDetail, initByEmployeeId } from '#/api/hr/employeeFlow';
import { applyRegular } from '#/api/hr/employeeInfo';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { useHrFlowHook } from '../useHrFlowHook';

const emit = defineEmits<{
  success: [];
}>();
const isUpdate = ref(false);

const formSchema: VbenFormSchema[] = [
  {
    label: '主键',
    fieldName: 'id',
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    label: '员工id',
    fieldName: 'employeeId',
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    component: 'Input',
    fieldName: 'applyCode',
    label: '申请编号',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    disabled: true,
  },
  {
    component: 'Input',
    fieldName: 'name',
    label: '姓名',
    disabled: true,
  },
  {
    component: 'Input',
    fieldName: 'deptName',
    label: '部门',
    disabled: true,
  },
  // {
  //   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: 'Input',
  //   fieldName: 'contractEntity',
  //   label: '合同主体',
  //   rules: 'required',
  // },
  // {
  //   component: 'Input',
  //   // componentProps: {
  //   //   buttonStyle: 'solid',
  //   //   optionType: 'button',
  //   // },
  //   fieldName: 'contractSigningStatus',
  //   label: '合同签订情况',
  //   rules: 'required',
  // },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'regularizationDate',
    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: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_YES_NO),
    },
    fieldName: 'hasEmployerInsurancePaid',
    label: '是否缴纳雇主险',
    // rules: 'required',
  },
  // {
  //   component: 'Input',
  //   fieldName: 'dictType',
  //   label: '字典类型',
  //   rules: 'required',
  // },
  // {
  //   component: 'Input',
  //   fieldName: 'description',
  //   label: '描述',
  //   rules: 'required',
  // },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '申请备注',
    formItemClass: 'items-start',
  },
];
const applyModalApi = shallowRef<ExtendedModalApi | null>(null);

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

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

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  confirmText: '提交申请',
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    let data = modalApi.getData() as EmployeeInfoApi.EmployeeApplyBaseBo & {
      applyModalApi: ExtendedModalApi;
    };
    applyModalApi.value = data.applyModalApi;
    isUpdate.value = !!data?.id;
    if (isUpdate.value && data.id) {
      updateForm(isUpdate.value);
      data = await apiDetail(data.id);
      updateDataInfo(data);
    } else {
      data = await initByEmployeeId('4', data.employeeId!);
    }
    await formApi.setValues(data);
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

const { handleTempSave, onSubmitFunc, updateDataInfo, updateForm } =
  useHrFlowHook(formApi, modalApi, applyRegular, () => {
    resetInitialized();
    emit('success');
  });

function onSubmit() {
  onSubmitFunc(applyModalApi.value);
}

// function updateDataInfo(data: EmployeeInfoApi.EmployeeApplyBaseBo) {
//   if (data.auditLogList && data.auditLogList.length > 0) {
//     data.auditLogList.map((t) => {
//       if (t && t.auditField) {
//         (data as any)[t.auditField] = t.afterVal;
//       }
//       return t;
//     });
//   }
// }
// function updateForm(update: boolean) {
//   formApi.updateSchema([
//     {
//       dependencies: {
//         show: () => update,
//         triggerFields: [''],
//       },
//       fieldName: 'applyCode',
//     },
//   ]);
// }

// async function onSubmit() {
//   const { valid } = await formApi.validate();
//   if (valid) {
//     modalApi.lock();
//     const data =
//       await formApi.getValues<EmployeeInfoApi.EmployeeRegularApplyBo>();
//     try {
//       await applyRegular(data);
//       resetInitialized();
//       emit('success');
//       modalApi.close();
//     } finally {
//       modalApi.unlock();
//     }
//   }
// }

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

const getModalTitle = computed(() =>
  isUpdate.value ? '修改转正申请' : '转正申请',
);
</script>
<template>
  <BasicModal :title="getModalTitle">
    <BasicForm class="mx-4" />
    <template #center-footer>
      <Button @click="handleTempSave">暂存</Button>
    </template>
  </BasicModal>
</template>
