<template>
  <div id="FormQuery" class="main-content-item-right width-computed">
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        id="FormQuery-queryForm"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <h-card class="list-table">
      <h-b-table
        v-bind="tableProps"
        rowKey="EID"
        :bordered="true"
        :show-export="false"
        :animateRows="false"
        :title="t('FormDesign.list.queryList')"
        ref="gridRef"
        id="FormQuery-querytable"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        :scroll="{ extra: 24, y: true }"
        :height="500"
      >
        <template #headerContent>
          <h-b-button-group
            v-show="true"
            v-bind="menuProps"
            :checkPermission="false"
            ref="menuRef"
            id="FormQuery-buttonGroup"
          />
        </template>
        <template #action="{ record }">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            :checkPermission="false"
            id="Template-buttonGroup-inline"
            @filterItems="lineBtnData(record)"
          />
        </template>
      </h-b-table>
    </h-card>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  createVNode,
  getCurrentInstance,
  onMounted,
  watchEffect,
  ref,
} from 'vue';
import { HModal, message, Icon } from '@crami/ui';
import { useTable, useButtonGroup, useForm } from '@crami/bui-platform';

import { getModelDesignList, deleteFbObjectData, exportFormFile } from '@/api/platform/form';
import { useI18n } from '@crami/locale';
import { commonApi } from '@remote/icpx-platform/commonApi';
import dayjs from 'dayjs';
import CreateProcessDialogVue from './components/CreateProcessDialog.vue';
import { useRouter } from 'vue-router';
import type { IBButtonGroupItem } from '@crami/bui-types';
import historyManagementVue from './components/historyManagement.vue';
import { getInfo, ICP_CONFIG, getUuid } from '@remote/icpx-platform/utils';
enum FlowState {
  // 1：审批中  2:已完成  3:已驳回  4:已撤销  5:已中止  6.未发起
  APPROVE = '1',
  REVIEW = '2',
  RECALL = '3',
  END = '4',
  REBUT = '5',
  NOFLOW = '6',
}
export default defineComponent({
  name: 'FormQuery',
  props: {
    propsData: {
      type: String,
      default: () => {
        return '';
      },
    },
  },
  emits: ['success'],
  setup(_) {
    const { t } = useI18n();
    const router = useRouter();
    let chooseUserId = ref('');
    const initForm = computed(() => {
      return {
        listViewName: _.propsData + 'ListView',
        formName: 'P_SYS_CUSTORM_DATA_STATIC',
        menu: 'P_SYS_CUSTORM_DATA_STATIC_Menu', // _.propsData + 'Menu',
      };
    });
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            mode: 'search',
            name: initForm.value.formName, // commonParams.value?.listViewName,
            // name: 'P_SYS_CUSTORM_DATA_STATIC',
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          // methods.setData({
          //   USER_ID: commonParams.value?.user_id,
          // });
          if (type === 'config') {
            methods?.setProps(
              {
                submitter: {
                  isQuery: true,
                  // searchConfig: { resetText: t('workflow.common.clear') },
                  // actionButtonGroupPosition: 'top',
                },
                // title: '查询',
                column: 4,
              },
              props,
            );
          }
          if (type === 'config') {
            const _props = {
              submitter: {
                isQuery: true,
              },
              column: 4,
            };
            methods?.setProps(_props, props);
            methods.updateSchema(
              [
                {
                  dataIndex: 'CREATEUID',
                  fieldProps: {
                    dataQueryType: 'company',
                    componentType: 'user',
                    selectMode: 'single',
                  },
                  width: '33%',
                  formItemProps: {
                    // rules: [
                    //   { required: true, message: t('queryConfiguration.common.selectPlaceholder') },
                    // ],
                  },
                },
              ],
              props,
            );
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );
    const onFinish = data => {
      // 处理data数据
      console.log(data);
      //组件获取到的数据带有‘；’符号 在这做一下去除
      if (methods.getData().USER_ID) {
        chooseUserId.value = methods.getData().USER_ID.split(';')[0];
      }

      const formData = formRef.value.getFilterData();
      search(formData, true);
    };
    const onReset = () => {
      search([], true);
    };

    const beforeRequest = (type, params: any) => {
      if (type == 'column') {
        // params.data.viewName = 'P_SYS_CUSTORM_DATAView'; // commonParams.value?.listViewName;
        if (params && params.data) {
          params.data = JSON.stringify(params.data);
        }
      }

      return {
        ...params,
        filter: (params.filter || []).concat({
          andOrFlag: 'AND',
          field: 'IS_NEW',
          operation: '=',
          value: 1,
        }),
      };
    };
    const [gridRef, tableProps, tableMethods] = useTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: initForm.value.listViewName, // commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: initForm.value.listViewName, //commonParams.value?.listViewName,
        },
      },
      beforeRequest: beforeRequest,
      operation: {
        dataIndex: 'action',
        title: t('FormDesign.common.operate'),
        width: 230,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });
    const search = (params: any, refresh?: boolean, current?: number) => {
      const allParam: any = {
        filter: params,
      };
      if (current) {
        allParam.page = current;
        allParam.pageNo = current;
      }
      tableMethods.query(allParam, refresh);
      //   .then(() => {
      //   // const rowData = getRowMenu('link');
      //   // menuPropsTableMethods.load(rowData);
      // });
    };

    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 10,
      pageName: 'FormQuery',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: initForm.value.menu, // commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, menuPropsTableMethods] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'FormQuery',
      items: [],
    });

    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      search(params, true);
    };
    const refreshCurrentData = (current?: number) => {
      const params = formRef.value?.getFilterData();
      search(params, false, current);
    };
    // 导出表单文件
    const exportFile = () => {
      const selectedDatas = tableMethods.getSelectedDatas();
      if (selectedDatas.length === 0) {
        message.warning(t('FormDesign.common.choose'));
        return;
      }
      const record = selectedDatas[0];

      const date = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
      const fileName = date + '.xlsx';
      exportFormFile(record.EID, fileName);
    };

    // 新建表单实例
    const createFormInstance = () => {
      // TODO: 接口获取表单模型下可用的-表单模板id,然后跳转到表单填报页面
      getModelDesignList(_.propsData).then(res => {
        if (res.code == 200) {
          if (res.data && res.data.length > 0) {
            showCreateDialog(res.data[0]?.value);
          } else {
            message.warning('无可用模板');
          }
        } else if (!res.success) {
          message.error(res.msg);
        }
      });
    };
    // 弹窗显示
    const showCreateDialog = templateId => {
      const data = {
        TemplateId: templateId,
        currentModel: 'new',
        ObjectType: _.propsData,
      };
      router.replace({
        path: `/CreateFormInstance`,
        query: data,
      });
    };
    const viewForm = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];
      if (!currentItem) {
        return;
      }
      const data = {
        ObjectID: currentItem.EID,
        TemplateId: currentItem.FORM_TEMPLATE_ID,
        currentModel: 'view',
        ObjectType: _.propsData,
      };
      router.replace({
        path: `/CreateFormInstance`,
        query: data,
      });
    };
    // 发起流程
    const startProcess = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];
      if (!currentItem) {
        return;
      }
      const { FLOW_STATE: flowState, FLOW_INSTANCE_ID: flowInstanceId } = currentItem,
        { REVIEW: review } = FlowState,
        pageConfig = {
          title: t(`FormDesign.list.${flowState === review ? 'createChanges' : 'createProcess'}`),
          content: CreateProcessDialogVue,
          componentProps: {
            // propsData: {
            // objectType: _.propsData,
            // 表单实例id
            objectId: currentItem.EID,
            // 表单模板id
            templateId: currentItem.FORM_TEMPLATE_ID,
            // 表单实例是否升版 2：已完成
            newVersion: flowState === review ? true : false,
            // todo: FLOW_STATE枚举类型
            isResubmit: flowInstanceId && flowState !== review ? '1' : null,
            // },
          },
          width: 600,
          // okText: t('FormDesign.common.save'),
          onOk: doCreateProcess,
          appContext,
        };
      HModal.page(pageConfig);
    };
    // 跳转到发起流程页面
    const doCreateProcess = (page, resolve) => {
      // return new Promise((resolve, reject) => {
      page
        .validate()
        .then(() => {
          let paramsUniqueKey = 'createProcessParams_' + getUuid(8, 8);
          localStorage.removeItem(paramsUniqueKey);
          const tempParams = page.getFormData();
          localStorage.setItem(paramsUniqueKey, JSON.stringify(tempParams));
          router.replace(`/platform/workflow/myWorkflow/createProcess/${paramsUniqueKey}`);
          resolve(true);
        })
        .catch(err => {
          if (err?.errorFields?.length != 0) {
            // reject(true);
            console.info('---validate', err);
          } else {
            resolve(true);
          }
        });
      // });
    };
    // 删除表单实例
    const deleteInstance = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];
      if (!currentItem) {
        return;
      }
      HModal.confirm({
        closable: true,
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        title: t('FormDesign.common.deleteTitle'),
        content: t('FormDesign.common.deleteMsg', { count: 1 }),
        onOk() {
          return new Promise((resolve, reject) => {
            deleteFbObjectData(currentItem.EID).then(data => {
              if (data.code == 200) {
                message.success(data.msg);
                refreshCurrentData();
              } else {
                message.error(data.msg);
              }
              resolve(true);
            });
          }).catch(err => console.log('Oops errors!', err));
        },
      });
    };
    /**
     * @description: 历史版本
     */
    let appContext;
    const historyInstance = () => {
      // todo 查看历史版本
      let popAuthConfigOptions = {
        title: t('FormDesign.list.history'),
        content: historyManagementVue,
        okText: ' ',
        cancelText: ' ',
        componentProps: {
          rows: gridRef.value?.getSelectedRows(),
          viewName: initForm.value.listViewName,
        },
        width: 886,
        appContext,
      };
      HModal.page(popAuthConfigOptions);
    };

    // 行操作按钮筛选
    const lineBtnData = record => {
      // FLOW_INSTANCE_ID
      const items: IBButtonGroupItem = [];
      const buttonData = getRowMenu('link');
      const {
        FLOW_STATE: flowState,
        FLOW_INSTANCE_ID: flowInstanceId,
        FLOW_DEFINE_ID: flowDefineId,
      } = record;

      buttonData.forEach(element => {
        // 已发起流程的表单实例（且流程状态为审批中时）不显示-发起流程-按钮
        // 发起流程：key：'75966ae5' name: "startProcess" ; 发起变更：key：'18252b72' name: "startChange"
        const { key } = element;
        let flag = false;

        switch (key) {
          // 发起流程
          case '75966ae5':
            //  流程状态不是审批中的时候
            flag =
              flowState == FlowState.REVIEW
                ? false
                : flowState !== FlowState.APPROVE || (!flowInstanceId && !flowDefineId);
            break;
          // 发起变更
          case '18252b72':
            flag = flowState == FlowState.REVIEW;
            break;
          // 其他按钮
          default:
            flag = true;
        }

        flag && items.push(element);
      });

      // 根据 order 重新排序
      items.sort((a: IBButtonGroupItem, b: IBButtonGroupItem) => a.order - b.order);

      return items;
    };
    //处理行内操作按钮
    watchEffect(() => {
      const rowData = getRowMenu('link');
      menuPropsTableMethods.load(rowData);
    });

    onMounted(() => {
      appContext = getCurrentInstance()?.appContext;
    });
    return {
      t,

      onFinish,
      initForm,
      onReset,
      formRef,
      props,
      methods,

      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      refreshCurrentPage,
      refreshCurrentData,

      gridRef,
      tableProps,
      exportFile,
      createFormInstance,
      viewForm,
      startProcess,
      lineBtnData,
      deleteInstance,
      historyInstance,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.hoteam-b-table) {
  border-radius: 8px;
}
</style>
