wujingjing
2024-11-27 a32fc7bdf0ae1fccecfee1228e7348b8f2c478a6
src/components/chat/chatComponents/summaryCom/components/recordSetTable/RecordSetTable.vue
@@ -1,10 +1,11 @@
<!-- 查询最新警告信息 -->
<template>
   <div class="w-full flex-column">
      <div class="flex-0 flex-items-center mb-1 h-[38px]">
      <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"
               :class="{ invisible: showMode2 === DisplayModeType2.Map }"
               v-model="visibleParams[index].value"
               v-for="(item, index) in visibleParams as any"
               :key="item.id"
@@ -13,25 +14,48 @@
               :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" @change="displayModeChange" />
         <DisplayMode
            v-if="isTotalTable"
            class="ml-auto"
            :order="modeChangeOrder"
            v-model="showMode"
            :displayModeTypeMap="displayModeTypeMap"
            @change="displayModeChange"
         />
         <div class="ml-auto space-x-2 flex-items-center">
            <ColFilter v-if="!isTotalTable" :columnList="colList" @change="colFilterChange" />
            <DisplayMode
               v-if="isMap"
               :order="modeChangeOrder2"
               :displayModeTypeMap="displayModeTypeMap2"
               v-model="showMode2"
               @change="displayModeChange2"
            />
         </div>
      </div>
      <div class="flex-auto flex-col" style="display: flex" v-show="showMode === DisplayModeType.List">
      <div
         class="flex-auto flex-col"
         style="display: flex"
         v-show="(isTotalTable && showMode === DisplayModeType.List) || (isMap && 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="chunkTableData[pager.index - 1]"
               :data="tableData"
               @row-click="recordSelectChange"
               rowClassName="cursor-pointer"
               @sort-change="sortChange"
               :spanMethod="objectSpanMethod"
               class="w-full h-full"
               highlightCurrentRow
               :rowClassName="tableRowClassName"
               cellClassName="text-sm"
               headerCellClassName="text-sm"
            >
@@ -42,9 +66,10 @@
                        :type="item.type"
                        :label="item.label"
                        :width="item.width"
                        :sortable="item.sortable"
                        :sortable="item.sortable ? 'custom' : false"
                        :key="item.prop"
                        :prop="item.prop"
                        @sortChange="sortChange"
                        show-overflow-tooltip
                     />
                  </template>
@@ -57,7 +82,7 @@
                           :type="item.type"
                           :label="item.label"
                           :width="item.width"
                           :sortable="item.sortable"
                           :sortable="item.sortable ? 'custom' : false"
                           :key="item.prop"
                           :prop="item.prop"
                           show-overflow-tooltip
@@ -85,6 +110,10 @@
         />
      </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>
@@ -95,22 +124,25 @@
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core';
import * as echarts from 'echarts';
import type { TableInstance } from 'element-plus';
import _ from 'lodash';
import type { CSSProperties } from 'vue';
import { computed, nextTick, onMounted, reactive, ref, type PropType, watchEffect, shallowRef } 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 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 InfoDetail from './infoDetail/InfoDetail.vue';
import StringInput from './components/StringInput.vue';
import { curveQuery } from '/@/api/ai/chat';
import { RecordSetParamsType, recordSetMapCom } from '../recordSet/types';
import { DisplayModeType } from '../recordSet/components/types';
import DisplayMode from '../recordSet/components/DisplayMode.vue';
import * as echarts from 'echarts';
import { PATH_ICON } from '../../../common';
import { sortBy, chunk } from 'lodash-es';
const props = defineProps({
   data: {
@@ -130,6 +162,10 @@
      type: Boolean,
      default: true,
   },
   disabled: {
      type: Boolean,
      default: false,
   },
});
const [DefineColumns, ReuseColumns] = createReusableTemplate<{
@@ -143,9 +179,15 @@
   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: '比例',
@@ -190,23 +232,52 @@
      // 添加合计行
      if (last?.length > 0) {
         const totalRow = new Array(last.length);
         totalRow[0] = '合计';
         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(() => {
   colList.value =
   const originData =
      tableCols.value?.map((item, index) => {
         let isShow = true;
         if (props.data.max_cols != null) {
@@ -216,11 +287,14 @@
            ...item,
            width: 0,
            label: item.title,
            // sortable: item.type === 'time',
            sortable: !!item.name,
            prop: index + '',
            isShow: isShow,
         } as TableCol;
      }) ?? [];
   const storeCols = getStoreCols(originData);
   colList.value = storeCols;
});
// 所有显示的 prop
@@ -277,14 +351,11 @@
      return values;
   }
   const groupData = _.groupBy(values, (item, index) => {
      const groupValue = item[curGroupIndex];
      return groupValue;
   });
   const groupData = getItemMap(values, curGroupIndex, true);
   // 顺延下一个分组
   i++;
   // 重新排布一下位置,保证 group 相邻,同时打上 rowspan
   const result = Object.values(groupData).reduce((preVal, curVal) => {
   const result = Object.values(Array.from(groupData.values())).reduce((preVal, curVal) => {
      curVal.map((item, index) => {
         // 行列作为 key
         const key = `${j + index},${curGroupIndex}`;
@@ -295,6 +366,28 @@
      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;
};
@@ -325,7 +418,8 @@
   // 计算每一列最长的标题字符串和标题字符串长度
   for (const item of tableValues.value) {
      item.map((subItem, index) => {
         const subItemLen = subItem?.gblen();
         // subItem 可能是 数字
         const subItemLen = (subItem + '')?.gblen();
         if (maxLenList[index] < subItemLen) {
            maxLenList[index] = subItemLen;
            maxStrList[index] = subItem;
@@ -360,7 +454,7 @@
      // 当前已满足宽度
      let curWidth = 0;
      // 排好序的宽度列表
      const sortedWidthList = _.sortBy(maxWidthList, 'maxWidth');
      const sortedWidthList = sortBy(maxWidthList, 'maxWidth');
      // 剩余宽度
      let restWidth = width;
      let notFitStartIndex = 1;
@@ -405,7 +499,7 @@
   }
   if (tableCols.value.length > 0) {
      cellRowSpanMap.clear();
      tableValues.value = buildGroupData(tableValues.value);
      // tableValues.value = buildGroupData(tableValues.value);
      calcColWidth(width);
      nextTick(() => {
         calcPagerHeight();
@@ -489,19 +583,23 @@
   tableRef.value.doLayout();
   // pager.index = 1;
   chunkTableData.value = _.chunk(tableValues.value ?? [], pager.size);
   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);
@@ -525,69 +623,79 @@
});
//#region ====================== 表格过滤参数 ======================
const queryLoading = ref(false);
const queryUpdate = async (val: any, item: any) => {
   const historyId = (props as any).originData.historyId;
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.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;
   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 {
      // 相同 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;
      }, []);
      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;
@@ -754,6 +862,8 @@
});
let groupTitle;
let activeChartType: ChartTypeEnum = ChartTypeEnum.Bar;
const getChartData = (values: Array<any[]>) => {
   // 排除合计行;
   const groupValues = values.slice(0, values.length - 1);
@@ -764,7 +874,7 @@
   groupTitle = groupCols[groupCols.length - 1].title;
   const data = groupValues.map((item) => {
      const groupName = item.filter((item, index) => !excludeIndex.includes(index) && index !== valueColIndex).join(',');
      const groupName = item.filter((item, index) => !excludeIndex.includes(index) && index !== valueColIndex).join('_');
      const value = item[valueColIndex];
      return {
         value,
@@ -775,14 +885,8 @@
   return data;
};
const getPieOption = (chartData: any[]) => {
   // const labelFormatter = chartData.length > 9 ? '{b}' : '{b}\n{c}/{d}%';
   const labelFormatter = '{b}: {c} / {d}%';
   const option: echarts.EChartsOption = {
      // grid:{
      //    containLabel:true
      // },
const getCommonOption = () => {
   return {
      title: {
         text: props.data.title,
         left: 'center',
@@ -790,99 +894,24 @@
            fontSize: 14,
         },
      },
      tooltip: {
         trigger: 'item',
         valueFormatter: (value) => `${value}(${toPercent(sumValue === 0 ? 0 : (value as number) / sumValue, true, 2)})`,
      },
      legend: {
         type: 'scroll',
         // orient:'vertical',
         top: 33,
         left: 'center',
      },
      toolbox: {
         show: true,
         feature: {
            myBar: {
               title: '转化为柱状图',
               show: true,
               icon: PATH_ICON.bar,
               onclick: () => {
                  const barData = chartData.map((item) => item.value);
                  const right = groupTitle
                     ? {
                           right: 60,
                       }
                     : {
                           right: 30,
                       };
                  const xData = chartData.map((item) => item.name);
                  chartInstance.value.setOption({
                     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;
                              }
                           },
                           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',
                     },
                     series: {
                        type: 'bar',
                        data: barData,
                        label: {
                           show: true,
                           position: 'outside',
                        },
                     },
                     dataZoom: {
                        type: 'inside',
                     },
                  });
               },
            },
            myPie: {
               title: '转化为饼状图',
               show: true,
               icon: PATH_ICON.pie,
               onclick: () => {
                  chartInstance.value.setOption(getPieOption(chartData), {
                     notMerge: true,
                  });
               },
            },
            saveAsImage: {},
         },
      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',
@@ -890,7 +919,7 @@
            center: ['50%', '55%'],
            label: {
               show: true,
               formatter: '{b}: {c}({d}%)', //自定义显示格式(b:name, c:value, d:百分比)
               // formatter: '{b}: {c}({d}%)', //自定义显示格式(b:name, c:value, d:百分比)
            },
            bottom: 0,
            itemStyle: {
@@ -907,20 +936,157 @@
            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 = getPieOption(chartData);
   const option = getChartOption(chartData);
   nextTick(() => {
      if(!chartInstance.value){
      if (!chartInstance.value) {
         chartInstance.value = echarts.init(chartRef.value);
      }
      chartInstance.value.setOption(option);
      chartInstance.value.setOption(option, {
         notMerge: true,
      });
   });
};
const displayModeChange = (val: DisplayModeType) => {
@@ -933,6 +1099,42 @@
};
//#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.Map);
const modeChangeOrder2 = [DisplayModeType2.Map, DisplayModeType2.List];
const displayModeChange2 = (val: DisplayModeType2) => {
   if (val === DisplayModeType2.Map) {
      //if (!chartInstance.value || needUpdateChart) {
      //updateChart();
      //needUpdateChart = false;
      //}
   }
};
defineExpose({
   updateAll,
   updateCurrent,