<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 { getVxePopupContainer } from '@vben/utils';

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

import { useVbenForm } from '#/adapter/form';
import { apiDetail } from '#/api/hr/employeeFlow';
import { applyEntry } from '#/api/hr/employeeInfo';
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: 'entryDate',
    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 [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const applyModalApi = shallowRef<ExtendedModalApi | null>(null);

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

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

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.EmployeeApplyBo & {
      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);
    }
    await formApi.setValues(data);
    await markInitialized();

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

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

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

// /**
//  * 暂存/提交 提取通用逻辑
//  */
// async function handleSaveOrUpdate() {
//   const { valid } = await formApi.validate();
//   if (!valid) {
//     throw new Error('表单验证失败');
//   }
//   const data = await formApi.getValues<EmployeeInfoApi.EmployeeApplyBo>();
//   return await applyEntry(data);
// }

// /**
//  * 暂存 草稿状态
//  */
// async function handleTempSave() {
//   modalApi.lock();
//   try {
//     await handleSaveOrUpdate();
//     resetInitialized();
//     emit('success');
//     modalApi.close();
//   } catch (error) {
//     console.error(error);
//   } 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>
