<template>
  <div class="content-version" id="History">
    <h-b-button-group v-show="false" v-bind="menuProps" ref="menuRef" id="Root-buttonGroup" />
    <h-b-table
      v-bind="tableProps"
      rowKey="EID"
      :show-size="false"
      :show-export="false"
      :pagination="false"
      :animateRows="false"
      ref="gridRef"
      :toolbar="false"
      id="History-querytable"
      :row-selection="{
        type: 'checkbox',
        memory: true,
        clickSelectTrigger: 'row',
        unSelectable: true,
      }"
      :height="230"
    >
      <template #action="{ record }">
        <h-b-button-group
          v-bind="menuPropsTable"
          ref="menuRefTable"
          :checkPermission="false"
          id="Template-buttonGroup-inline"
          @filterItems="processButtonGroupData(record)"
        />
      </template>
    </h-b-table>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, watchEffect } from 'vue';
import { message, HModal } from '@crami/ui';
import type { IBButtonGroupItem } from '@crami/bui-types';
import { useTable, useButtonGroup } from '@crami/bui-platform';

import { useI18n } from '@crami/locale';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
import { commonApi } from '@remote/icpx-platform/commonApi';
import dayjs from 'dayjs';
import { exportFormFile } from '@/api/platform/form';

// 表单设计-版本管理
export default defineComponent({
  name: 'HistoryManagement',
  components: {},
  props: {
    componentProps: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(_) {
    const { t } = useI18n();

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    const versionListView = _.componentProps?.viewName;
    const beforeRequest = (type, params: any) => {
      if (type == 'column') {
        if (params && params.data) {
          params.data = JSON.stringify(params.data);
        }
      }
      return {
        ...params,
        filter: [
          {
            andOrFlag: 'AND',
            field: 'PARENT_ID',
            operation: '=',
            value: _.componentProps.rows[0].PARENT_ID,
          },
        ],
      };
    };
    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: versionListView,
          },
        },
      },
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        params: {
          // MasterType: _.componentProps.rows[0].EID,
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: versionListView,
          page: 1,
          pageNo: 1,
          // 数据不分页
          pageSize: -1,
        },
      },
      beforeRequest: beforeRequest,
      operation: {
        dataIndex: 'action',
        title: t('FormDesign.common.operate'),
        width: 130,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const menuName = 'P_SYS_CUSTORM_DATA_STATIC_Menu';
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 10,
      pageName: 'HistoryManagement',
      checkPermission: false,
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: menuName,
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, menuMethodsTable] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'HistoryManagement',
      moreItem: {
        trigger: ['click'],
      },
    });
    //处理行内按钮的显示
    const processButtonGroupData = record => {
      // FLOW_INSTANCE_ID
      const items: IBButtonGroupItem = [];
      const buttonData = getRowMenu('link');

      buttonData.forEach(element => {
        // 只显示导出按钮
        if (element.key === '2c3f7f8a') {
          items.push(element);
        }
      });
      return items;
    };
    // 导出表单文件
    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 newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

    const search = (refresh?: boolean) => {
      tableMethods.query({}, refresh).then(() => {
        // TODO
        const rowData = getRowMenu('link');
        menuMethodsTable.load(rowData);
      });
    };

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

    return {
      t,
      commonParams,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      exportFile,
      processButtonGroupData,

      gridRef,
      tableProps,
    };
  },
});
</script>

<style scoped>
.content-version {
  flex: 1;
  overflow-y: auto !important;
}
</style>
