/**
|
* 通用的表格合计方法
|
* @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 };
|