import { apiConfigFunc, camelCaseString, pushMessageFunc } from '/@/utils/event/design';
import { execute } from '/@/api/liteflow';
import { addLog } from '/@/api/system/log';
import { RuleProcessExecute } from '/@/api/ruleProcess';
import { AssignmentTypeToRuleType } from '/@/api/ruleProcess/model';

export enum EventType {
  CREATE = 0, //初始化表单
  GET, // 获取表单数据
  LOAD, //加载表单
  SUBMIT, //提交表单
}
//初始化表单
export async function createFormEvent(
  formEventConfig,
  formModels,
  formRef,
  schemas,
  isCustomForm = false,
  menuName = '',
  formId = '',
) {
  try {
    if (
      formEventConfig &&
      formEventConfig[EventType.CREATE] &&
      Array.isArray(formEventConfig[EventType.CREATE])
    ) {
      await executeFormEvent(
        formEventConfig[EventType.CREATE],
        formModels,
        formRef,
        schemas,
        isCustomForm,
        menuName,
        formId,
      );
    }
  } catch (error) {}
}

//获取表单数据
export async function getFormDataEvent(
  formEventConfig,
  formModels,
  formRef,
  schemas,
  isCustomForm = false,
  menuName = '',
  formId = '',
) {
  try {
    if (
      formEventConfig &&
      formEventConfig[EventType.GET] &&
      Array.isArray(formEventConfig[EventType.GET])
    ) {
      await executeFormEvent(
        formEventConfig[EventType.GET],
        formModels,
        formRef,
        schemas,
        isCustomForm,
        menuName,
        formId,
      );
    }
  } catch (error) {}
}

//加载表单
export async function loadFormEvent(
  formEventConfig,
  formModels,
  formRef,
  schemas,
  isCustomForm = false,
  menuName = '',
  formId = '',
) {
  try {
    if (
      formEventConfig &&
      formEventConfig[EventType.LOAD] &&
      Array.isArray(formEventConfig[EventType.LOAD])
    ) {
      await executeFormEvent(
        formEventConfig[EventType.LOAD],
        formModels,
        formRef,
        schemas,
        isCustomForm,
        menuName,
        formId,
      );
    }
  } catch (error) {}
}

//提交表单
export async function submitFormEvent(
  formEventConfig,
  formModels,
  formRef,
  schemas,
  isCustomForm = false,
  menuName = '',
  formId = '',
) {
  try {
    if (
      formEventConfig &&
      formEventConfig[EventType.SUBMIT] &&
      Array.isArray(formEventConfig[EventType.SUBMIT])
    ) {
      await executeFormEvent(
        formEventConfig[EventType.SUBMIT],
        formModels,
        formRef,
        schemas,
        isCustomForm,
        menuName,
        formId,
      );
    }
  } catch (error) {}
}

export async function executeFormEvent(
  formEventConfig,
  formModel,
  formRef,
  schemas,
  isCustomForm = false,
  menuName,
  formId,
) {
  if (!formEventConfig.length) return;
  formEventConfig.map((x) => {
    x.nodeInfo?.processEvent?.map(async (config) => {
      const params = {
        category: '6',
        method: menuName,
        operation: '',
      };
      if (config.operateType === 'api') {
        const info = `【${x.text}】 - 【执行API】 - 【${config.operateConfig.path}】 - `;
        try {
          await apiConfigFunc(config.operateConfig, isCustomForm, formModel);
          params.operation = info.concat('【成功】');
        } catch (err) {
          params.operation = info.concat('【失败】');
        }
      } else if (config.operateType === 'liteflow') {
        try {
          await execute(config.operateConfig, formModel);
          params.operation = `【${x.text}】 - 【执行规则引擎】 - 【${config.operateName}】`;
        } catch (error) {}
      } else if (config.operateType === 'ruleProcess') {
        try {
          if (config.ruleConfig.id) {
            let processParamConfigs = [];
            if (
              config.ruleConfig.processParamConfigs &&
              Array.isArray(config.ruleConfig.processParamConfigs) &&
              config.ruleConfig.processParamConfigs.length > 0
            ) {
              processParamConfigs = config.ruleConfig.processParamConfigs.map((item2) => {
                if (item2.assignmentType == AssignmentTypeToRuleType.FORM) {
                  const temp = JSON.parse(item2.assignmentValue);
                  const fild = !isCustomForm
                    ? temp['bindField']!
                    : camelCaseString(temp['bindField'])!;
                  item2.assignmentValue = formModel[fild];
                }
                return item2;
              });
            }
            await RuleProcessExecute(config.ruleConfig.id, processParamConfigs);
          }
        } catch (error) {}
      } else if (config.operateType === 'js') {
        try {
          const operateConfig =
            typeof config.operateConfig === 'string' ? config.operateConfig : '';
          const event = new Function('schema', 'formModel', 'formActionType', operateConfig);
          event(schemas, formModel, formRef);
          params.operation = `【${x.text}】 - 【执行JS】`;
        } catch (error) {}
      } else if (config.operateType === 'pushMessage') {
        try {
          //推送消息
          await pushMessageFunc(config.operateConfig, isCustomForm, formModel, formId);
        } catch (error) {}
      }
      if (x.isLogRecord) {
        try {
          await addLog(params);
        } catch (error) {}
      }
    });
  });
}
