<template>
  <!-- 开发用编辑系统内置通用查询按钮 -->
  <!-- <button @click="goEditPage">编辑系统内置</button> -->
  <div class="main-content main-content-padding" id="GeneralQueryConfigIndex">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="GeneralQueryConfigIndex-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="GeneralQueryConfigIndex-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('queryConfiguration.configIndex.tableTitle')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        :scroll="{
          extra: 24,
          y: true,
        }"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group
            id="GeneralQueryConfigIndex-buttonGroup"
            v-bind="menuProps"
            ref="menuRef"
          />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{ record }">
          <h-b-button-group
            id="GeneralQueryConfigIndex-buttonGroup-inline"
            v-bind="menuPropsTable"
            ref="menuRefTable"
            @filterItems="rowButtonGroupData(record)"
          />
        </template>
      </h-b-table>
    </h-card>
  </div>
</template>
<script lang="ts">
import { useRouter } from 'vue-router';
import { defineComponent, watchEffect, computed } from 'vue';
import { useTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG, hasPermission } from '@remote/icpx-platform/utils';
/* 
import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; 
import { getPageLinksData, hasPermission } from '@/utils/hasPermissionUtil';
*/
import { message, HModal } from '@crami/ui';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

import type { IBButtonGroupItem } from '@crami/bui-types';

export default defineComponent({
  name: 'GeneralQueryConfigIndex',
  components: {},
  setup() {
    if (window.name === '') {
      console.log('页面首次被加载');
    } else {
      console.log('页面被刷新');
    }
    const { t } = useI18n();
    const router = useRouter();
    // 获取info
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'P_COMMON_QUERY_CONFIGListView',
        menuName: 'P_COMMON_QUERY_OFTENMenu',
      };
    });
    // 查询表单配置信息
    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            mode: 'search',
            name: commonParams.value?.listViewName,
          },
          method: 'post',
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props = {
              submitter: {
                isQuery: true,
                // actionButtonGroupPosition: 'top',
              },
              column: 2,
              // title: t('platform.common.search'),
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    // 表格配置信息
    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: commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/commonquery/commonQuery/manage/page',
        method: 'post',
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: commonParams.value?.listViewName,
        },
      },
      beforeRequest: (type, params) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 160,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        ROLE_STATUS: {
          customSlot: 'roleState',
        },
      },
    });

    // 按钮配置信息
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'GeneralQueryConfigIndex',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: commonParams.value?.menuName,
        },
        method: 'post',
      },
    });
    //  表格按钮配置信息
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'GeneralQueryConfigIndex',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    //处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });
    //处理行内按钮的显示
    const rowButtonGroupData = record => {
      // const record = tableProps.dataSource[recordIndexs[0]];
      const items: IBButtonGroupItem = [];
      const buttonData = getRowMenu('link');
      buttonData.forEach(element => {
        if (hasPermission(element.key)) {
          if (element.name === '删除' && record.TYPE === '1') {
          } else {
            items.push(element);
          }
        }
      });

      return items;
    };
    // 刷新表格
    const RefreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };
    // 重置方法
    const onReset = () => {
      search([]);
    };
    // 查询方法
    const search = params => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true).then(() => {
        setTimeout(() => {
          const rowData = getRowMenu('link');
          load(rowData);
        }, 50);
      });
    };
    // 新建事件
    const goCreatePage = () => {
      router.push({
        name: 'GeneralQueryConfigCreate',
      });
    };
    const newJsMethod1 = () => {
      const selectData = tableMethods.getSelectRows();
      if (selectData[0].TYPE === '0') {
        router.push({
          name: 'GeneralQueryConfigView',
          query: {
            EID: selectData[0].EID,
          },
        });
      } else {
        router.push({
          name: 'SystemBuiltInView',
          query: {
            EID: selectData[0].EID,
          },
        });
      }
    };
    // 编辑事件
    const goEditPage = () => {
      // todo接口
      const selectData = tableMethods.getSelectRows();
      if (selectData[0].TYPE === '0') {
        router.push({
          name: 'GeneralQueryConfigEdit',
          query: {
            EID: selectData[0].EID,
          },
        });
      } else {
        router.push({
          name: 'SystemBuiltInEdit',
          query: {
            EID: selectData[0].EID,
          },
        });
      }
    };
    // 查询事件
    const onFinish = () => {
      // 处理data数据
      const formData = formRef.value.getFilterData();
      search(formData);
    };
    // 删除事件
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        RefreshTable();
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };
    return {
      t,
      goCreatePage,
      goEditPage,
      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      RefreshTable,
      gridRef,
      tableProps,
      newJsFun,
      newJsMethod1,
      rowButtonGroupData,
    };
  },
});
</script>
