<template>
  <div class="main-content main-content-padding" id="EsIndexConfiguration">
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="EsIndexConfiguration-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        :submitter="{
          isQuery: true,
          searchConfig: {
            resetText: t('platform.common.reset'),
            submitText: t('queryConfiguration.common.search'),
          },
        }"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-pro-table
        id="EsIndexConfiguration-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :showExport="false"
        :animateRows="false"
        :show-size="false"
        :title="t('queryConfiguration.esIndexConfiguration.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="EsIndexConfiguration-buttonGroup"
            v-bind="menuProps"
            ref="menuRef"
          />
        </template>
        <template #INDEX_STATUS="{ text, record }">
          {{ record.PROGRESS_PERCENT ? `${text}(${record.PROGRESS_PERCENT})` : text }}
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            id="EsIndexConfiguration-buttonGroup-inline"
            v-bind="menuPropsTable"
            ref="menuRefTable"
          />
        </template>
      </h-b-pro-table>
    </h-card>

    <map-edit-modal
      ref="mapEditModalRef"
      :maskClosable="false"
      @refreshTable="RefreshTable"
    ></map-edit-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, watchEffect, ref, createVNode, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useProTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG, getParams } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG, getParams } from '@/utils/commMethods'; */
import { message, HModal, Icon } from '@crami/ui';
import { useHttp, Http } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';
import NewIndex from './NewIndex.vue';
import mapEditModal from '../components/mapEditModal.vue';
import asyncPolling from './asyncPolling';

export default defineComponent({
  name: 'EsIndexConfiguration',
  components: {
    mapEditModal,
  },

  setup() {
    // 多语言
    const { t } = useI18n();
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'ICPX_INDEX_MANAGEMENT_LISTVIEW',
        menuName: 'ICPX_INDEX_MANAGEMENT_MENU',
      };
    });
    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: any = {
              submitter: {
                isQuery: true,
              },
              column: 2,
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const onFinish = () => {
      // 处理data数据
      const formData = formRef.value.getFilterData();
      search(formData);
    };

    const getListViewName = () => {
      const route = useRoute();
      const router = window.sessionStorage.getItem('HomeAdminRouter');
      const routerMenu = router ? JSON.parse(router) : [];
      return getParams(routerMenu, route.meta?.initPath || route.path)?.extra?.listViewName;
    };

    const LIST_VIEW_NAME = getListViewName();

    // 轮询查询数据的状态进度
    const handleProcess = () => {
      return new Promise(resolve => {
        const processingData = tableMethods
          .getDisplayAllData()
          .filter(item => item.PROGRESS_PERCENT);
        if (processingData.length) {
          useHttp({
            url: '/index/indexConfig/listByIdList',
            method: 'post',
            params: {
              ...commonApi().system.getData.params,
              // 这里不用commonParams.value?.listViewName的原因是使用闭包的方式获取的listViewName值，当前函数递归执行时，切换tab页面又切回来的话获取到listViewName的值为空
              viewName: LIST_VIEW_NAME,
              userId: commonParams.value.user_id,
              objectType: '',
              filter: [
                {
                  field: 'EID',
                  value: processingData.map(item => item.EID).join(';'),
                  operation: 'IN',
                  andOrFlag: 'AND',
                  key: 'EID',
                },
              ],
            },
          })
            .then(res => {
              if (res.code === 200) {
                if (!res.data || !res.data.length) {
                  cancel();
                  return;
                }

                let constantCount = 0;
                const data = tableMethods.getDisplayAllData();
                res.data.forEach(item => {
                  let matchedData = data.find(row => row.EID === item.EID);
                  if (matchedData) {
                    if (item.PROGRESS_PERCENT) {
                      matchedData.PROGRESS_PERCENT = item.PROGRESS_PERCENT;
                      constantCount++;
                    } else {
                      matchedData.PROGRESS_PERCENT = undefined;
                    }
                    matchedData.INDEX_STATUS = item.INDEX_STATUS;
                  }
                });
                tableMethods.setData(data);

                if (constantCount === 0) {
                  cancel();
                }
              } else {
                cancel();
              }
            })
            .catch(err => {
              cancel();
            })
            .finally(() => {
              resolve();
            });
        } else {
          cancel();
          resolve();
        }
      });
    };
    const { startup, cancel } = asyncPolling(handleProcess, 3000);

    const [gridRef, tableProps, tableMethods] = useProTable({
      // 表头数据
      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,
        url: '/index/indexConfig/page',
        method: commonApi().system.getGetOnePageGridDataList.method,
        // url: '/index/indexConfig/page',
        // method: 'post',
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: commonParams.value?.listViewName,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
        };
      },
      afterRequest: (type, params) => {
        if (type === 'data') {
          if (params.data.find(item => item.PROGRESS_PERCENT)) {
            setTimeout(() => {
              startup();
            }, 500);
          }
          return params;
        }
      },
      operation: {
        dataIndex: 'action',
        title: t('queryConfiguration.common.operate'),
        width: 240,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        AUDITSTATE: {
          customSlot: 'auditState',
        },
        INDEX_STATUS: {
          customSlot: 'INDEX_STATUS',
        },
      },
    });

    const search = (params: any) => {
      cancel();
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'EsIndexConfiguration',
      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: 'EsIndexConfiguration',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const newJsFun = (event: any) => {
      if (event !== undefined) {
        RefreshTable();
        HModal.destroyAll();
      } else {
        if (undefined == event || undefined == event.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

    // 新建索引
    const newIndex = (row?: any) => {
      let addRowOptions = {
        title: t('queryConfiguration.common.modalTitle'),
        content: NewIndex,
        componentProps: {
          rows: row ? [row] : gridRef.value?.getSelectedRows(),
        },
        width: '40%',
        onOk: saveOnOK,
      };
      HModal.page(addRowOptions);
    };

    const saveOnOK = (page, resolve) => {
      saveData(page, resolve);
    };

    // 保存数据
    const saveData = async (page, resolve) => {
      const radioValue = page.radioValue;
      // 校验失败时会返回false，成功返回表单对象
      if (radioValue) {
        const result = await useHttp({
          url: '/api/index/indexConfig/add',
          method: 'post',
          params: {
            data: radioValue,
            companyId: commonParams.value?.companyId,
            userId: commonParams.value.user_id,
            lang: commonParams.value?.lang,
            connect: commonParams.value?.connect,
            timeZone: commonParams.value?.TIME_ZONE,
          },
        });
        if (result.code == 200) {
          message.success(result.msg);
          RefreshTable();
          resolve();
        } else {
          message.error(result.msg);
        }
      } else {
        message.warning(t('queryConfiguration.common.selectTip'));
      }
    };

    // 删除配置
    const deleteIndex = async () => {
      const selectData = tableMethods.getSelectRows();
      HModal.confirm({
        width: '450px',
        title: t('queryConfiguration.common.deleteTitle'),
        class: 'self-warning-modal',
        closable: true,
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        content: t('queryConfiguration.common.deleteMsg'),
        onOk() {
          deleteApi(selectData[0].EID);
        },
      });
    };
    const deleteApi = async (idStr: string) => {
      const res = await useHttp({
        url: '/api/index/indexConfig/delete',
        method: 'post',
        params: {
          EIDStr: idStr,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (res.code == 200) {
        message.success(res.msg);
        RefreshTable();
      } else {
        message.error(res.msg);
      }
    };

    // 索引重建
    const rebuildIndex = () => {
      const selectData = tableMethods.getSelectRows();
      const ids = selectData.map(item => {
        return item.EID;
      });
      if (selectData.length === 0) {
        message.warning(t('queryConfiguration.common.selectOne'));
      } else {
        HModal.confirm({
          width: '450px',
          title: t('queryConfiguration.common.rebuildTitle'),
          class: 'self-warning-modal',
          closable: true,
          icon: createVNode(Icon, {
            name: 'icp-exclamation-circle-filled',
            size: 24,
            style: {
              float: 'left',
              marginRight: '8px',
            },
          }),
          content: t('queryConfiguration.common.rebuildMsg'),
          onOk() {
            rebuildApi(ids);
          },
        });
      }
    };
    const rebuildApi = async ids => {
      const res = await useHttp({
        url: '/api/index/indexConfig/rebuild',
        method: 'post',
        params: {
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          userId: commonParams.value?.user_id,
          ids: ids,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (res.code == 200) {
        message.success(res.msg);
        RefreshTable();
      } else {
        message.error(res.msg);
      }
    };

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

    const RefreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };
    const onReset = () => {
      search([]);
    };

    const mapEditModalRef = ref();
    const nameMapping = () => {
      const row = gridRef.value?.getSelectedRows();
      mapEditModalRef.value.showModal(row[0] || {}, {
        optionsApiUrl: '/api/index/indexConfig/getNameMapping',
        saveApiUrl: '/api/index/indexConfig/update',
      });
    };

    return {
      t,
      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      RefreshTable,
      deleteIndex,
      newIndex,
      rebuildIndex,
      mapEditModalRef,
      nameMapping,
      gridRef,
      tableProps,
    };
  },
});
</script>
<style lang="less" scoped>
.fixHeight {
  margin-bottom: 260px;
  display: flex;
  align-items: center;
}

//删除弹窗图标样式
.tenant-confirm-delete {
  .ant-modal-confirm-body img {
    float: left;
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}
.rebuildIndex .ant-modal-confirm-body .ant-modal-confirm-content,
.deleteIndex .ant-modal-confirm-body .ant-modal-confirm-content {
  padding-left: 0 !important;
}
</style>
