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

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

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

import { HrDictEnum } from '../dict-enum';
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',
    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: 'Input',
    fieldName: 'name',
    label: '姓名',
    disabled: true,
  },
  {
    component: 'Input',
    fieldName: 'oldDeptName',
    label: '现部门',
    disabled: true,
  },
  {
    component: 'ApiTreeSelect',
    componentProps: (formModel) => ({
      api: async () => {
        const deptArray = await treeList();
        // const deptTree = genDeptTree(deptArray);
        addFullName(deptArray, 'label', ' / ');
        return 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];
      },
      getVxePopupContainer,
      class: 'w-full',
      treeLine: { showLeafIcon: false },
      treeIcon: false,
      // 筛选的字段
      treeNodeFilterProp: 'label',
      // 选中后显示在输入框的值
      treeNodeLabelProp: 'fullName',
      // fieldNames: { label: 'label', value: 'id' },
      labelField: 'label',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'id',
      childrenField: 'children',
    }),
    fieldName: 'deptId',
    label: '新的部门',
    rules: 'selectRequired',
  },
  {
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      getVxePopupContainer,
    },
    fieldName: 'transferDate',
    label: '调配时间',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'performanceRatio',
    label: '绩效比例',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'staffingLocation',
    label: '编制所在地',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'costOfDept',
    label: '成本费用所属',
    // rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      options: getDictOptions(HrDictEnum.HR_COST_TYPE),
    },
    fieldName: 'costType',
    label: '成本费用细分',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'internalResume',
    label: '内部个人履历',
    // rules: 'required',
  },
  // {
  //   component: 'Select',
  //   componentProps: {
  //     getVxePopupContainer,
  //     placeholder: '请先选择一级部门',
  //   },
  //   fieldName: 'secondLevelDepartment',
  //   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: 90,
  },
  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.EmployeeTransferApplyBo & {
      applyModalApi: ExtendedModalApi;
    };
    applyModalApi.value = data.applyModalApi;
    isUpdate.value = !!data?.id;
    if (isUpdate.value && data.id) {
      updateForm(isUpdate.value);
      data = await apiDetail(data.id);
      data.oldDeptName = data.deptName;
      updateDataInfo(data);
    } else {
      data = await initByEmployeeId('5', data.employeeId!);
    }
    await formApi.setValues(data);
    await markInitialized();

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

const { handleTempSave, onSubmitFunc, updateDataInfo, updateForm } =
  useHrFlowHook(formApi, modalApi, applyTransfer, () => {
    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.EmployeeTransferApplyBo>();
//     try {
//       await applyTransfer(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>
