<template>
  <div class="main-content main-content-padding" id="ImexTest">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="ImexTest-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="ImexTest-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('ImpExp.common.seatManagement')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        :scroll="{ extra: 24, y: true }"
        :height="500"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group id="ImexTest-buttonGroup" v-bind="menuProps" ref="menuRef" />
        </template>
        <!-- 行内操作按钮 -->
        <template #bodyCell="{ column, record }">
          <!-- UI设计图的启用禁用状态 -->
          <template v-if="column.dataIndex === 'STATE'">
            <template v-if="record.STATE === t('ImpExp.common.Enable')">
              <h-badge status="success" :text="record.STATE" />
            </template>
            <template v-else-if="record.STATE === t('ImpExp.common.Deactivate')">
              <h-badge status="error" :text="record.STATE" />
            </template>
          </template>
          <!-- 行内操作按钮 -->
          <template v-if="column.dataIndex === 'action'">
            <h-b-button-group
              id="ImexTest-buttonGroup-inline"
              v-bind="menuPropsTable"
              ref="menuRefTable"
            />
          </template>
        </template>
      </h-b-table>
    </h-card>
    <template v-if="compile2">
      <imp-guide
        ref="impRef"
        :compile2="compile2"
        :extraParams="extraParams"
        @submit-event="submit"
        @Refresh="Refresh"
        @closeModel="compile2 = false"
        :commonParams="commonParams"
      ></imp-guide>
    </template>
    <exp-guide
      :expCompile="expCompile"
      @expCompiles="expCompile = false"
      :searchParams="searchParams"
      :pageParams="pageParams"
      :dataEids="dataEids"
    ></exp-guide>
    <test-exp-guide
      :expCompile="testExpCompile"
      @expCompiles="testExpCompile = false"
      :searchParams="searchParams"
      :pageParams="pageParams"
      :dataEids="dataEids"
    ></test-exp-guide>
  </div>
</template>

<script lang="ts">
import { defineComponent, watchEffect, computed, ref, reactive } from 'vue';
import { useTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
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 ImpGuide from './Compnent/ImpGuide.vue';
import TestExpGuide from './Compnent/TestExpGuide.vue';

export default defineComponent({
  name: 'ImexTest',
  components: { ImpGuide, TestExpGuide },
  setup() {
    const { t } = useI18n();
    const pageParams = ref();
    const impRef = ref(null);
    const extraParams = reactive({});
    // 设置下拉框选中事件
    const handleChange = (value: string) => {
      console.log(`selected ${value}`);
    };
    const Refresh = () => {
      console.log(12345);
      tableMethods.query({}, true);
    };
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'P_SYS_IMEX_TEST_LISTVIEW',
        menuName: 'P_SYS_IMEX_TEST_MENU',
      };
    });
    // console.log(commonParams);
    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: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                // actionButtonGroupPosition: 'top',
              },
              // layout: 'vertical',
              column: 2,
              // labelCol: { span: 20 }, //标签
              // wrapperCol: { span: 20 },
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );
    const onFinish = () => {
      // 处理data数据
      const formData = formRef.value.getFilterData();
      search(formData);
    };

    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: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: commonParams.value?.listViewName,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data) {
            params.data = JSON.stringify(params.data);
          }
        }
        pageParams.value = params;
        return {
          ...params,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 120,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const searchParams = ref();
    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      searchParams.value = params;
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'ImexTest',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'ImexTest',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    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);
        }
      }
    };

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

    const refreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };

    const onReset = () => {
      search([]);
    };

    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      console.log(params);
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, false);
    };

    const expCompile = ref<boolean>(false);
    const testExpCompile = ref(false);
    const dataEids = ref();
    // 导出
    const exportGridData = dataExp => {
      HModal.confirm({
        icon: false,
        title: t('ImpExp.common.ExpConfirm'),
        content: t('ImpExp.common.ExpDatas'),
        onOk() {
          return new Promise((resolve, reject) => {
            // console.log(dataExp);
            localStorage.setItem('dataExp', JSON.stringify(dataExp));
            dataEids.value = tableMethods.getSelectedKeys();
            expCompile.value = true;
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    const compile2 = ref<boolean>(false);
    const importFile = dataImp => {
      compile2.value = true;
      // console.log(dataImp);
      localStorage.setItem('dataImp', JSON.stringify(dataImp));
    };

    const testExportGridData = dataExp => {
      HModal.confirm({
        icon: false,
        title: t('ImpExp.common.ExpConfirm'),
        content: t('ImpExp.common.ExpDatas'),
        onOk() {
          return new Promise((resolve, reject) => {
            // console.log(dataExp);
            localStorage.setItem('dataExp', JSON.stringify(dataExp));
            dataEids.value = tableMethods.getSelectedKeys();
            testExpCompile.value = true;
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    const submit = (res: any) => {
      res();
    };
    return {
      impRef,
      extraParams,
      Refresh,
      submit,
      t,
      exportGridData,
      testExportGridData,
      expCompile,
      testExpCompile,
      searchParams,
      pageParams,
      dataEids,
      commonParams,
      search,

      importFile,
      compile2,

      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,

      refreshCurrentPage,
      refreshTable,

      gridRef,
      tableProps,

      handleChange,
    };
  },
});
</script>
<style lang="less" scoped></style>
