wujingjing
2024-10-21 6dc8a04ea58dbcf253104504f1507997cc866ee6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
<!-- 查询最新警告信息 -->
<template>
    <div>
        <!-- <span v-if="data?.title" class="text-base font-bold flex-center mb-5">{{ data?.title }}</span> -->
        <div class="w-full flex-column">
            <div class="flex-0 flex-items-center mb-1 h-[38px] ">
                <template v-if="visibleParams && visibleParams.length > 0">
                    <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="recordSetTableMap[item.type]"
                        :data="item"
                        @change="(val) => handleQueryChange(val, item)"
                        :originData="originData"
                    ></component>
                    
                </template>
 
                <ColFilter class="ml-auto" :columnList="colList" @change="colFilterChange" />
            </div>
            <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]"
                    @row-click="recordSelectChange"
                    rowClassName="cursor-pointer"
                    :spanMethod="objectSpanMethod"
                    class="w-full h-full"
                    highlightCurrentRow
                    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"
                                :key="item.prop"
                                :prop="item.prop"
                                show-overflow-tooltip
                            />
                        </template>
                    </DefineColumns>
                    <el-table-column v-if="data?.title" :label="data?.title" show-overflow-tooltip>
                        <template v-if="data?.cols?.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"
                                    :key="item.prop"
                                    :prop="item.prop"
                                    show-overflow-tooltip
                                />
                            </template>
                        </template>
                    </el-table-column>
                    <template v-else>
                        <template v-if="data?.cols?.length > 0">
                            <ReuseColumns :cols="colList" />
                        </template>
                    </template>
                </el-table>
            </div>
 
            <el-pagination
                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"
            />
 
            <InfoDetail class="text-base" v-model="infoDetailIsShow" :item="detailMapRow" :colList="colList" />
        </div>
    </div>
</template>
 
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core';
import type { TableInstance } from 'element-plus';
import _ from 'lodash';
import type { CSSProperties } from 'vue';
import { computed, nextTick, onMounted, reactive, ref, type PropType, watchEffect } from 'vue';
import { BORDER_COLOR, COL_HEADER_CELL_BG_COLOR, THICK_BORDER_WIDTH } from '../deviceLastValue/constants';
import ColFilter from '/@/components/table/colFilter/ColFilter.vue';
import { TableCol } from '/@/components/table/colFilter/types';
import { debounce, getTextWidth } from '/@/utils/util';
import InfoDetail from './infoDetail/InfoDetail.vue';
import { RecordSetTableType, recordSetTableMap } from './types';
import StringInput from './components/StringInput.vue';
import { curveQuery } from '/@/api/ai/chat';
 
const props = defineProps({
    data: {
        type: Object as PropType<any>,
    },
    originData: {
        type: Object as PropType<any>,
    },
    summaryIndex: {
        type: Number,
    },
});
 
const [DefineColumns, ReuseColumns] = createReusableTemplate<{
    cols: any[];
}>();
const emits = defineEmits<{
    (event: 'updateQuery', res: any): void;
}>();
 
const colList = ref([]);
watchEffect(() => {
    colList.value =
        props.data.cols?.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.type === 'time',
                prop: index + '',
                isShow: isShow,
            } as TableCol;
        }) ?? [];
});
 
// 所有显示的 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 filterGroupIndexList = computed(() => {
    const groupIndexList = [];
 
    (props.data?.cols ?? []).map((item, index) => {
        // 是分组,且当前可见
        if (item.group && visibleColProp.value.includes(index + '')) {
            groupIndexList.push(index);
        }
    });
 
    return groupIndexList;
});
 
const chunkTableData = ref([props.data?.values]);
// FIXME:  如果全部 group 都为 true,恰好最后多条记录也可以归为一组,很可能显示不对,少了几条重复的数据
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    const key = `${rowIndex},${columnIndex}`;
    const rowspan = cellRowSpanMap.get(key);
    if (rowspan !== undefined) {
        return {
            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 = _.groupBy(values, (item, index) => {
        const groupValue = item[curGroupIndex];
        return groupValue;
    });
    // 顺延下一个分组
    i++;
    // 重新排布一下位置,保证 group 相邻,同时打上 rowspan
    const result = Object.values(groupData).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;
};
 
/**
 * 计算每一列的宽度
 * 1)总宽小于容器宽:直接按比例分
 * 2)总宽大于容器宽:先完全满足最小的宽度,直到到不满足宽度的地方,然后剩余宽度,按宽度比例分配
 * 3)计算完的宽度放在 colList.value 的 width 属性上
 * @param width
 */
const calcColWidth = (width) => {
    // 返回所有标题字符串
    const maxStrList = props.data.cols.map((item, index) => {
        if (visibleColProp.value.includes(index + '')) {
            return item.title;
        } else {
            return '';
        }
    });
    // 返回所有标题字符串长度
    const maxLenList = props.data.cols.map((item, index) => {
        if (visibleColProp.value.includes(index + '')) {
            return item.title.gblen();
        } else {
            return 0;
        }
    });
    // 计算每一列最长的标题字符串和标题字符串长度
    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) => {
        // 不可见列宽度为 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 ) {
        cellRowSpanMap.clear();
        props.data.values = buildGroupData(props.data.values);
        calcColWidth(width);
        nextTick(() => {
            calcPagerHeight();
        });
    }
 
    setTimeout(() => {
        tableRef.value?.doLayout();
    }, 300);
};
 
const resizeHandler = debounce(resizeEvent);
//#region ====================== 样式 ======================
const tableCellStyle = ({ row, rowIndex, column, columnIndex }): CSSProperties => {
    const extraStyle = {
        ...(columnIndex === 0 ? { borderLeft: `${THICK_BORDER_WIDTH}px solid ${BORDER_COLOR}` } : {}),
    };
 
    return {
        textAlign: 'center',
        borderColor: BORDER_COLOR,
        borderWidth: `${THICK_BORDER_WIDTH}px`,
        color: '#7331a5',
        fontSize: '0.875rem',
        ...extraStyle,
    };
};
 
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' }
            : {}),
    };
 
    return {
        textAlign: 'center',
        borderColor: BORDER_COLOR,
        borderWidth: `${THICK_BORDER_WIDTH}px`,
        backgroundColor: COL_HEADER_CELL_BG_COLOR,
        fontWeight: 700,
        fontSize: '0.875rem',
        color: '#000',
        ...extraStyle,
    };
}; //#endregion
 
//#region ====================== 分页 ======================
const pager = reactive({
    index: 1,
    size: 10,
    total: props.data?.values?.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 = document.body.clientHeight * 0.7;
 
    // 求 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(props.data.values ?? [], pager.size);
};
 
//#endregion
 
const reloadTable = () => {
    // 重新计算宽度
 
    resizeEvent({ width: containerRef.value.clientWidth, height: containerRef.value.clientHeight });
};
const colFilterChange = () => {
    // 重新计算宽度
    reloadTable();
};
 
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 queryLoading = ref(false);
const queryUpdate = async (val: any, item: any) => {
    const historyId = (props as any).originData.historyId;
    const curAgentKey = props.data.agent_key;
    let res = null;
 
    // 改变原始值
    if (item.type === RecordSetTableType.StringInput) {
        item.origin.value = val;
    }
    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 === RecordSetTableType.StringInput) {
                    subPreVal.push({
                        update: subCurVal.update,
                        value: subCurVal.value,
                        path: subCurVal.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),
        };
        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 === RecordSetTableType.StringInput) {
        debounceQueryUpdate(val, item);
    }
 
    // queryUpdate(val,item)
 
    return;
};
 
//#endregion
 
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 RecordSetTableType.StringInput:
                newList.push({
                    id: current.id,
                    type: RecordSetTableType.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 === RecordSetTableType.StringInput) {
                currentItem.value = newItem.value;
            }
        }
    });
};
 
const resetPager = (data) => {
    pager.index = 1;
    pager.total = data?.values?.length ?? 0;
};
const updateCurrent = (res) => {
    const title = res?.title;
    const values = res?.values ?? [];
    props.data.title = title;
    props.data.values = values;
    // 不更新,后端压根没返回
    // updateFilterValue(res);
    resetPager(res);
 
    reloadTable();
};
// 查询
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);
};
 
defineExpose({
    updateAll,
});
</script>
<style scoped lang="scss">
// :deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell){
//     background-color: v-bind(stripedBgColor);
// }
</style>