import type { ExtendedFormApi, ExtendedModalApi } from '@vben/common-ui';

import type { EmployeeInfoApi } from '#/api/hr/employeeModel';
import type { StartWorkFlowReqData } from '#/api/workflow/task/model';

import { startWorkFlow } from '#/api/workflow/task';

export function useHrFlowHook(
  formApi: ExtendedFormApi,
  modalApi: ExtendedModalApi,
  applyFunc: <T extends EmployeeInfoApi.EmployeeApplyBaseBo>(
    data: T,
  ) => Promise<EmployeeInfoApi.EmployeeApplyBaseBo>,
  callback: () => void,
) {
  /**
   * 暂存/提交 提取通用逻辑
   */
  async function handleSaveOrUpdate() {
    const { valid } = await formApi.validate();
    if (!valid) {
      throw new Error('表单验证失败');
    }
    const data = await formApi.getValues<EmployeeInfoApi.EmployeeApplyBaseBo>();
    return await applyFunc(data);
  }

  /**
   * 暂存 草稿状态
   */
  async function handleTempSave() {
    modalApi.lock();
    try {
      await handleSaveOrUpdate();
      callback();
      // resetInitialized();
      // emit('success');
      modalApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      modalApi.unlock();
    }
  }

  async function onSubmitFunc(applyModelApi: ExtendedModalApi | null) {
    modalApi.lock();
    try {
      const applyResp = await handleSaveOrUpdate();
      initAndStartFlow(applyResp, applyModelApi);
      callback();
      // resetInitialized();
      // emit('success');
      modalApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      modalApi.unlock();
    }
  }

  async function initAndStartFlow(
    applyResp: EmployeeInfoApi.EmployeeApplyBaseBo,
    applyModelApi: ExtendedModalApi | null,
  ) {
    // 启动流程
    const taskVariables = {
      leaveDays: applyResp.name,
      userList: [applyResp.employeeId],
    };
    // const formValues = await formApi.getValues();
    // const flowCode = formValues?.flowType ?? 'leave1';
    const startWorkFlowData: StartWorkFlowReqData = {
      businessId: applyResp.id,
      flowCode: applyResp.flowCode || 'hrEntryFlow',
      variables: taskVariables,
      flowInstanceBizExtBo: {
        businessTitle: '申请',
        businessCode: applyResp.applyCode,
      },
    };
    const { taskId } = await startWorkFlow(startWorkFlowData);
    // 打开窗口
    applyModelApi?.setData({
      taskId,
      taskVariables,
      variables: {},
    });
    applyModelApi?.open();
  }

  function updateDataInfo(
    data: EmployeeInfoApi.EmployeeApplyBo,
    mapDict?: Record<string, string>,
  ) {
    if (data.auditLogList && data.auditLogList.length > 0) {
      if (mapDict) {
        data.auditLogList.map((t) => {
          if (t && t.auditField) {
            // 使用中间变量进行类型检查
            const targetField = mapDict?.[t.auditField] ?? t.auditField;
            if (targetField) {
              (data as any)[targetField] = t.afterVal;
            }
          }
          return t;
        });
      } else {
        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',
      },
    ]);
  }

  return {
    handleTempSave,
    onSubmitFunc,
    updateDataInfo,
    updateForm,
  };
}
