import { createVNode } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { regTestProps, requestProps } from '/@/components/Form/src/types/form';
import type { ModalFuncProps } from 'ant-design-vue/lib/modal/Modal';
import { defHttp } from '/@/utils/http/axios';
import { ExecuteType } from '/@/enums/desktop';
import useComplexApiRequest from '/@/views/generator/desktop/hooks/useComplexApiRequest';
import { execute } from '/@/api/liteflow';
import { apiConfigFunc, camelCaseString } from '/@/utils/event/design';
import { useMessage } from '/@/hooks/web/useMessage';
import { useI18n } from '/@/hooks/web/useI18n';
import { RuleProcessExecute } from '/@/api/ruleProcess';
import { AssignmentTypeToRuleType } from '/@/api/ruleProcess/model';
import { apiConfigPageDesignFunc } from './pagetool';
import { useUserStore } from '/@/store/modules/user';

const userStore = useUserStore();
const { pushMessageFunc } = useComplexApiRequest();
const { notification } = useMessage();
const { t } = useI18n();

const regTest = async (regular: regTestProps) => {
  const regExpression = regular.regExpression;
  const testRes = regExpression.test(regular.testValue);
  testRes ? message.success(regular.successMessage) : message.error(regular.errorMessage);
};

const showModal = async (modal: ModalFuncProps) => {
  Modal.confirm({
    title: modal.title,
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { style: 'color:red;' }, modal.content),
    onOk: modal.onOk,
    onCancel: modal.onCancel,
    ...modal,
  });
};
const showMessage = (content: string) => {
  message.info(content);
};
const httpRequest = async (request: requestProps) => {
  if (request.requestType.toLowerCase() === 'get') {
    return defHttp[request.requestType](
      {
        url: request.requestUrl,
        params: request.params,
      },
      {
        errorMessageMode: request.errorMessageMode || 'none',
      },
    );
  } else {
    return defHttp[request.requestType](
      {
        url: request.requestUrl,
        data: request.data,
        params: request.params,
      },
      {
        errorMessageMode: request.errorMessageMode || 'none',
      },
    );
  }
};

const getUserInfo = (info: string) => {
  if (info === 'roleId') {
    return userStore.getUserInfo.roles.length && userStore.getUserInfo.roles[0].id;
  }
  return userStore.getUserInfo[info];
};
//系统表单列表页自定义按钮
export const executeEvent = (setting, api, selectedKeys?, selectedRowsData?) => {
  let flag = true;
  if (setting?.length) {
    setting.forEach(async (item, index) => {
      let msg = t('执行成功');
      if (
        item.operateType == ExecuteType.API &&
        item.operateConfig &&
        item.operateConfig.apiConfig
      ) {
        try {
          const hasFieldParams = item.operateConfig.apiConfig.apiParams.find((par) => {
            return par.tableInfo?.find(
              (info) => info.bindType === 'data' && info.value.includes('bindField'),
            );
          });
          if (!hasFieldParams || (selectedKeys?.length && hasFieldParams)) {
            let data = {};
            if (hasFieldParams) {
              data = await api(selectedKeys[selectedKeys.length - 1]);
            }
            const res = await apiConfigFunc(item.operateConfig.apiConfig, true, data);
            msg = res && typeof res == 'string' ? res : t('执行成功');
            if (index == setting.length - 1) {
              notification.success({
                message: t('提示'),
                description: msg,
              });
            }
          } else {
            notification.error({
              message: t('提示'),
              description: t('请先选择一条数据'),
            });
            flag = false;
          }
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！') + error,
          });
        }
      } else if (
        item.operateType == ExecuteType.RULE &&
        item.operateConfig &&
        item.operateConfig.rule
      ) {
        await execute(item.operateConfig.rule, {});
        if (index == setting.length - 1) {
          notification.success({
            message: t('提示'),
            description: msg,
          });
        }
      } else if (item.operateType == 'ruleProcess' && item.ruleConfig) {
        try {
          if (item.ruleConfig.id) {
            let processParamConfigs = [];
            if (
              item.ruleConfig.processParamConfigs &&
              Array.isArray(item.ruleConfig.processParamConfigs) &&
              item.ruleConfig.processParamConfigs.length > 0
            ) {
              const formModel = selectedRowsData
                ? selectedRowsData[selectedRowsData.length - 1]
                : {};
              processParamConfigs = item.ruleConfig.processParamConfigs.map((item2) => {
                if (item2.assignmentType == AssignmentTypeToRuleType.FORM) {
                  const temp = JSON.parse(item2.assignmentValue);
                  const fild = camelCaseString(temp['bindField'])!;
                  item2.assignmentValue = formModel[fild];
                }

                return item2;
              });
            }
            await RuleProcessExecute(item.ruleConfig.id, processParamConfigs);
            if (index == setting.length - 1) {
              notification.success({
                message: t('提示'),
                description: msg,
              });
            }
          }
        } catch (error) {}
      } else if (
        item.operateType == ExecuteType.JS &&
        item.operateConfig &&
        item.operateConfig.js
      ) {
        const event = new Function('formActionType', `${item.operateConfig.js}`);
        event({
          httpRequest,
          showModal,
          regTest,
          selectedRowsData,
          getUserInfo,
        });
        if (index == setting.length - 1) {
          notification.success({
            message: t('提示'),
            description: msg,
          });
        }
      } else if (
        item.operateType == ExecuteType.PUSH_MESSAGE &&
        item.operateConfig &&
        item.operateConfig.messageConfig
      ) {
        try {
          await pushMessageFunc(item.operateConfig.messageConfig);
          if (index == setting.length - 1) {
            notification.success({
              message: t('提示'),
              description: msg,
            });
          }
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！'),
          });
        }
      }
    });
  }
  return flag;
};
//自定义表单列表页自定义按钮
export const executeCustomEvent = (setting, api, releaseId, selectedKeys?, selectedRowsData?) => {
  let flag = true;
  if (setting?.length) {
    let msg = t('执行成功');
    setting.forEach(async (item, index) => {
      if (
        item.operateType == ExecuteType.API &&
        item.operateConfig &&
        item.operateConfig.apiConfig
      ) {
        try {
          const hasFieldParams = item.operateConfig.apiConfig.apiParams.find((par) => {
            return par.tableInfo?.find(
              (info) => info.bindType === 'data' && info.value.includes('bindField'),
            );
          });
          if (!hasFieldParams || (selectedKeys?.length && hasFieldParams)) {
            let data = {};
            if (hasFieldParams) {
              data = await api({ id: selectedKeys[selectedKeys.length - 1], releaseId });
            }
            const res = await apiConfigFunc(item.operateConfig.apiConfig, false, data);
            msg = res && typeof res == 'string' ? res : t('执行成功');
            if (index == setting.length - 1) {
              notification.success({
                message: t('提示'),
                description: msg,
              });
            }
          } else {
            notification.error({
              message: t('提示'),
              description: t('请先选择一条数据'),
            });
            flag = false;
          }
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！') + error,
          });
        }
      } else if (
        item.operateType == ExecuteType.RULE &&
        item.operateConfig &&
        item.operateConfig.rule
      ) {
        await execute(item.operateConfig.rule, {});
        if (index == setting.length - 1) {
          notification.success({
            message: t('提示'),
            description: msg,
          });
        }
      } else if (item.operateType == 'ruleProcess' && item.ruleConfig) {
        try {
          if (item.ruleConfig.id) {
            let processParamConfigs = [];
            if (
              item.ruleConfig.processParamConfigs &&
              Array.isArray(item.ruleConfig.processParamConfigs) &&
              item.ruleConfig.processParamConfigs.length > 0
            ) {
              const formModel = selectedRowsData
                ? selectedRowsData[selectedRowsData.length - 1]
                : {};
              processParamConfigs = item.ruleConfig.processParamConfigs.map((item2) => {
                if (item2.assignmentType == AssignmentTypeToRuleType.FORM) {
                  const temp = JSON.parse(item2.assignmentValue);
                  const fild = temp['bindField']!;
                  item2.assignmentValue = formModel[fild];
                }

                return item2;
              });
            }
            await RuleProcessExecute(item.ruleConfig.id, processParamConfigs);
            if (index == setting.length - 1) {
              notification.success({
                message: t('提示'),
                description: msg,
              });
            }
          }
        } catch (error) {}
      } else if (
        item.operateType == ExecuteType.JS &&
        item.operateConfig &&
        item.operateConfig.js
      ) {
        const event = new Function('formActionType', `${item.operateConfig.js}`);
        try {
          const res = event({
            httpRequest,
            showModal,
            regTest,
            selectedRowsData,
            getUserInfo,
          });
          if (res.code === 0) {
            if (index == setting.length - 1) {
              notification.success({
                message: t('提示'),
                description: msg,
              });
            }
          } else {
            notification.error({
              message: t('提示'),
              description: t('执行失败！') + res.message,
            });
          }
        } catch (error) {}
      } else if (
        item.operateType == ExecuteType.PUSH_MESSAGE &&
        item.operateConfig &&
        item.operateConfig.messageConfig
      ) {
        try {
          await pushMessageFunc(item.operateConfig.messageConfig);
          if (index == setting.length - 1) {
            notification.success({
              message: t('提示'),
              description: msg,
            });
          }
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！'),
          });
        }
      }
    });
  }
  return flag;
};
//表单弹窗自定义按钮，表格组件和次级表格组件行内按钮，系统表单和自定义表单公用;
export const executeCurFormEvent = (setting, formModel, isCamelCase = false, tableData?) => {
  if (setting?.length) {
    setting.forEach(async (item) => {
      if (
        item.operateType == ExecuteType.API &&
        item.operateConfig &&
        item.operateConfig.apiConfig
      ) {
        try {
          await apiConfigFunc(
            item.operateConfig.apiConfig,
            isCamelCase,
            formModel,
            tableData?.curIndex,
            null,
            tableData?.curParentIndex,
          );
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！') + error,
          });
        }
      } else if (
        item.operateType == ExecuteType.RULE &&
        item.operateConfig &&
        item.operateConfig.rule
      ) {
        await execute(item.operateConfig.rule, {});
      } else if (item.operateType == 'ruleProcess' && item.ruleConfig) {
        try {
          if (item.ruleConfig.id) {
            let processParamConfigs = [];
            if (
              item.ruleConfig.processParamConfigs &&
              Array.isArray(item.ruleConfig.processParamConfigs) &&
              item.ruleConfig.processParamConfigs.length > 0
            ) {
              processParamConfigs = item.ruleConfig.processParamConfigs.map((item2) => {
                if (item2.assignmentType == AssignmentTypeToRuleType.FORM) {
                  const temp = JSON.parse(item2.assignmentValue);
                  const fild = isCamelCase
                    ? camelCaseString(temp['bindField'])!
                    : temp['bindField'];
                  item2.assignmentValue = formModel[fild];
                }

                return item2;
              });
            }
            await RuleProcessExecute(item.ruleConfig.id, processParamConfigs);
          }
        } catch (error) {}
      } else if (
        item.operateType == ExecuteType.JS &&
        item.operateConfig &&
        item.operateConfig.js
      ) {
        try {
          const event = new Function(
            'formActionType',
            'curRowData',
            'index',
            'parentIndex',
            'formModel',
            `${item.operateConfig.js}`,
          );
          event(
            {
              httpRequest,
              showModal,
              showMessage,
              regTest,
              selectedRowsData: tableData?.selectedRows,
              openModal: tableData?.formApi?.openModal,
              reload: tableData?.formApi?.reload,
              validateModal: tableData?.formApi?.validateModal,
              customModalClose: tableData?.formApi?.customModalClose,
              getUserInfo,
            },
            tableData?.curRow,
            tableData?.curIndex,
            tableData?.curParentIndex,
            formModel,
          );
        } catch (error) {
          notification.error({
            message: 'Tip',
            description: '脚本事件填写有误！',
          });
        }
      } else if (
        item.operateType == ExecuteType.PUSH_MESSAGE &&
        item.operateConfig &&
        item.operateConfig.messageConfig
      ) {
        try {
          await pushMessageFunc(item.operateConfig.messageConfig);
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！'),
          });
        }
      }
    });
  }
};

//页面设计中按钮组件自定义事件;
export const executePageButtonEvent = (setting, formModel) => {
  if (setting?.length) {
    setting.forEach(async (item) => {
      if (
        item.operateType == ExecuteType.API &&
        item.operateConfig &&
        item.operateConfig.apiConfig
      ) {
        try {
          await apiConfigPageDesignFunc(item.operateConfig.apiConfig, formModel);
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！') + error,
          });
        }
      } else if (
        item.operateType == ExecuteType.RULE &&
        item.operateConfig &&
        item.operateConfig.rule
      ) {
        await execute(item.operateConfig.rule, {});
      } else if (item.operateType == 'ruleProcess' && item.ruleConfig) {
        try {
          if (item.ruleConfig.id) {
            let processParamConfigs = [];
            if (
              item.ruleConfig.processParamConfigs &&
              Array.isArray(item.ruleConfig.processParamConfigs) &&
              item.ruleConfig.processParamConfigs.length > 0
            ) {
              processParamConfigs = item.ruleConfig.processParamConfigs.map((item2) => {
                if (item2.assignmentType == AssignmentTypeToRuleType.FORM) {
                  const temp = JSON.parse(item2.assignmentValue);
                  const fild = temp['bindField'];
                  item2.assignmentValue = formModel[fild];
                }

                return item2;
              });
            }
            await RuleProcessExecute(item.ruleConfig.id, processParamConfigs);
          }
        } catch (error) {}
      } else if (
        item.operateType == ExecuteType.JS &&
        item.operateConfig &&
        item.operateConfig.js
      ) {
        const event = new Function('formActionType', `${item.operateConfig.js}`);
        event({
          httpRequest,
          showModal,
          regTest,
          getUserInfo,
        });
      } else if (
        item.operateType == ExecuteType.PUSH_MESSAGE &&
        item.operateConfig &&
        item.operateConfig.messageConfig
      ) {
        try {
          await pushMessageFunc(item.operateConfig.messageConfig);
        } catch (error) {
          notification.error({
            message: t('提示'),
            description: t('执行失败！'),
          });
        }
      }
    });
  }
};
