chenrui
2025-05-20 1ed11ff9b539891e92f73940772b680497bda98f
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
/**
 * 通用的表格合计方法
 * @param {Object} param - 包含表格列配置和数据源的对象
 * @param {Array<string>} summaryProps - 需要汇总的字段名数组
 * @param {Object} specialFormat - 特殊格式化规则:字段名 -> 格式化选项(如是否去掉小数)
 * @returns {Array} 合计行数据
 */
const summarizeTable = (param, summaryProps, specialFormat = {}) => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计';
            return;
        }
        const prop = column.property;
        if (summaryProps.includes(prop)) {
            const values = data.map(item => Number(item[prop]));
            // 只对有效数字进行求和
            if (!values.every(isNaN)) {
                const sum = values.reduce((acc, val) => (!isNaN(val) ? acc + val : acc), 0);
                if (specialFormat[prop] && specialFormat[prop].noDecimal) {
                    // 如果指定了不需要保留小数,则直接转换为整数
                    sums[index] = Math.round(sum).toString();
                } else {
                    // 默认保留两位小数
                    sums[index] = parseFloat(sum).toFixed(specialFormat[prop]?.decimalPlaces ?? 2);
                }
            } else {
                sums[index] = '';
            }
        } else {
            sums[index] = '';
        }
    });
    return sums;
};
// 导出函数供其他文件使用
export { summarizeTable };