wujingjing
2024-09-30 5e78e5bc69a8b7abf76663acaab6b7da63f35aa2
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
<!-- 查询最新警告信息 -->
<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" ref="containerRef" v-resize="resizeHandler">
            <el-table
                ref="tableRef"
                :height="tableHeight"
                border
                :cell-style="tableCellStyle"
                :header-cell-style="tableHeaderCellStyle"
                :data="chunkTableData[pager.index - 1]"
                :spanMethod="objectSpanMethod"
                class="w-full h-full"
                cellClassName="text-sm"
                headerCellClassName="text-sm"
            >
                <DefineColumns v-slot="{ cols }">
                    <el-table-column
                        v-for="(item, index) in cols"
                        :label="item.title"
                        :width="item.width"
                        :sortable="item.type === 'time'"
                        :key="index"
                        :prop="index + ''"
                        show-overflow-tooltip
                    />
                </DefineColumns>
                <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">
                        <ReuseColumns :cols="colList" />
                    </template>
                </template>
            </el-table>
            <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"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>
 
<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core';
import type { TableInstance } from 'element-plus';
import _ from 'lodash';
import { CSSProperties, onMounted, reactive, ref, type PropType, nextTick } from 'vue';
import { BORDER_COLOR, COL_HEADER_CELL_BG_COLOR, THICK_BORDER_WIDTH } from '../deviceLastValue/constants';
import { debounce, getTextWidth } from '/@/utils/util';
const props = defineProps({
    data: {
        type: Object as PropType<any>,
    },
});
 
const [DefineColumns, ReuseColumns] = createReusableTemplate<{
    cols: any[];
}>();
// props.data.title = '哈哈哈哈哈';
 
const colList = ref([]);
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 chunkTableData = ref([props.data?.values]);
 
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (groupColIndex.includes(columnIndex)) {
        return {
            rowspan: row.rowspan,
            colspan: 1,
        };
    }
};
 
/**
 * 构建分组结构
 */
const buildGroupData = () => {
    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;
    });
 
    // 重新排布一下位置,保证 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;
    }, []);
};
 
/**
 * 计算每一列的宽度
 * 1)总宽小于容器宽:直接按比例分
 * 2)总宽大于容器宽:先完全满足最小的宽度,直到到不满足宽度的地方,然后剩余宽度,按宽度比例分配
 * 3)计算完的宽度放在 colList.value 的 width 属性上
 * @param width
 */
const calcColWidth = (width) => {
    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);
            // 当加上 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 = props.data.cols.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) {
        buildGroupData();
        calcColWidth(width);
        nextTick(() => {
            calcPagerHeight();
        });
    } else {
        colList.value = [];
    }
 
    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').clientHeight;
    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);
};
 
const handleCurrentChange = (...a) => {};
//#endregion
 
const tableHeight = ref(0.7 * document.body.clientHeight);
onMounted(() => {
    resizeEvent({
        width: containerRef.value.clientWidth,
        height: 0.7 * document.body.clientHeight,
    });
});
</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>