<template>
  <div class="main-content main-content-padding" id="Imex30">
    <h-card class="margin-bottom list-query-form">
      <!-- //查询表单 -->
      <h-b-form
        id="Imex30-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
        style="padding: 15px 22px"
      ></h-b-form>
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="Imex30-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('ImpExp.common.expList')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        :scroll="{ extra: 24, y: true }"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group id="Imex30-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="Imex30-buttonGroup-inline"
              v-bind="menuPropsTable"
              ref="menuRefTable"
            />
          </template>
        </template>
      </h-b-table>
    </h-card>
    <template v-if="compile2">
      <imp-guide
        :compile2="compile2"
        @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>
  </div>
</template>

<script lang="ts">
import { defineComponent, watchEffect, computed, ref } 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';

export default defineComponent({
  name: 'Imex30',
  components: { ImpGuide },
  setup() {
    const { t } = useI18n();
    const pageParams = ref();
    // 设置下拉框选中事件
    const handleChange = (value: string) => {
      console.log(`selected ${value}`);
    };
    const Refresh = () => {
      console.log(12345);
      tableMethods.query({}, true);
    };
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    // 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({
      sortRule: 'default',
      pageName: 'Imex30',
      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({
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'Imex30',
      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 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));
    };

    return {
      Refresh,
      t,
      exportGridData,
      expCompile,
      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>
