<template>
  <div class="box">
    <div class="item-box">
      <div class="title">{{ props.title }}</div>
      <div class="button-box">
        <div
          class="item"
          @click.stop="handleClick(item)"
          v-for="(item, index) in props.config.buttons"
          :key="index"
          >{{ item.name }}</div
        >
      </div>
    </div>
    <ModalPanel
      :visible="state.createOpen"
      :title="state.name"
      @submit="createSubmit"
      @close="createClose"
    >
      <SimpleForm
        ref="formRef"
        :formProps="createData.formProps"
        :formModel="createData.formModel"
      />
    </ModalPanel>
    <ModalPanel
      :visible="state.searchOpen"
      :title="state.name"
      @submit="searchSubmit"
      @close="searchClose"
    >
      <a-table :columns="searchData.columns" :data-source="searchData.data" bordered />
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, h } from 'vue';
  import { buttonProperties } from '../config/properties';
  import { DesktopComponent, ExecuteType } from '/@/enums/desktop';
  import { ButtonConfig } from '/@/model/desktop/designer';
  import { ModalPanel } from '/@/components/ModalPanel/index';
  import { getFormTemplate } from '/@/api/form/design';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { buildOption } from '/@/utils/helper/designHelper';
  import { addComplexFormExecute } from '/@/api/form/design/index';
  import { message, notification } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { ButtonType } from '/@/enums/desktop';
  import { execute } from '/@/api/liteflow';
  import useComplexApiRequest from './../../../hooks/useComplexApiRequest';
  import type { ModalFuncProps } from 'ant-design-vue/lib/modal/Modal';
  import { regTestProps, requestProps } from '/@/components/Form/src/types/form';
  import { defHttp } from '/@/utils/http/axios';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { AssignmentTypeToRuleType } from '/@/api/ruleProcess/model';
  import { RuleProcessExecute } from '/@/api/ruleProcess';

  const userStore = useUserStore();
  const { changeApiOptions, pushMessageFunc } = useComplexApiRequest();
  const { t } = useI18n();
  const formRef = ref();
  const props = withDefaults(
    defineProps<{
      type: DesktopComponent;
      w: number;
      h: number;
      title: string;
      config: ButtonConfig;
    }>(),
    {
      type: DesktopComponent.DEFAULT,
      w: 0,
      h: 0,
      config: () => {
        return buttonProperties;
      },
    },
  );
  const refreshAPI = () => {
    // TODO 刷新api 操作方法
    console.log('refreshAPI---');
  };
  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.params,
        },
        {
          errorMessageMode: request.errorMessageMode || 'none',
        },
      );
    }
  };
  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) => {
    const ContentHtml = (text) => {
      return h(
        'div',
        {
          class: 'my-div',
        },
        text,
      );
    };
    Modal.confirm({
      title: modal.title,
      icon: h(ExclamationCircleOutlined),
      content: ContentHtml(modal.content),
      onOk: modal.onOk,
      onCancel: modal.onCancel,
      ...modal,
    });
  };
  const formApi = {
    httpRequest,
    showModal,
    regTest,
    refreshAPI,
  };
  const state = reactive({
    createOpen: false,
    searchOpen: false,
    formId: '',
    name: '',
  });
  const searchData = reactive({
    columns: [],
    data: [],
  });

  const createData = reactive({
    formModel: {},
    formProps: {},
  });
  async function handleClick(item) {
    state.formId = item.formId;
    state.name = item.name;
    if (item.type === ButtonType.CREATE) {
      if (state.formId) {
        state.createOpen = true;
        try {
          const templateResult = await getFormTemplate(state.formId);
          const formJson = JSON.parse(templateResult.formJson);
          let formProps = buildOption(formJson.formJson, false);
          createData.formProps = formProps;
        } catch (error) {
          console.log('error: ', error);
        }
      } else {
        console.log('你未选择表单');
      }
    }
    if (item.type === ButtonType.SEARCH) {
      searchData.columns = item.apiColumn;
      searchData.data = [];
      if (item.apiConfig.path) {
        // TODO api组件参数参数
        let res = await changeApiOptions(item.apiConfig);
        if (res) {
          searchData.data = res;
        }
        state.searchOpen = true;
      }
    }
    if (item.type === ButtonType.EXECUTE) {
      try {
        if (item.processEvent.length > 0) {
          for (let index = 0; index < item.processEvent.length; index++) {
            const element = item.processEvent[index];
            if (
              element.operateType == ExecuteType.API &&
              element.operateConfig &&
              element.operateConfig.apiConfig
            ) {
              try {
                await changeApiOptions(element.operateConfig.apiConfig);
              } catch (error) {
                notification.error({
                  message: t('提示'),
                  description: t('执行失败！'),
                }); //提示消息
              }
            } else if (
              element.operateType == ExecuteType.RULE &&
              element.operateConfig &&
              element.operateConfig.rule
            ) {
              await execute(element.operateConfig.rule, {});
            } else if (element.operateType == 'ruleProcess' && element.ruleConfig) {
              try {
                if (element.ruleConfig.id) {
                  let processParamConfigs = [];
                  if (
                    element.ruleConfig.processParamConfigs &&
                    Array.isArray(element.ruleConfig.processParamConfigs) &&
                    element.ruleConfig.processParamConfigs.length > 0
                  ) {
                    processParamConfigs = element.ruleConfig.processParamConfigs.map((item2) => {
                      item2.assignmentValue = getRuleProcessFormValue(item2);
                      return item2;
                    });
                  }
                  await RuleProcessExecute(element.ruleConfig.id, processParamConfigs);
                }
              } catch (error) {}
            } else if (
              element.operateType == ExecuteType.JS &&
              element.operateConfig &&
              element.operateConfig.js
            ) {
              const event = new Function('formActionType', `${element.operateConfig.js}`);
              event(formApi);
            } else if (
              element.operateType == ExecuteType.PUSH_MESSAGE &&
              element.operateConfig &&
              element.operateConfig.messageConfig
            ) {
              try {
                await pushMessageFunc(element.operateConfig.messageConfig);
              } catch (error) {
                notification.error({
                  message: t('提示'),
                  description: t('执行失败！'),
                }); //提示消息
              }
            }
          }
        }
        notification.success({
          message: t('提示'),
          description: t('执行成功！'),
        });
      } catch (error) {
        notification.error({
          message: t('提示'),
          description: t('执行失败！'),
        });
      }
    }
  }
  async function createSubmit() {
    try {
      const values = await formRef.value?.validate();
      await addComplexFormExecute(state.formId, values);
      notification.success({
        message: t('提示'),
        description: t('新增成功！'),
      }); //提示消息
      state.createOpen = false;
    } catch (error) {
      console.log('error: ', error);
    }
  }
  function createClose() {
    state.createOpen = false;
  }
  async function searchSubmit() {
    try {
      state.searchOpen = false;
    } catch (error) {
      console.log('error: ', error);
    }
  }
  function searchClose() {
    state.searchOpen = false;
  }

  function getRuleProcessFormValue(element) {
    if (element.assignmentType == AssignmentTypeToRuleType.FORM) {
      // 当前人信息
      if (element.value.includes('currentInfo----')) {
        const type = element.value.replace('currentInfo----', '');
        if (type == 'name') {
          return userStore.getUserInfo.name;
        } else if (type == 'id') {
          return userStore.getUserInfo.id;
        } else if (type == 'code') {
          return userStore.getUserInfo.code;
        } else if (type == 'mobile') {
          return userStore.getUserInfo.mobile;
        } else if (type == 'departmentName') {
          return userStore.getUserInfo.departmentName;
        } else if (type == 'departmentId') {
          return userStore.getUserInfo.departmentId;
        } else if (type == 'postId') {
          return userStore.getUserInfo.postId;
        } else if (type == 'roles.id') {
          return userStore.getUserInfo.roles[0].id;
        }
      }
      return '';
    }
    return element.value;
  }
</script>

<style lang="less" scoped>
  .box {
    .item-box {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        color: #262626;
        font-size: 16px;
        padding-left: 16px;
      }

      .button-box {
        display: flex;
        align-items: center;
        padding-right: 10px;

        .item {
          font-size: 14px;
          padding: 2px 10px;
          margin-right: 4px;
          cursor: pointer;
          border-radius: 4px;
          color: #fff;
          background-color: #39f;
        }
      }
    }
  }
</style>
