wujingjing
2024-11-26 9eed6e2af239a7cc07825c409b64d1f621f149be
src/components/chat/chatComponents/summaryCom/components/recordSetTable/RecordSetTable.vue
@@ -1,178 +1,495 @@
<!-- 查询最新警告信息 -->
<template>
   <div>
      <!-- <span v-if="data?.title" class="text-base font-bold flex-center mb-5">{{ data?.title }}</span> -->
      <div class="w-full" style="height: 70vh" ref="containerRef" v-resize="resizeHandler">
         <el-table
            ref="tableRef"
            border
            :cell-style="tableCellStyle"
            :header-cell-style="tableHeaderCellStyle"
            :data="data?.values"
            :spanMethod="objectSpanMethod"
            class="w-full h-full"
            cellClassName="text-sm"
            headerCellClassName="text-sm"
         >
            <el-table-column v-if="data?.title" :label="data?.title" show-overflow-tooltip>
               <template v-if="data?.cols?.length > 0">
                  <el-table-column
                     v-for="(item, index) in colList"
                     :label="item.title"
                     :width="item.width"
                     :sortable="item.type === 'time'"
                     :key="index"
                     :prop="index + ''"
                     show-overflow-tooltip
                  />
               </template>
            </el-table-column>
            <template v-else>
               <template v-if="data?.cols?.length > 0">
                  <el-table-column
                     v-for="(item, index) in colList"
                     :label="item.title"
                     :width="item.width"
                     :sortable="item.type === 'time'"
                     :key="index"
                     :prop="index + ''"
                     show-overflow-tooltip
                  />
               </template>
            </template>
         </el-table>
   <div class="w-full flex-column">
      <div class="flex-0 flex-items-center mb-1 flex-wrap">
         <template v-if="visibleParams && visibleParams.length > 0 && showFilter">
            <component
               class="flex-0 m-2"
               v-model="visibleParams[index].value"
               v-for="(item, index) in visibleParams as any"
               :key="item.id"
               :id="item.id"
               :is="recordSetMapCom[item.type]"
               :data="item"
               @change="(val) => handleQueryChange(val, item)"
               :originData="originData"
               :disabled="disabled"
            ></component>
         </template>
         <ColFilter v-if="!isTotalTable" class="ml-auto" :columnList="colList" @change="colFilterChange" />
         <DisplayMode v-if="isTotalTable" class="ml-auto" :order="modeChangeOrder" v-model="showMode" :displayModeTypeMap="displayModeTypeMap" @change="displayModeChange" />
         <DisplayMode v-if="isMap" class="ml-auto" :order="modeChangeOrder2" :displayModeTypeMap="displayModeTypeMap2" v-model="showMode2" @change="displayModeChange2" />
      </div>
      <div class="flex-auto flex-col" style="display: flex" v-show="showMode === DisplayModeType.List && showMode2===DisplayModeType2.List">
         <div class="flex-auto" ref="containerRef" v-resize="resizeHandler" v-loading="queryLoading">
            <el-table
               ref="tableRef"
               :maxHeight="tableHeight"
               :cell-style="tableCellStyle"
               :header-cell-style="tableHeaderCellStyle"
               :data="tableData"
               @row-click="recordSelectChange"
               @sort-change="sortChange"
               :spanMethod="objectSpanMethod"
               class="w-full h-full"
               highlightCurrentRow
               :rowClassName="tableRowClassName"
               cellClassName="text-sm"
               headerCellClassName="text-sm"
            >
               <DefineColumns v-slot="{ cols }">
                  <template v-for="item in colList" :key="item.prop">
                     <el-table-column
                        v-if="item.isShow ?? true"
                        :type="item.type"
                        :label="item.label"
                        :width="item.width"
                        :sortable="item.sortable ? 'custom' : false"
                        :key="item.prop"
                        :prop="item.prop"
                        @sortChange="sortChange"
                        show-overflow-tooltip
                     />
                  </template>
               </DefineColumns>
               <el-table-column v-if="data?.title" :label="data?.title" show-overflow-tooltip>
                  <template v-if="tableCols.length > 0">
                     <template v-for="item in colList" :key="item.prop">
                        <el-table-column
                           v-if="item.isShow ?? true"
                           :type="item.type"
                           :label="item.label"
                           :width="item.width"
                           :sortable="item.sortable ? 'custom' : false"
                           :key="item.prop"
                           :prop="item.prop"
                           show-overflow-tooltip
                        />
                     </template>
                  </template>
               </el-table-column>
               <template v-else>
                  <template v-if="tableCols.length > 0">
                     <ReuseColumns :cols="colList" />
                  </template>
               </template>
            </el-table>
         </div>
         <el-pagination
            class="flex-0"
            style="margin-bottom: 0 !important; margin-left: auto !important; float: none !important"
            small
            hide-on-single-page
            v-model:current-page="pager.index"
            v-model:page-size="pager.size"
            layout="total,prev,pager,next,jumper"
            :total="pager.total"
         />
      </div>
      <div class="flex-auto" v-if="showMode2 === DisplayModeType2.Map">
         <MapView  :data="data"/>
      </div>
      <div class="flex-auto" v-resize="debounceResizeChart" v-show="showMode === DisplayModeType.Chart">
         <div ref="chartRef" style="height: 25rem"></div>
      </div>
      <InfoDetail class="text-base" v-model="infoDetailIsShow" :item="detailMapRow" :colList="colList" />
   </div>
</template>
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core';
import * as echarts from 'echarts';
import type { TableInstance } from 'element-plus';
import _ from 'lodash';
import { CSSProperties, onMounted, ref, type PropType } from 'vue';
import type { CSSProperties } from 'vue';
import { computed, nextTick, onMounted, reactive, ref, shallowRef, watchEffect, type PropType } from 'vue';
import { PATH_ICON } from '../../../common';
import { ChartTypeEnum } from '../../../types';
import { BORDER_COLOR, COL_HEADER_CELL_BG_COLOR, THICK_BORDER_WIDTH } from '../deviceLastValue/constants';
import { debounce, getTextWidth } from '/@/utils/util';
import DisplayMode from '../recordSet/components/DisplayMode.vue';
import { DisplayModeType, DisplayModeType2,displayModeTypeMap2,displayModeTypeMap } from '../recordSet/components/types';
import { RecordSetParamsType, recordSetMapCom } from '../recordSet/types';
import MapView from './map/Map.vue'
import InfoDetail from './infoDetail/InfoDetail.vue';
import { curveQuery } from '/@/api/ai/chat';
import ColFilter from '/@/components/table/colFilter/ColFilter.vue';
import { TableCol } from '/@/components/table/colFilter/types';
import { axisLabelFormatter } from '/@/utils/chart';
import { LocalPlus } from '/@/utils/storage';
import { debounce, getTextWidth, toPercent } from '/@/utils/util';
import { sortBy, chunk } from 'lodash-es';
const props = defineProps({
   data: {
      type: Object as PropType<any>,
   },
   originData: {
      type: Object as PropType<any>,
   },
   summaryIndex: {
      type: Number,
   },
   tableLimitHeight: {
      type: Number,
      required: false,
   },
   showFilter: {
      type: Boolean,
      default: true,
   },
   disabled: {
      type: Boolean,
      default: false,
   },
});
const [DefineColumns, ReuseColumns] = createReusableTemplate<{
   cols: any[];
}>();
const emits = defineEmits<{
   (event: 'updateQuery', res: any): void;
}>();
const checkIsTotalTable = (propsData) => {
   return propsData?.hasOwnProperty('agg_count_col') ?? false;
};
const isMap = computed(() => {
   return props.data?.hasOwnProperty('map') ?? false;
});
const isTotalTable = computed(() => checkIsTotalTable(props.data));
const getTableCols = (propsData) => {
   const current = propsData?.cols ?? [];
   if (checkIsTotalTable(propsData)) {
      current.push({
         title: '比例',
         type: 'text',
      });
   }
   return current;
};
// 统计表格,需要增加比例列
const tableCols = ref(getTableCols(props.data));
// 值列索引
let valueColIndex;
// 比例列索引
let rateColIndex;
// 总数
let sumValue;
const getTableValues = (propsData) => {
   const agg_count_col = propsData?.agg_count_col;
   const current = (propsData?.values ?? []) as Array<any[]>;
   if (checkIsTotalTable(propsData)) {
      const last = current[current.length - 1];
      const lastItemIndex = last?.length > 0 ? last.length - 1 : 0;
      valueColIndex = agg_count_col ?? lastItemIndex;
      rateColIndex = valueColIndex + 1;
      // 计算总数
      sumValue = current.reduce((pre, cur) => {
         const value = Number(cur[valueColIndex] ?? 0);
         pre += value;
         return pre;
      }, 0);
      // 计算比例,并放到比例行
      current.forEach((rowValue) => {
         const value = rowValue[valueColIndex];
         const rate = sumValue === 0 ? 0 : (value ?? 0) / sumValue;
         const percent = toPercent(rate, true, 2);
         rowValue.splice(rateColIndex, 0, percent);
      });
      // 添加合计行
      if (last?.length > 0) {
         const totalRow = new Array(last.length);
         let lastGroupIndex = tableCols.value.findLastIndex((item, index) => index !== rateColIndex && index !== valueColIndex);
         lastGroupIndex = lastGroupIndex === -1 ? 0 : lastGroupIndex;
         totalRow[lastGroupIndex] = '合计';
         // 比例列
         totalRow[rateColIndex] = '100%';
         // 合计总数
         totalRow[valueColIndex] = sumValue + '';
         (totalRow as any).isTotal = true;
         current.push(totalRow);
      }
   }
   return current;
};
const tableRowClassName = ({ row, rowIndex }) => {
   let className = 'cursor-pointer';
   if (row.isTotal) {
      const bgColor = '!bg-[#c5d9f1]';
      className += ` font-bold ${bgColor} hover:${bgColor} active:${bgColor}`;
   }
   return className;
};
// 统计表格,需要增加累计值行,以及比例列
const tableValues = ref(getTableValues(props.data));
const storeCols = (colList: any[]) => {
   const key = colList.map((item) => item.label).join(',');
   if (!key) return;
   LocalPlus.set(key, colList, 7);
};
const colList = ref([]);
const getStoreCols = (colList: any[]) => {
   if (colList.length === 0) return colList;
   const key = colList.map((item) => item.label).join(',');
   if (!key) return colList;
   const storeValue = LocalPlus.get(key);
   if (!storeValue) {
      return colList;
   } else {
      return storeValue;
   }
};
watchEffect(() => {
   const originData =
      tableCols.value?.map((item, index) => {
         let isShow = true;
         if (props.data.max_cols != null) {
            isShow = index < props.data.max_cols;
         }
         return {
            ...item,
            width: 0,
            label: item.title,
            sortable: !!item.name,
            prop: index + '',
            isShow: isShow,
         } as TableCol;
      }) ?? [];
   const storeCols = getStoreCols(originData);
   colList.value = storeCols;
});
// 所有显示的 prop
const visibleColProp = computed(() => colList.value.filter((item) => item.isShow == null || item.isShow).map((item) => item.prop));
const containerRef = ref<HTMLDivElement>(null);
const tableRef = ref<TableInstance>(null);
const measureWidthOffset = 28;
const groupColIndex = [];
(props.data?.cols ?? []).map((item, index) => {
   if (item.group) {
      groupColIndex.push(index);
   }
const filterGroupIndexList = computed(() => {
   const groupIndexList = [];
   tableCols.value.map((item, index) => {
      // 是分组,且当前可见
      if (item.group && visibleColProp.value.includes(index + '')) {
         groupIndexList.push(index);
      }
   });
   return groupIndexList;
});
const chunkTableData = ref([tableValues.value]);
// FIXME:  如果全部 group 都为 true,恰好最后多条记录也可以归为一组,很可能显示不对,少了几条重复的数据
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
   if (groupColIndex.includes(columnIndex)) {
   const key = `${rowIndex},${columnIndex}`;
   const rowspan = cellRowSpanMap.get(key);
   if (rowspan !== undefined) {
      return {
         rowspan: row.rowspan,
         rowspan,
         colspan: 1,
      };
   } else {
      return {
         rowspan: 1,
         colspan: 1,
      };
   }
};
// 单元格行合并情况
const cellRowSpanMap = new Map<string, number | undefined>();
/**
 * 构建分组结构,一组一组按层次构建
 * @param i 当前分组的索引位置
 * @param j 当前记录所在行位置
 */
const buildGroupData = (values, i = 0, j = 0) => {
   if (!values || values.length === 0) return [];
   const curGroupIndex = filterGroupIndexList.value[i];
   // 不可以分组,直接 return;
   if (curGroupIndex == undefined || values.length === 1) {
      return values;
   }
   const groupData = getItemMap(values, curGroupIndex, true);
   // 顺延下一个分组
   i++;
   // 重新排布一下位置,保证 group 相邻,同时打上 rowspan
   const result = Object.values(Array.from(groupData.values())).reduce((preVal, curVal) => {
      curVal.map((item, index) => {
         // 行列作为 key
         const key = `${j + index},${curGroupIndex}`;
         cellRowSpanMap.set(key, index === 0 ? curVal.length : 0);
      });
      preVal = preVal.concat(buildGroupData(curVal, i, j));
      j += curVal.length;
      return preVal;
   }, []);
   return result;
};
const getItemMap = <T>(arr: T[], defaultProps = 'ID', isMultiple = false) => {
   if (!arr || arr.length === 0) return {};
   const result = arr.reduce((acc, curr) => {
      if (isMultiple) {
         if (!acc.get(curr[defaultProps])) {
            acc.set(curr[defaultProps], [curr]);
         } else {
            {
               /* acc[curr[defaultProps]].push(curr); */
            }
            acc.get(curr[defaultProps]).push(curr);
         }
      } else {
         acc.set(curr[defaultProps], curr);
      }
      return acc;
   }, new Map()) as Map<string, T | T[]>;
   return result;
};
/**
 * 计算每一列的宽度
 * 1)总宽小于容器宽:直接按比例分
 * 2)总宽大于容器宽:先完全满足最小的宽度,直到到不满足宽度的地方,然后剩余宽度,按宽度比例分配
 * 3)计算完的宽度放在 colList.value 的 width 属性上
 * @param width
 */
const calcColWidth = (width) => {
   // 返回所有标题字符串
   const maxStrList = tableCols.value.map((item, index) => {
      if (visibleColProp.value.includes(index + '')) {
         return item.title;
      } else {
         return '';
      }
   });
   // 返回所有标题字符串长度
   const maxLenList = tableCols.value.map((item, index) => {
      if (visibleColProp.value.includes(index + '')) {
         return item.title.gblen();
      } else {
         return 0;
      }
   });
   // 计算每一列最长的标题字符串和标题字符串长度
   for (const item of tableValues.value) {
      item.map((subItem, index) => {
         // subItem 可能是 数字
         const subItemLen = (subItem + '')?.gblen();
         if (maxLenList[index] < subItemLen) {
            maxLenList[index] = subItemLen;
            maxStrList[index] = subItem;
         }
      });
   }
   // 总宽
   let sumWidth = 0;
   // 计算所有列实际列宽
   let maxWidthList = maxStrList.map((item, index) => {
      // 不可见列宽度为 0
      const width = !visibleColProp.value.includes(index + '')
         ? 0
         : getTextWidth(item, {
               size: '0.875rem',
           }) + measureWidthOffset;
      sumWidth += width;
      return {
         index,
         maxWidth: width,
      };
   });
   // 总宽小于容器宽度
   if (sumWidth <= width) {
      // 按比例分配宽度
      maxWidthList = maxWidthList.map((item) => ({
         ...item,
         width: (item.maxWidth / sumWidth) * width,
      }));
      // 先满足小的,剩余空间按比例均分
   } else {
      // 当前已满足宽度
      let curWidth = 0;
      // 排好序的宽度列表
      const sortedWidthList = sortBy(maxWidthList, 'maxWidth');
      // 剩余宽度
      let restWidth = width;
      let notFitStartIndex = 1;
      for (let index = 0; index < sortedWidthList.length; index++) {
         const item = sortedWidthList[index];
         // 加上当前宽度
         curWidth += item.maxWidth;
         // 没占满容器,或是最小的那个,直接取它的最大宽度
         if (curWidth <= width || index === 0) {
            maxWidthList[item.index].width = item.maxWidth;
            continue;
         }
         // 加上当前宽度超出当前容器,就不加,计算不加时的剩余宽度
         restWidth = width - (curWidth - item.maxWidth);
         // 当加上 index 索引处的宽度时,正好宽度超出容器
         notFitStartIndex = index;
         break;
      }
      // 剩余宽度
      let sumRestMaxWidth = 0;
      // 剩余加上会超出容器宽度的索引
      const notFitIndexList = sortedWidthList.slice(notFitStartIndex).map((item) => {
         sumRestMaxWidth += item.maxWidth;
         return item.index;
      });
      // 按 maxWidth 比例分配剩余空间
      for (const item of notFitIndexList) {
         maxWidthList[item].width = restWidth * (maxWidthList[item].maxWidth / sumRestMaxWidth);
         // if (maxWidthList[item].maxWidth <= restWidth) {
         //    maxWidthList[item].width = restWidth;
         // }
      }
   }
   colList.value.map((item, index) => {
      item.width = maxWidthList[index].width;
   });
};
const resizeEvent = ({ width, height }) => {
   if (width === 0 || height === 0) {
      return;
   }
   if (props.data?.cols?.length > 0 && props.data?.values?.length > 0) {
      const groupData = _.groupBy(props.data.values, (item, index) => {
         // 找出所有需要 group 的值,加起来
         const groupKey = item.reduce((preVal, curVal, index) => {
            const isGroup = props.data.cols[index].group;
            if (isGroup) {
               preVal += curVal;
            }
            return preVal;
         }, '');
         return groupKey;
   if (tableCols.value.length > 0) {
      cellRowSpanMap.clear();
      // tableValues.value = buildGroupData(tableValues.value);
      calcColWidth(width);
      nextTick(() => {
         calcPagerHeight();
      });
      // 重新排布一下位置,保证 group 相邻,同时打上 rowspan
      props.data.values = Object.values(groupData).reduce((preVal, curVal) => {
         curVal.map((item, index, array) => {
            item.rowspan = index === 0 ? array.length : undefined;
         });
         preVal = preVal.concat(curVal);
         return preVal;
      }, []);
      const maxStrList = props.data.cols.map((item) => item.title);
      const maxLenList = props.data.cols.map((item) => item.title.gblen());
      for (const item of props.data.values) {
         item.map((subItem, index) => {
            const subItemLen = subItem?.gblen();
            if (maxLenList[index] < subItemLen) {
               maxLenList[index] = subItemLen;
               maxStrList[index] = subItem;
            }
         });
      }
      // 总宽
      let sumWidth = 0;
      let maxWidthList = maxStrList.map((item, index) => {
         const width =
            getTextWidth(item, {
               size: '0.875rem',
            }) + measureWidthOffset;
         sumWidth += width;
         return {
            index,
            maxWidth: width,
         };
      });
      if (sumWidth <= width) {
         maxWidthList = maxWidthList.map((item) => ({
            ...item,
            width: (item.maxWidth / sumWidth) * width,
         }));
         // 先满足小的,剩余空间按比例均分
      } else {
         let curWidth = 0;
         const sortedWidthList = _.sortBy(maxWidthList, 'maxWidth');
         let restWidth = width;
         let notFitStartIndex = 1;
         for (let index = 0; index < sortedWidthList.length; index++) {
            const item = sortedWidthList[index];
            curWidth += item.maxWidth;
            if (curWidth < width || index === 0) {
               maxWidthList[item.index].width = item.maxWidth;
               continue;
            }
            restWidth = width - (curWidth - item.maxWidth);
            notFitStartIndex = index;
            break;
         }
         let sumRestMaxWidth = 0;
         const notFitIndexList = sortedWidthList.slice(notFitStartIndex).map((item) => {
            sumRestMaxWidth += item.maxWidth;
            return item.index;
         });
         // 平均分配剩余空间
         for (const item of notFitIndexList) {
            maxWidthList[item].width = restWidth * (maxWidthList[item].maxWidth / sumRestMaxWidth);
            if (maxWidthList[item].maxWidth <= restWidth) {
               maxWidthList[item].width = restWidth;
            }
            // maxWidthList[item].width = undefined;
         }
      }
      colList.value = props.data.cols.map((item, index) => ({
         ...item,
         width: maxWidthList[index].width,
      }));
   } else {
      colList.value = [];
   }
   tableRef.value.doLayout();
   setTimeout(() => {
      tableRef.value?.doLayout();
   }, 300);
};
const resizeHandler = debounce(resizeEvent);
@@ -195,7 +512,9 @@
const tableHeaderCellStyle = ({ row, rowIndex, column, columnIndex }): CSSProperties => {
   const extraStyle = {
      ...(columnIndex === 0 ? { borderLeft: `${THICK_BORDER_WIDTH}px solid ${BORDER_COLOR}` } : {}),
      ...(rowIndex === 0 ? { borderTop: `${THICK_BORDER_WIDTH}px solid ${BORDER_COLOR}`, backgroundColor: '#8db4e2',fontSize: '1rem'} : {}),
      ...(rowIndex === 0
         ? { borderTop: `${THICK_BORDER_WIDTH}px solid ${BORDER_COLOR}`, backgroundColor: '#8db4e2', fontSize: '1rem' }
         : {}),
   };
   return {
@@ -210,12 +529,599 @@
   };
}; //#endregion
//#region ====================== 分页 ======================
const pager = reactive({
   index: 1,
   size: 10,
   total: tableValues.value.length ?? 0,
});
const calcCellHeight = (count, cellHeight) => {
   return count * cellHeight + count * THICK_BORDER_WIDTH;
};
/**
 * 计算分页表格宽度
 */
const calcPagerHeight = () => {
   // 表格内容单元格高度
   const cellHeight = tableRef.value.$el.querySelector('.el-table__body .el-table__cell[rowspan="1"]')?.clientHeight ?? 39;
   const headerHeight = tableRef.value.$el.querySelector('.el-table__header-wrapper').clientHeight;
   // 限制高度
   const limitHeight = props.tableLimitHeight ?? containerRef.value.clientHeight;
   // 求 size
   // size*cellHeight + size*THICK_BORDER_WIDTH + headerHeight <= limitHeight;
   // size <= (limitHeight - headerHeight)/(cellHeight+THICK_BORDER_WIDTH);
   // 一页有  pager.size,条记录
   pager.size = Math.floor((limitHeight - headerHeight) / (cellHeight + THICK_BORDER_WIDTH));
   const currentHeight = calcCellHeight(pager.size, cellHeight) + headerHeight;
   tableHeight.value = currentHeight;
   tableRef.value.doLayout();
   // pager.index = 1;
   chunkTableData.value = chunk(tableValues.value ?? [], pager.size);
};
//#endregion
const tableData = computed(() => buildGroupData(chunkTableData.value[pager.index - 1]));
const reloadTable = () => {
   // 重新计算宽度
   resizeEvent({ width: containerRef.value.clientWidth, height: containerRef.value.clientHeight });
};
const colFilterChange = () => {
   // 重新计算宽度
   reloadTable();
   storeCols(colList.value);
};
const tableHeight = ref(0.7 * document.body.clientHeight);
//#region ======================  ======================
const infoDetailIsShow = ref(false);
const detailMapRow = ref(null);
// 是否已经显示所有列了
const haveShowAll = computed(() => visibleColProp.value.length === colList.value.length);
const recordSelectChange = (row) => {
   if (haveShowAll.value) return;
   detailMapRow.value = row;
   infoDetailIsShow.value = true;
};
//#endregion
onMounted(() => {
   resizeEvent({
      width: containerRef.value.clientWidth,
      height: 0.7 * document.body.clientHeight,
   });
});
//#region ====================== 表格过滤参数 ======================
const getFilterList = () => {
   const curAgentKey = props.data.agent_key;
   // 相同 agent_key 下所有 filter 请求参数
   const filterList = ((props as any).originData?.content?.origin?.summary ?? []).reduce((preVal, curVal) => {
      if (curVal.agent_key !== curAgentKey) return preVal;
      const filter = (curVal.filter ?? []).reduce((subPreVal, subCurVal) => {
         if (subCurVal.type === RecordSetParamsType.StringInput) {
            subPreVal.push({
               update: subCurVal.update,
               value: subCurVal.value,
               path: subCurVal.path,
            });
         } else if (subCurVal.type === RecordSetParamsType.TimeRange) {
            subPreVal.push(
               ...[
                  {
                     update: subCurVal.update,
                     value: subCurVal.start_value,
                     path: subCurVal.start_path,
                  },
                  {
                     update: subCurVal.update,
                     value: subCurVal.end_value,
                     path: subCurVal.end_path,
                  },
               ]
            );
         } else if (subCurVal.type === RecordSetParamsType.Step) {
            subPreVal.push({
               update: subCurVal.update,
               value: subCurVal.step_value,
               path: subCurVal.step_path,
            });
         }
         return subPreVal;
      }, []);
      preVal = preVal.concat(filter);
      return preVal;
   }, []);
   return filterList;
};
const queryLoading = ref(false);
let orderDimName = '';
const queryUpdate = async (val?: any, item?: any) => {
   const historyId = (props as any).originData.historyId;
   let res = null;
   if (item) {
      // 改变原始值
      if (item.type === RecordSetParamsType.StringInput) {
         item.origin.value = val;
      } else if (item.type === RecordSetParamsType.TimeRange) {
         item.origin.start_value = val[0];
         item.origin.end_value = val[1];
      } else if (item.type === RecordSetParamsType.Step) {
         item.origin.step_value = val;
      }
   }
   const filterList = getFilterList();
   try {
      const params = {
         history_id: historyId,
         // 查询前后 agent_key 不会变
         agent_key: props.data.agent_key,
         filter_json: JSON.stringify(filterList),
         order_dim_name: orderDimName,
      };
      res = await curveQuery(params);
      queryLoading.value = true;
   } finally {
      queryLoading.value = false;
   }
   emits('updateQuery', res);
};
const debounceQueryUpdate = debounce(queryUpdate, 600);
const handleQueryChange = async (val: any, item: any) => {
   if (item.type === RecordSetParamsType.StringInput) {
      debounceQueryUpdate(val, item);
   } else {
      queryUpdate(val, item);
   }
};
//#endregion
const stepOptions = [
   { title: '5分钟', value: '5 minutes' },
   { title: '10分钟', value: '10 minutes' },
   { title: '半小时', value: '30 minutes' },
   { title: '1小时', value: '1 hours' },
   { title: '1天', value: '1 days' },
];
const getVisibleParams = (data) => {
   // const visibleList = props.data?.params?.filter((item) => !item?.hide) ?? [];
   // index 作为 id
   const visibleList = (data?.filter ?? []).map((item, index) => {
      // 不修改原始地址
      item.id = index + '';
      return item;
   });
   const newList: any[] = [];
   for (let index = 0; index < visibleList.length; index++) {
      const current = visibleList[index];
      switch (current.type) {
         case RecordSetParamsType.TimeRange:
            newList.push({
               id: current.id,
               type: RecordSetParamsType.TimeRange,
               origin: current,
               value: [current.start_value, current.end_value],
               title: current.title,
            });
            break;
         case RecordSetParamsType.Step:
            newList.push({
               id: current.id,
               type: RecordSetParamsType.Step,
               origin: current,
               value: current.step_value,
               list: stepOptions,
               title: current.title,
            });
            break;
         case RecordSetParamsType.StringInput:
            newList.push({
               id: current.id,
               type: RecordSetParamsType.StringInput,
               origin: current,
               value: current?.value ?? '',
               title: current.title,
            });
            break;
         default:
            break;
      }
      Reflect.deleteProperty(current, 'id');
   }
   return newList;
};
const visibleParams = ref(getVisibleParams(props.data));
const updateFilterValue = (data) => {
   const filter = data?.filter ?? [];
   filter.map((newItem, index) => {
      const currentItem = visibleParams.value.find((item) => item.id === index + '');
      if (currentItem) {
         if (newItem.type === RecordSetParamsType.StringInput) {
            currentItem.value = newItem.value;
         }
      }
   });
};
const resetPager = (data) => {
   pager.index = 1;
   pager.total = tableValues.value.length ?? 0;
};
let needUpdateChart = false;
const updateCurrent = (res) => {
   const title = res?.title;
   props.data.title = title;
   tableValues.value = getTableValues(res);
   // 不更新,后端压根没返回
   // updateFilterValue(res);
   resetPager(res);
   reloadTable();
   if (showMode.value === DisplayModeType.List) {
      needUpdateChart = true;
   } else {
      updateChart();
   }
};
// 查询
const updateAll = (triggerIndex, res) => {
   // 当前 agent_key
   const curAgentKey = props.data.agent_key;
   const triggerAgentKey = (props as any).originData?.content?.origin?.summary?.[triggerIndex]?.agent_key;
   if (curAgentKey !== triggerAgentKey) {
      return;
   }
   if (!curAgentKey) {
      return;
   }
   // 当前项所在索引
   let currentIndex = -1;
   for (let index = 0; index < (props as any).originData.content.origin.summary.length; index++) {
      const item = (props as any).originData.content.origin.summary[index];
      if (item.agent_key === curAgentKey) {
         currentIndex++;
         if (index === props.summaryIndex) {
            break;
         }
      }
   }
   // 表格 summary 可能整个返回为空,为空时,values 设置为空
   const newSummary = res?.summary?.[currentIndex] ?? {
      title: props.data.title,
      values: [],
   };
   updateCurrent(newSummary);
};
const updateIndexSummary = (summary) => {
   updateCurrent(summary?.[props.summaryIndex]);
};
//#region ====================== 模式切换 ======================
const showMode = ref(DisplayModeType.List);
const modeChangeOrder = [DisplayModeType.List, DisplayModeType.Chart];
const chartRef = ref<HTMLDivElement>(null);
const chartInstance = shallowRef<echarts.ECharts>(null);
const debounceResizeChart = debounce(({ width, height }) => {
   if (width === 0 || height === 0) return;
   chartInstance.value?.resize({
      width,
      height,
   });
});
let groupTitle;
let activeChartType: ChartTypeEnum = ChartTypeEnum.Bar;
const getChartData = (values: Array<any[]>) => {
   // 排除合计行;
   const groupValues = values.slice(0, values.length - 1);
   const excludeIndex = [rateColIndex];
   const groupCols = tableCols.value.filter((item, index) => !excludeIndex.includes(index) && index !== valueColIndex);
   // 取最后一个作为 title
   groupTitle = groupCols[groupCols.length - 1].title;
   const data = groupValues.map((item) => {
      const groupName = item.filter((item, index) => !excludeIndex.includes(index) && index !== valueColIndex).join('_');
      const value = item[valueColIndex];
      return {
         value,
         name: groupName,
      };
   });
   return data;
};
const getCommonOption = () => {
   return {
      title: {
         text: props.data.title,
         left: 'center',
         textStyle: {
            fontSize: 14,
         },
      },
      legend: {
         type: 'scroll',
         // orient:'vertical',
         top: 33,
         left: 'center',
      },
      tooltip: {
         trigger: 'item',
         valueFormatter: (value) => `${value} / ${toPercent(sumValue === 0 ? 0 : (value as number) / sumValue, true, 2)}`,
      },
   } as echarts.EChartsOption;
};
const getPieOption = (chartData: any[]) => {
   // const labelFormatter = chartData.length > 9 ? '{b}' : '{b}\n{c}/{d}%';
   const labelFormatter = '{b}: {c} / {d}%';
   return {
      series: [
         {
            type: 'pie',
            radius: ['20%', '55%'],
            center: ['50%', '55%'],
            label: {
               show: true,
               // formatter: '{b}: {c}({d}%)', //自定义显示格式(b:name, c:value, d:百分比)
            },
            bottom: 0,
            itemStyle: {
               normal: {
                  label: {
                     formatter: labelFormatter,
                     // formatter: '{b}',
                  },
                  borderColor: '#ffffff',
                  borderWidth: 5,
               },
            },
            data: chartData,
         },
      ],
   } as echarts.EChartsOption;
};
const getBarOption = (chartData: any[]) => {
   const barData = chartData.map((item) => item.value);
   const right = groupTitle
      ? {
            right: 60,
        }
      : {
            right: 30,
        };
   const xData = chartData.map((item) => item.name);
   return {
      grid: {
         top: 65,
         left: 30,
         ...right,
         bottom: 0,
         containLabel: true,
      },
      xAxis: {
         name: groupTitle,
         type: 'category',
         data: xData,
         axisLabel: {
            fontSize: 12,
            // formatter: function (value) {
            //    if (value.length > 6) {
            //       return value.substr(0, 6) + '...';
            //    } else {
            //       return value;
            //    }
            // },
            width: 86,
            overflow: 'truncate',
            // nameTruncate: {
            //    maxWidth: 52,
            // },
            rotate: 30,
         },
         nameTextStyle: {
            padding: [-15, 0, 0, -10],
            align: 'left',
            verticalAlign: 'top',
            // color: '#fff',
         },
         nameTruncate: {
            maxWidth: 52,
         },
      },
      yAxis: {
         name: tableCols.value[valueColIndex].title,
         type: 'value',
         axisLabel: {
            formatter: axisLabelFormatter,
         },
      },
      series: {
         type: 'bar',
         data: barData,
         label: {
            show: true,
            position: 'outside',
            formatter: (params) => {
               const value = params.value;
               return `${value} / ${toPercent(sumValue === 0 ? 0 : (value as number) / sumValue, true, 2)}`;
            },
            fontSize: 10,
         },
      },
      dataZoom: {
         type: 'inside',
      },
   } as echarts.EChartsOption;
};
const getChartOption = (chartData: any[]) => {
   let typeOption: echarts.EChartsOption = {};
   if (activeChartType === ChartTypeEnum.Pie) {
      typeOption = getPieOption(chartData);
   } else if (activeChartType === ChartTypeEnum.Bar) {
      typeOption = getBarOption(chartData);
   }
   const option: echarts.EChartsOption = {
      ...getCommonOption(),
      toolbox: {
         show: true,
         feature: {
            myBar: {
               title: '转化为柱状图',
               show: true,
               icon: PATH_ICON.bar,
               onclick: () => {
                  activeChartType = ChartTypeEnum.Bar;
                  chartInstance.value.setOption(
                     {
                        ...getCommonOption(),
                        toolbox: option.toolbox,
                        ...getBarOption(chartData),
                     },
                     {
                        notMerge: true,
                     }
                  );
               },
            },
            myPie: {
               title: '转化为饼状图',
               show: true,
               icon: PATH_ICON.pie,
               onclick: () => {
                  activeChartType = ChartTypeEnum.Pie;
                  chartInstance.value.setOption(
                     {
                        ...getCommonOption(),
                        toolbox: option.toolbox,
                        ...getPieOption(chartData),
                     },
                     {
                        notMerge: true,
                     }
                  );
               },
            },
            saveAsImage: {},
         },
      },
      ...typeOption,
   };
   return option;
};
const updateChart = () => {
   const chartData = getChartData(tableValues.value);
   const option = getChartOption(chartData);
   nextTick(() => {
      if (!chartInstance.value) {
         chartInstance.value = echarts.init(chartRef.value);
      }
      chartInstance.value.setOption(option, {
         notMerge: true,
      });
   });
};
const displayModeChange = (val: DisplayModeType) => {
   if (val === DisplayModeType.Chart) {
      if (!chartInstance.value || needUpdateChart) {
         updateChart();
         needUpdateChart = false;
      }
   }
};
//#endregion
const orderMap = new Map();
const sortChange = ({ column, prop, order }) => {
   // 恢复原状,更新后再显示排序状态
   const curOrder = orderMap.get(prop) ?? null;
   column.order = curOrder;
   let sendOrder;
   if (order === 'descending') {
      sendOrder = 'desc';
   } else if (order === 'ascending') {
      sendOrder = 'asc';
   } else {
      sendOrder = '';
   }
   const colName = colList.value[prop].name;
   const sendOrderName = sendOrder ? `${colName},${sendOrder}` : '';
   orderDimName = sendOrderName;
   queryUpdate().then(()=>{
      orderMap.set(prop,order);
      column.order = order;
   });
};
// 地图模式展示
const showMode2 = ref(DisplayModeType2.List);
const modeChangeOrder2 = [DisplayModeType2.List, DisplayModeType2.Map];
const displayModeChange2 = (val: DisplayModeType2) => {
   if (val === DisplayModeType2.Map) {
      //if (!chartInstance.value || needUpdateChart) {
         //updateChart();
         //needUpdateChart = false;
      //}
   }
};
defineExpose({
   updateAll,
   updateCurrent,
   updateIndexSummary,
});
</script>
<style scoped lang="scss">
// :deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell){