import { isValidElement, type Key } from 'react'; import { getStoredWorkspaceThemeId, getWorkspaceTheme, type WorkspaceThemeId } from './ui-themes.ts'; type ExportColumn = { exportRate?: boolean; key?: Key; title?: unknown; width?: string | number; children?: readonly ExportColumn[] }; type ExportValue = string | number | null; function nodeText(node: unknown): string { if (typeof node === 'string' || typeof node === 'number') return String(node); if (Array.isArray(node)) return node.map(nodeText).join(''); if (isValidElement<{ children?: unknown }>(node)) return `${node.type === 'small' ? '\n' : ''}${nodeText(node.props.children)}`; return ''; } // Use the table's actual column tree, so key/full mode and dynamic defect fields stay aligned. export function workbookColumns(columns: readonly ExportColumn[], parents: string[] = []): { key: string; header: string; rate: boolean }[] { return columns.flatMap(column => { const path = [...parents, nodeText(column.title).trim()].filter(Boolean); if (column.children) return workbookColumns(column.children, path); const key = String(column.key ?? ''); if (!key || key === 'actions') return []; const rate = column.exportRate === true || key === 'compositeRate' || /^(black|bright)-rate$/.test(key); return [{ key, header: `${path.join(' / ')}${key === 'object' || rate ? '' : ' / kg'}`, rate }]; }); } function dataColumns(columns: readonly ExportColumn[]): ExportColumn[] { return columns.flatMap(column => { if (column.children) { const children = dataColumns(column.children); return children.length ? [{ ...column, children }] : []; } return String(column.key ?? '') && column.key !== 'actions' ? [column] : []; }); } function mix(foreground: string, background: string, proportion: number): string { return 'FF' + [1, 3, 5].map(offset => Math.round( parseInt(foreground.slice(offset, offset + 2), 16) * proportion + parseInt(background.slice(offset, offset + 2), 16) * (1 - proportion), ).toString(16).padStart(2, '0')).join('').toUpperCase(); } // Mirrors the query table's theme tokens and semantic colors. Dark always exports as light. export function metricWorkbookPalette(themeId: WorkspaceThemeId = 'light') { const theme = getWorkspaceTheme(themeId === 'dark' ? 'light' : themeId); return { ink: mix(theme.ink, theme.surface, 1), surface: mix(theme.surface, theme.surface, 1), grid: mix(theme.metricGrid, theme.surface, 1), headGrid: mix(theme.metricGridHead, theme.surface, 1), head: mix(theme.surface, theme.background, .55), alternate: mix(theme.surface, theme.soft, .97), black: 'FF20252B', bright: mix(theme.primary, theme.surface, 1), combined: mix(theme.teal, theme.surface, 1), blackHead: mix('#20252B', theme.surface, .07), brightHead: mix(theme.primary, theme.surface, .10), combinedFill: mix(theme.teal, theme.surface, .05), }; } export async function createMetricWorkbook(columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue, themeId: WorkspaceThemeId = getStoredWorkspaceThemeId()) { const { default: ExcelJS } = await import('exceljs'); const workbook = new ExcelJS.Workbook(); workbook.creator = '质量数据分析平台'; const tree = dataColumns(columns); const fields = workbookColumns(tree); const depth = (items: readonly ExportColumn[]): number => Math.max(1, ...items.map(column => column.children ? 1 + depth(column.children) : 1)); const headerRows = depth(tree); const palette = metricWorkbookPalette(themeId); const sheet = workbook.addWorksheet('质量汇总', { views: [{ state: 'frozen', xSplit: fields.length ? 1 : 0, ySplit: headerRows, showGridLines: false }], properties: { defaultRowHeight: 26.25 }, pageSetup: { orientation: 'landscape', paperSize: 9, fitToPage: true, fitToWidth: 1, fitToHeight: 0 }, }); if (!fields.length) return workbook; const border = (argb: string) => ({ top: { style: 'thin' as const, color: { argb } }, bottom: { style: 'thin' as const, color: { argb } }, left: { style: 'thin' as const, color: { argb } }, right: { style: 'thin' as const, color: { argb } }, }); const solid = (argb: string) => ({ type: 'pattern' as const, pattern: 'solid' as const, fgColor: { argb } }); let leafIndex = 0; const writeHeaders = (items: readonly ExportColumn[], level: number) => { for (const column of items) { const start = leafIndex + 1; const key = String(column.key ?? ''); const isGroup = !!column.children; if (column.children) writeHeaders(column.children, level + 1); else { leafIndex++; const pixels = Number(column.width) || (key === 'object' ? 220 : 112); sheet.getColumn(start).width = Math.max(14, Math.min(60, (pixels - 5) / 7)); sheet.getColumn(start).key = key; sheet.getColumn(start).numFmt = key === 'object' ? '@' : fields[start - 1].rate ? '0.00%' : '#,##0.0'; } const lastRow = isGroup ? level : headerRows; const end = leafIndex; const black = key === 'stage-black' || key === 'black-rate'; const bright = key === 'stage-bright' || key === 'bright-rate'; const combined = key === 'compositeRate'; const fill = combined ? palette.combinedFill : isGroup && black ? palette.blackHead : isGroup && bright ? palette.brightHead : palette.head; const color = combined ? palette.combined : black ? palette.black : bright ? palette.bright : palette.ink; for (let r = level; r <= lastRow; r++) for (let c = start; c <= end; c++) { const cell = sheet.getCell(r, c); cell.fill = solid(fill); cell.border = border(palette.headGrid); cell.font = { name: '微软雅黑', size: 10.5, bold: true, color: { argb: color } }; cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true }; } if (lastRow > level || end > start) sheet.mergeCells(level, start, lastRow, end); const label = nodeText(column.title).trim(); sheet.getCell(level, start).value = !isGroup && key !== 'object' && !fields[start - 1].rate ? `${label}\n(kg)` : label; } }; writeHeaders(tree, 1); for (let i = 1; i <= headerRows; i++) { let lines = 1; sheet.getRow(i).eachCell(cell => { if (typeof cell.value === 'string') lines = Math.max(lines, cell.value.split('\n').length); }); sheet.getRow(i).height = Math.max(27, lines * 16 + 6); } rows.forEach((row, index) => { const exported = sheet.getRow(headerRows + index + 1); let lines = 1; fields.forEach((field, column) => { const result = value(field.key, row); const cell = exported.getCell(column + 1); cell.value = typeof result === 'number' && !Number.isFinite(result) ? null : result; const combined = field.key === 'compositeRate'; const color = combined ? palette.combined : field.key === 'black-rate' ? palette.black : field.key === 'bright-rate' ? palette.bright : palette.ink; cell.font = { name: field.key === 'object' ? '微软雅黑' : 'Arial', size: combined ? 11.25 : field.key === 'object' ? 12 : 9.75, bold: field.key === 'object' || field.key.endsWith('-rate') || combined, color: { argb: color } }; cell.fill = solid(combined ? palette.combinedFill : index % 2 ? palette.alternate : palette.surface); cell.border = border(palette.grid); cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true }; if (typeof result === 'string') { const width = sheet.getColumn(column + 1).width! - 2; const textLines = result.split(/\r?\n/).reduce((total, line) => total + Math.max(1, Math.ceil(Array.from(line).reduce((length, char) => length + (/[^\x00-\xff]/.test(char) ? 2 : 1), 0) / width)), 0); lines = Math.max(lines, textLines); } }); exported.height = Math.max(26.25, lines * 16 + 8); }); sheet.autoFilter = { from: { row: headerRows, column: 1 }, to: { row: headerRows + rows.length, column: fields.length } }; sheet.pageSetup.printTitlesRow = `1:${headerRows}`; sheet.pageSetup.printArea = `A1:${sheet.getColumn(fields.length).letter}${headerRows + rows.length}`; return workbook; } export async function downloadMetricWorkbook(filename: string, columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue) { const workbook = await createMetricWorkbook(columns, rows, value); const buffer = await workbook.xlsx.writeBuffer(); const url = URL.createObjectURL(new Blob([new Uint8Array(buffer)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })); const link = document.createElement('a'); link.href = url; link.download = `${filename.replace(/[\\/:*?"<>|]/g, '_')}.xlsx`; document.body.appendChild(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 30_000); }