<template>
  <div class="content-version" id="Versions">
    <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="Versions-querytable"
      :row-selection="{
        type: 'checkbox',
        memory: true,
        clickSelectTrigger: 'row',
        unSelectable: true,
      }"
      :height="230"
    >
      <template #bodyCell="{ column, record, recordIndexs }">
        <template v-if="column.dataIndex === 'action'">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="Versions-buttonGroup-inline"
            :checkPermission="false"
            :processButtonGroupData="() => processButtonGroupData(recordIndexs)"
          />
          <!--  @filterItems="processButtonGroupData(record)" -->
          <!-- :processButtonGroupData="()=>processButtonGroupData(recordIndexs)" -->
        </template>
        <template v-if="column.dataIndex === 'ISMAINVERSION'">
          {{ record.ISMAINVERSION === 'true' ? t('FormDesign.list.yes') : t('FormDesign.list.no') }}
        </template>
        <template v-if="column.dataIndex === 'SERIALNUMBER'">
          {{ Number(recordIndexs) + 1 }}
        </template>
      </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 { setMainVersion } from '@/api/platform/form';
let timeout: any;
// 表单设计-版本管理
export default defineComponent({
  name: 'VersionManagement',
  components: {},
  props: {
    componentProps: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(_) {
    const { t } = useI18n();

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

    const versionListView = 'P_SYS_CUSTORM_DATA_VERSION_ListView';
    const beforeRequest = (type, params: any) => {
      if (type == 'column') {
        if (params && params.data) {
          params.data = JSON.stringify(params.data);
        }
      }
      return {
        ...params,
        filter: [
          {
            andOrFlag: 'AND',
            field: 'MAIN_ID',
            operation: '=',
            value: _.componentProps.rows[0].EID,
          },
        ],
      };
    };
    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,
        },
      },
      beforeRequest: beforeRequest,
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 130,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        SERIALNUMBER: {
          customSlot: 'SERIALNUMBER',
        },
      },
    });

    const menuName = 'P_SYS_CUSTORM_DATA_VERSION_Menu';
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 10,
      pageName: 'VersionManagement',
      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: 'VersionManagement',
      moreItem: {
        trigger: ['click'],
      },
    });
    //处理行内按钮的显示
    const processButtonGroupData = recordIndexs => {
      const record = tableProps.dataSource[recordIndexs[0]];
      const items: IBButtonGroupItem = [];
      const buttonData = getRowMenu('link');

      buttonData.forEach(element => {
        if (record.ISMAINVERSION !== 'true') {
          items.push(element);
        }
      });

      return items;
    };

    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 setMasterVersion = () => {
      const currentItem = gridRef.value?.getSelectedRows()[0];
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      function fetchData() {
        setMainVersion(_.componentProps.rows[0].EID, currentItem.EID).then(source => {
          if (source.code == 200) {
            search(true);
            message.success(source.msg);
          } else if (!source.success) {
            message.error(source.msg);
          }
        });
      }
      timeout = setTimeout(fetchData, 300);
    };

    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,
      setMasterVersion,
      processButtonGroupData,

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

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