Files
shanxia2.0/web-admin/src/utils/bx/table-summary.ts
T
2026-07-05 10:07:24 +08:00

73 lines
2.1 KiB
TypeScript

import { formatSumMoney } from './format'
export interface SummaryColumn {
property?: string
type?: string
}
export interface PageSummaryParams {
columns: SummaryColumn[]
data: Record<string, unknown>[]
}
export interface BuildPageSummaryOptions {
/** 放置合计标签的列 prop,默认 applyCode;默认不展示标签文案 */
labelProp?: string
/** 自定义标签文案;默认返回空字符串 */
labelFormatter?: (count: number) => string
/** 列 prop -> 合计值(已格式化字符串) */
sumByProp?: Record<string, (data: Record<string, unknown>[]) => string>
}
/** 对数值字段求和并格式化为合计金额 */
export function sumField(
data: Record<string, unknown>[],
field: string,
optional = false
): string {
const total = data.reduce((sum, row) => {
const value = row[field]
if (optional && (value == null || value === '')) return sum
return sum + Number(value || 0)
}, 0)
return formatSumMoney(total)
}
/** 按业务类型(备用金 / 报销单)分列求和,用于合并列表合计行 */
export function sumFieldByBizType(
data: Record<string, unknown>[],
field: string,
bizTypeField = 'bizType'
): string {
let advanceTotal = 0
let reimburseTotal = 0
for (const row of data) {
const amount = Number(row[field] || 0)
const bizType = row[bizTypeField]
if (bizType === '备用金') advanceTotal += amount
else if (bizType === '报销单') reimburseTotal += amount
}
return `备用金总额 ${formatSumMoney(advanceTotal)} / 报销单总额 ${formatSumMoney(reimburseTotal)}`
}
/**
* 生成 Element Plus 表格合计行方法;按当前可见 columns 动态对齐,兼容列显隐。
*/
export function buildPageSummaryMethod(options: BuildPageSummaryOptions = {}) {
const {
labelProp = 'applyCode',
labelFormatter = () => '',
sumByProp = {}
} = options
return ({ columns, data }: PageSummaryParams) => {
const label = labelFormatter(data.length)
return columns.map((col) => {
const prop = col.property
if (prop === labelProp) return label
if (prop && sumByProp[prop]) return sumByProp[prop](data)
return ''
})
}
}