import type { EChartsCoreOption } from 'echarts/core'; import { analysisPeriodLabel, isValidAnalysisPeriodContext, parseAnalysisPeriod } from './analysisPeriodModel.ts'; export type AnalysisVisualUnit = 'ratio' | 'kg' | 'pp' | 'count'; export type AnalysisVisualStage = 'black' | 'bright'; export type AnalysisVisualSectionKey = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category_black' | 'category_bright' | 'defect_black' | 'defect_bright' | 'defect_combined' | 'trend' | 'composition'; export type AnalysisVisualDimension = 'department' | 'group' | 'product' | 'category' | 'defect'; export type AnalysisExclusionDimension = 'department' | 'group' | 'product' | 'projectGroup'; export type AnalysisExclusions = Partial>; export interface SourceColumnFilter { field: string; stages: Array<'black' | 'bright'>; operator: 'in' | 'not_in' | 'is_empty' | 'not_empty'; values?: string[] } export type AnalysisVisualContextValue = string | number | boolean | Array | Record | Record | SourceColumnFilter[] | AnalysisExclusions; export type AnalysisVisualContext = Record; export interface AnalysisVisualSeries { key: string; label: string; values: Array; } export interface AnalysisVisual { id: string; type: string; title: string; subtitle: string; unit: AnalysisVisualUnit; categories: Array<{ key: string; label: string }>; series: AnalysisVisualSeries[]; evidenceRefs: string[]; requiredFields: string[]; scope: AnalysisVisualContext; period: AnalysisVisualContext; comparisonPeriod?: AnalysisVisualContext; stage?: AnalysisVisualStage; metric: string; coverage: { totalRows: number; returnedRows: number; truncated: boolean; shareBasis?: string; denominator?: number; }; note?: string; originTurnId: string; invalidValueCells: string[]; chartable: boolean; chartIssue?: string; sectionKey?: AnalysisVisualSectionKey; dimension?: AnalysisVisualDimension; } export interface ParseVisualsResult { visuals: AnalysisVisual[]; issues: string[]; } export interface VisualChartTheme { ink?: string; mutedInk?: string; line?: string; surface?: string; colors?: string[]; } export const MAX_ANALYSIS_VISUALS = 12; export const MAX_VISUAL_BYTES = 256 * 1024; export const MAX_VISUAL_CATEGORIES = 36; export const MAX_VISUAL_SERIES = 4; const UNIT_VALUES = new Set(['ratio', 'kg', 'pp', 'count']); const CHART_TYPES = new Set(['bar', 'line', 'column', 'area', 'heatmap', 'donut', 'pareto', 'waterfall']); const SECTION_KEYS = new Set(['overview', 'stage', 'department', 'group', 'product', 'category_black', 'category_bright', 'defect_black', 'defect_bright', 'defect_combined', 'trend', 'composition']); const DIMENSIONS = new Set(['department', 'group', 'product', 'category', 'defect']); const VISUAL_KEYS = new Set(['id', 'type', 'title', 'subtitle', 'unit', 'categories', 'series', 'evidenceRefs', 'requiredFields', 'scope', 'period', 'comparisonPeriod', 'stage', 'metric', 'coverage', 'note', 'originTurnId', 'sectionKey', 'dimension']); const CATEGORY_KEYS = new Set(['key', 'label']); const SERIES_KEYS = new Set(['key', 'label', 'values']); const COVERAGE_KEYS = new Set(['totalRows', 'returnedRows', 'truncated', 'shareBasis', 'denominator']); const PARSED_VISUALS = new WeakSet(); const DONUT_CATEGORY_KEYS: Record> = { black: new Set(['black_responsibility_scrap', 'black_material_scrap', 'black_external_scrap']), bright: new Set(['bright_plating_scrap', 'bright_material_scrap', 'bright_processing_scrap', 'bright_diffusion_scrap']), }; const SCRAP_RATE_REQUIRED_FIELDS: Record = { black_scrap_rate: { stage: 'black', fields: ['black_scrap_weight', 'black_total_weight'] }, bright_scrap_rate: { stage: 'bright', fields: ['bright_scrap_weight', 'bright_total_weight'] }, }; const OFFICIAL_RATES_ALLOWING_OVER_ONE = new Set([ 'black_rate', 'composite_rate', 'composite_rate_without_headquarters_scrap', ]); const DEFAULT_COLORS = ['#607ae1', '#008f7d', '#d58c35', '#8b68c5']; function isScrapRateMetric(metric: string): boolean { return Object.hasOwn(SCRAP_RATE_REQUIRED_FIELDS, metric); } function allowsAboveOneRatio(metric: string): boolean { return isScrapRateMetric(metric) || OFFICIAL_RATES_ALLOWING_OVER_ONE.has(metric); } function ratioAxisMax(visual: AnalysisVisual): number | undefined { if (visual.unit !== 'ratio') return undefined; if (!allowsAboveOneRatio(visual.metric)) return 100; const highest = Math.max(0, ...visual.series.flatMap(series => series.values.filter((value): value is number => value !== null && Number.isFinite(value)))); if (isScrapRateMetric(visual.metric) && highest <= 1) { if (highest === 0) return 1; const targetPercent = highest * 100 * 1.15; const magnitude = 10 ** Math.floor(Math.log10(targetPercent)); const factor = [1, 2, 5, 10].find(value => value * magnitude >= targetPercent) || 10; return Math.min(100, factor * magnitude); } if (highest <= 1) return 100; const highestPercent = highest * 100; if (!Number.isFinite(highestPercent)) return undefined; return Math.ceil((highestPercent + Math.max(10, highestPercent * 0.08)) / 10) * 10; } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } function hasOnlyKeys(value: Record, allowed: Set): boolean { return Object.keys(value).every(key => allowed.has(key)); } /** 解析前仅复制普通 JSON 数据,阻止 getter、toJSON、原型和函数进入渲染链路。 */ function copyJsonData(value: unknown, seen = new Set(), budget = { nodes: 0 }, depth = 0): unknown { if (depth > 32 || ++budget.nodes > 100_000) throw new Error('unsafe JSON data'); if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' || value === undefined) return value; if (typeof value !== 'object' || seen.has(value)) throw new Error('unsafe JSON data'); if (PARSED_VISUALS.has(value)) { seen.add(value); try { const descriptors = Object.getOwnPropertyDescriptors(value); const result: Record = Object.create(null); for (const key of VISUAL_KEYS) { const descriptor = descriptors[key]; if (!descriptor) continue; if (!('value' in descriptor)) throw new Error('unsafe JSON data'); result[key] = copyJsonData(descriptor.value, seen, budget, depth + 1); } return result; } finally { seen.delete(value); } } seen.add(value); try { if (Array.isArray(value)) { if (Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length) throw new Error('unsafe JSON data'); const descriptors = Object.getOwnPropertyDescriptors(value); const result: unknown[] = []; for (let index = 0; index < value.length; index++) { const descriptor = descriptors[String(index)]; if (!descriptor || !('value' in descriptor)) throw new Error('unsafe JSON data'); result.push(copyJsonData(descriptor.value, seen, budget, depth + 1)); } if (Object.keys(descriptors).some(key => key !== 'length' && (!/^\d+$/.test(key) || String(Number(key)) !== key || Number(key) >= value.length))) { throw new Error('unsafe JSON data'); } return result; } const prototype = Object.getPrototypeOf(value); if (prototype !== Object.prototype && prototype !== null) throw new Error('unsafe JSON data'); if (Object.getOwnPropertySymbols(value).length) throw new Error('unsafe JSON data'); const result: Record = Object.create(null); for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) { if (!('value' in descriptor)) throw new Error('unsafe JSON data'); result[key] = copyJsonData(descriptor.value, seen, budget, depth + 1); } return result; } finally { seen.delete(value); } } function boundedText(value: unknown, maxLength = 200): string | null { if (typeof value !== 'string') return null; const text = value.trim().replace(/数学/g, ''); if (!text || text.length > maxLength) return null; return text; } function safeTextList(value: unknown, maxItems = 40): string[] | null { if (!Array.isArray(value) || value.length > maxItems) return null; const list: string[] = []; for (const item of value) { const text = boundedText(item, 160); if (!text) return null; list.push(text); } return list; } function safeExclusions(value: unknown): AnalysisExclusions | null { if (!isRecord(value) || Object.keys(value).length > 4) return null; const result: AnalysisExclusions = {}; for (const [dimension, rawValues] of Object.entries(value)) { if (!['department', 'group', 'product', 'projectGroup'].includes(dimension) || !Array.isArray(rawValues) || rawValues.length < 1 || rawValues.length > 50 || rawValues.some(item => typeof item !== 'string' || !item.trim() || item.length > 256)) return null; Object.defineProperty(result, dimension, { value: [...rawValues], enumerable: true, configurable: true, writable: true }); } return result; } export function isValidAnalysisExclusions(value: unknown): boolean { return safeExclusions(value) !== null; } function safeContext(value: unknown): AnalysisVisualContext | null { if (!isRecord(value) || Object.keys(value).length > 32) return null; const result: AnalysisVisualContext = {}; for (const [key, raw] of Object.entries(value)) { if (!/^[\w.-]{1,64}$/.test(key)) return null; if (key === 'exclusions') { const exclusions = safeExclusions(raw); if (!exclusions) return null; Object.defineProperty(result, key, { value: exclusions, enumerable: true, configurable: true, writable: true }); } else if (key === 'columnFilters') { if (!Array.isArray(raw) || raw.length > 20) return null; const filters: SourceColumnFilter[] = []; for (const rule of raw) { if (!isRecord(rule) || Object.keys(rule).some(key => !['field', 'stages', 'operator', 'values'].includes(key)) || typeof rule.field !== 'string' || !/^[A-Za-z0-9_]{1,64}$/.test(rule.field) || !Array.isArray(rule.stages) || !rule.stages.length || rule.stages.length > 2 || new Set(rule.stages).size !== rule.stages.length || rule.stages.some(stage => stage !== 'black' && stage !== 'bright') || !['in', 'not_in', 'is_empty', 'not_empty'].includes(String(rule.operator))) return null; const needsValues = rule.operator === 'in' || rule.operator === 'not_in'; if (needsValues && (!Array.isArray(rule.values) || !rule.values.length || rule.values.length > 50 || rule.values.some(value => typeof value !== 'string' || !value.trim() || value.length > 256))) return null; if (!needsValues && rule.values !== undefined) return null; filters.push({ field: rule.field, stages: [...rule.stages] as SourceColumnFilter['stages'], operator: rule.operator as SourceColumnFilter['operator'], ...(needsValues ? { values: [...rule.values as string[]] } : {}) }); } result[key] = filters; } else if (key === 'columnLabels') { if (!isRecord(raw) || Object.keys(raw).length > 25 || Object.entries(raw).some(([name, label]) => !/^[A-Za-z0-9_]{1,64}$/.test(name) || typeof label !== 'string' || label.length > 160)) return null; result[key] = Object.fromEntries(Object.entries(raw)) as Record; } else if (key === 'extraFilters') { if (!isRecord(raw) || Object.keys(raw).length > 20) return null; const filters: Record = {}; for (const [filterKey, filterValues] of Object.entries(raw)) { if (!/^[\w.-]{1,128}$/.test(filterKey) || !Array.isArray(filterValues) || filterValues.length > 20 || !filterValues.every(item => typeof item === 'string' && item.length <= 160)) return null; Object.defineProperty(filters, filterKey, { value: [...filterValues], enumerable: true, configurable: true, writable: true }); } Object.defineProperty(result, key, { value: filters, enumerable: true, configurable: true, writable: true }); } else if (typeof raw === 'string') { if (raw.length > 160) return null; Object.defineProperty(result, key, { value: raw, enumerable: true, configurable: true, writable: true }); } else if (typeof raw === 'boolean' || (typeof raw === 'number' && Number.isFinite(raw))) { Object.defineProperty(result, key, { value: raw, enumerable: true, configurable: true, writable: true }); } else if (Array.isArray(raw) && raw.length <= 20 && raw.every(item => typeof item === 'boolean' || (typeof item === 'string' && item.length <= 160) || (typeof item === 'number' && Number.isFinite(item)))) { Object.defineProperty(result, key, { value: raw as Array, enumerable: true, configurable: true, writable: true }); } else return null; } return result; } function parseVisual(value: unknown, index: number, issues: string[]): AnalysisVisual | null { if (!isRecord(value) || !hasOnlyKeys(value, VISUAL_KEYS)) { issues.push(`第 ${index + 1} 张图表结构无效`); return null; } const id = boundedText(value.id, 128); const type = boundedText(value.type, 32); const title = boundedText(value.title); const subtitle = typeof value.subtitle === 'string' && value.subtitle.length <= 200 ? value.subtitle.trim() : null; const unit = value.unit; const metric = boundedText(value.metric, 128); const originTurnId = boundedText(value.originTurnId, 128); const scope = safeContext(value.scope); const period = safeContext(value.period); const comparisonPeriod = value.comparisonPeriod === undefined ? undefined : safeContext(value.comparisonPeriod); const evidenceRefs = safeTextList(value.evidenceRefs, 100); const requiredFields = safeTextList(value.requiredFields, 100); const note = value.note === undefined ? undefined : boundedText(value.note, 500); const stage = value.stage === undefined ? undefined : value.stage; const sectionKey = value.sectionKey === undefined ? undefined : value.sectionKey; const dimension = value.dimension === undefined ? undefined : value.dimension; const coverage = isRecord(value.coverage) && hasOnlyKeys(value.coverage, COVERAGE_KEYS) ? value.coverage : null; const validCoverage = coverage && Number.isSafeInteger(coverage.totalRows) && Number(coverage.totalRows) >= 0 && Number.isSafeInteger(coverage.returnedRows) && Number(coverage.returnedRows) >= 0 && Number(coverage.returnedRows) <= Number(coverage.totalRows) && typeof coverage.truncated === 'boolean' && (coverage.shareBasis === undefined || boundedText(coverage.shareBasis, 128) !== null) && (coverage.denominator === undefined || typeof coverage.denominator === 'number' && Number.isFinite(coverage.denominator) && coverage.denominator > 0 && coverage.shareBasis === 'all_scope_weight') ? { totalRows: Number(coverage.totalRows), returnedRows: Number(coverage.returnedRows), truncated: coverage.truncated, ...(coverage.shareBasis === undefined ? {} : { shareBasis: String(coverage.shareBasis) }), ...(coverage.denominator === undefined ? {} : { denominator: Number(coverage.denominator) }), } : null; const categories = Array.isArray(value.categories) && value.categories.length > 0 && value.categories.length <= MAX_VISUAL_CATEGORIES ? value.categories.map(category => { if (!isRecord(category) || !hasOnlyKeys(category, CATEGORY_KEYS)) return null; const key = boundedText(category.key, 128); const label = boundedText(category.label, 240); return key && label ? { key, label } : null; }) : null; const categoryKeys = categories?.map(category => category?.key) ?? []; const validCategories = categories && categories.every((category): category is { key: string; label: string } => category !== null) && new Set(categoryKeys).size === categoryKeys.length ? categories as Array<{ key: string; label: string }> : null; const rawSeries = Array.isArray(value.series) && value.series.length > 0 && value.series.length <= MAX_VISUAL_SERIES ? value.series : null; const invalidValueCells: string[] = []; const series: AnalysisVisualSeries[] = []; if (rawSeries && validCategories) { for (const [seriesIndex, raw] of rawSeries.entries()) { if (!isRecord(raw) || !hasOnlyKeys(raw, SERIES_KEYS)) { series.length = 0; break; } const key = boundedText(raw.key, 128); const label = boundedText(raw.label, 160); if (!key || !label || !Array.isArray(raw.values) || raw.values.length !== validCategories.length) { series.length = 0; break; } const seen = new Set(series.map(item => item.key)); if (seen.has(key)) { series.length = 0; break; } const values = raw.values.map((item, valueIndex) => { if (item === null) return null; if (typeof item !== 'number' || !Number.isFinite(item)) { invalidValueCells.push(`${seriesIndex}:${valueIndex}`); return null; } if (unit === 'ratio' && (item < 0 || (!allowsAboveOneRatio(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`); return item; }); series.push({ key, label, values }); } } const validSeries = !!rawSeries && !!validCategories && series.length === rawSeries.length; const valid = !!id && !!type && !!title && subtitle !== null && UNIT_VALUES.has(unit as AnalysisVisualUnit) && !!metric && !!originTurnId && !!scope && isValidAnalysisPeriodContext(scope) && !!period && isValidAnalysisPeriodContext(period) && (value.comparisonPeriod === undefined || !!comparisonPeriod && isValidAnalysisPeriodContext(comparisonPeriod)) && !!evidenceRefs && !!requiredFields && (value.note === undefined || note !== null) && (stage === undefined || stage === 'black' || stage === 'bright') && (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey)) && (dimension === undefined || DIMENSIONS.has(dimension as AnalysisVisualDimension)) && !!validCoverage && !!validCategories && validSeries; if (!valid) { issues.push(`第 ${index + 1} 张图表未通过结构校验`); return null; } const unitValue = unit as AnalysisVisualUnit; const hasData = series.some(item => item.values.some(point => point !== null && Number.isFinite(point))); const candidate: AnalysisVisual = { id: id!, type: type!, title: title!, subtitle: subtitle!, unit: unitValue, categories: validCategories!, series, evidenceRefs: evidenceRefs!, requiredFields: requiredFields!, scope: scope!, period: period!, ...(comparisonPeriod ? { comparisonPeriod } : {}), ...(stage ? { stage } : {}), metric: metric!, coverage: validCoverage!, ...(note ? { note } : {}), originTurnId: originTurnId!, invalidValueCells, chartable: false, ...(sectionKey ? { sectionKey: sectionKey as AnalysisVisualSectionKey } : {}), ...(dimension ? { dimension: dimension as AnalysisVisualDimension } : {}), }; const semanticIssue = visualSemanticIssue(candidate); const chartable = CHART_TYPES.has(type!) && hasData && invalidValueCells.length === 0 && !semanticIssue; let chartIssue: string | undefined; if (!CHART_TYPES.has(type!)) chartIssue = '暂不支持此图形,以下展示原始数据表'; else if (invalidValueCells.length) chartIssue = unitValue === 'ratio' ? '比例值无效或超出 0–1 范围,以下展示原始数据表' : '存在无效数值,以下展示原始数据表'; else if (!hasData) chartIssue = '没有可绘制的数值,以下展示数据表'; else if (semanticIssue) chartIssue = `${semanticIssue},以下展示原始数据表`; if (!chartable) issues.push(`“${title}”已降级为数据表:${chartIssue}`); const parsedVisual: AnalysisVisual = { ...candidate, chartable, ...(chartIssue ? { chartIssue } : {}), }; PARSED_VISUALS.add(parsedVisual); return parsedVisual; } function visualSemanticIssue(visual: AnalysisVisual): string | undefined { const scrapRate = SCRAP_RATE_REQUIRED_FIELDS[visual.metric]; if (scrapRate) { if (visual.unit !== 'ratio') return '阶段报废率必须使用比例单位'; if (visual.requiredFields.length !== scrapRate.fields.length || new Set(visual.requiredFields).size !== scrapRate.fields.length || scrapRate.fields.some(field => !visual.requiredFields.includes(field))) return '阶段报废率缺少对应重量字段权限'; if ((visual.stage !== undefined && visual.stage !== scrapRate.stage) || (visual.scope.stage !== undefined && visual.scope.stage !== scrapRate.stage)) return '报废率阶段与查询范围不一致'; } if (visual.type === 'area' && visual.series.length !== 1) return '面积趋势图仅支持单一序列'; if (visual.type === 'area' && visual.series.some(series => series.values.some(value => value !== null && value < 0))) return '面积趋势图不支持负值'; if (visual.type === 'waterfall') { const allowedFields = new Set(['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight']); const actualFields = visual.requiredFields; if (visual.metric !== 'composite_impact_pp' || visual.unit !== 'pp') return '瀑布图仅支持综合率阶段影响(百分点)'; if (visual.categories.length !== 3 || visual.categories.map(item => item.key).join('|') !== 'black|bright|total') return '瀑布图类别必须依次为黑片、亮片和综合变化'; if (visual.series.length !== 1 || visual.series[0].key !== 'composite_impact_pp') return '瀑布图仅支持综合阶段影响序列'; if (actualFields.length !== allowedFields.size || new Set(actualFields).size !== allowedFields.size || actualFields.some(field => !allowedFields.has(field))) { return '瀑布图必须具备黑片和亮片的合格重量、总重量字段权限'; } if (visual.stage !== undefined || visual.scope.stage !== undefined || visual.scope.category !== undefined || visual.scope.defect !== undefined) { return '瀑布图只支持未按阶段、类别或缺陷筛选的综合范围'; } if (!visual.comparisonPeriod || Object.keys(visual.period).length === 0 || Object.keys(visual.comparisonPeriod).length === 0 || plainPeriod(visual.period) === '当前期间' || plainPeriod(visual.comparisonPeriod) === '当前期间' || plainPeriod(visual.period) === plainPeriod(visual.comparisonPeriod)) return '瀑布图必须提供两个不同的有效期间'; const values = visual.series[0].values; if (values.length !== 3 || values.some(value => value === null || !Number.isFinite(value))) return '瀑布图的三项影响必须是有限数值'; const sum = (values[0] as number) + (values[1] as number); if (!Number.isFinite(sum) || Math.abs(sum - (values[2] as number)) > 1e-8) return '黑片与亮片影响之和必须等于综合率变化'; return undefined; } if (visual.type !== 'donut' && visual.type !== 'pareto') return undefined; const chartName = visual.type === 'donut' ? '环形图' : '柏拉图'; if (visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight') { const values = visual.series[0]?.values || []; const total = visual.coverage.denominator; const combined = visual.metric === 'current_scrap_weight' && !visual.stage && ['black_scrap_weight', 'bright_scrap_weight'].every(field => visual.requiredFields.includes(field)); if (visual.unit !== 'kg' || !combined && !/^(?:black|bright)_(?:total|scrap)_weight$/.test(visual.metric) || !combined && (!visual.stage || !visual.metric.startsWith(`${visual.stage}_`)) || visual.comparisonPeriod || !['product','department','group'].includes(visual.dimension || '') || visual.categories.length < 1 || visual.categories.length > 10 || visual.series.length !== 1 || visual.coverage.returnedRows !== visual.categories.length || typeof total !== 'number' || !(total > 0) || values.some((v,i) => v === null || !Number.isFinite(v) || v < 0 || i > 0 && v > (values[i-1] as number))) return '分组重量柏拉图缺少全范围总量或有效排名'; if (values.reduce((sum,v)=>sum+(v as number),0) > total + Math.max(0.00001,total*1e-10)) return 'Top重量不能大于全范围总量'; return undefined; } if (visual.unit !== 'kg' || visual.metric !== 'source_defect_weight') return `${chartName}仅支持来源类别重量`; if (visual.stage !== 'black' && visual.stage !== 'bright') return `${chartName}必须明确黑片或亮片阶段`; if (visual.scope.stage !== undefined && visual.scope.stage !== visual.stage) return `${chartName}阶段与查询范围不一致`; if (visual.scope.category !== undefined || visual.scope.defect !== undefined) return `${chartName}不支持来源类别或具体缺陷筛选`; if (visual.coverage.shareBasis !== 'displayed_categories' || visual.coverage.truncated || visual.coverage.totalRows !== visual.categories.length || visual.coverage.returnedRows !== visual.categories.length) { return `${chartName}需要完整列出互斥类别,且占比口径为本图所列类别`; } const expected = DONUT_CATEGORY_KEYS[visual.stage]; if (visual.categories.some(category => !expected.has(category.key))) { return `${chartName}类别不符合该阶段的正式类别集合`; } if (visual.series.length !== 1 || visual.categories.length < 2) return `${chartName}需要一个序列和至少两个类别`; const values = visual.series[0].values; if (values.length !== visual.categories.length || values.some(value => value === null || !Number.isFinite(value) || value < 0)) { return `${chartName}数值必须是完整的有限非负重量`; } const total = values.reduce((sum, value) => sum + (value as number), 0); if (!Number.isFinite(total) || !(total > 0)) return `${chartName}所列类别重量合计必须是有限正数`; if (visual.type === 'pareto' && values.some((value, index) => index > 0 && (value as number) > (values[index - 1] as number))) { return '柏拉图类别重量必须按降序排列'; } return undefined; } /** Parse untrusted JSON-shaped chart data. An object wrapper may also include visualSchemaVersion. */ export function parseAnalysisVisuals(input: unknown, schemaVersion?: unknown): ParseVisualsResult { const issues: string[] = []; let safeInput: unknown; try { safeInput = copyJsonData(input); } catch { return { visuals: [], issues: ['图表数据无法安全读取'] }; } let rawVisuals = safeInput; let version = schemaVersion; if (isRecord(safeInput) && 'visuals' in safeInput) { if (!hasOnlyKeys(safeInput, new Set(['visuals', 'visualSchemaVersion']))) { return { visuals: [], issues: ['图表数据包含未知字段'] }; } rawVisuals = safeInput.visuals; if (version === undefined) version = safeInput.visualSchemaVersion; } if (version !== undefined && version !== 1) { return { visuals: [], issues: ['不支持此版本的图表数据'] }; } if (rawVisuals === undefined || rawVisuals === null) return { visuals: [], issues }; if (!Array.isArray(rawVisuals)) return { visuals: [], issues: ['图表数据格式无效'] }; let serialized: string; try { serialized = JSON.stringify(rawVisuals); } catch { return { visuals: [], issues: ['图表数据无法安全读取'] }; } if (typeof serialized !== 'string' || new TextEncoder().encode(serialized).byteLength > MAX_VISUAL_BYTES) { return { visuals: [], issues: ['图表数据超过安全大小限制'] }; } const result: AnalysisVisual[] = []; const ids = new Set(); for (const [index, item] of rawVisuals.slice(0, MAX_ANALYSIS_VISUALS).entries()) { const visual = parseVisual(item, index, issues); if (!visual) continue; if (ids.has(visual.id)) { issues.push(`图表编号重复:${visual.id}`); continue; } ids.add(visual.id); result.push(visual); } if (rawVisuals.length > MAX_ANALYSIS_VISUALS) issues.push(`仅展示前 ${MAX_ANALYSIS_VISUALS} 张图表`); return { visuals: result, issues }; } /** Combine only comparable, already-validated stage defect views. Saved reports remain unchanged. */ export function combineStageDefectVisuals(visuals: AnalysisVisual[]): AnalysisVisual[] { const used = new Set(); const comparableScope = (visual: AnalysisVisual) => { const { stage: _stage, ...scope } = visual.scope; return JSON.stringify(Object.entries(scope).sort(([a], [b]) => a.localeCompare(b))); }; const canPair = (a: AnalysisVisual, b: AnalysisVisual) => a.type === 'bar' && b.type === 'bar' && a.unit === 'kg' && b.unit === 'kg' && a.metric === b.metric && ['source_defect_delta_weight', 'source_defect_weight'].includes(a.metric) && a.sectionKey === `defect_${a.stage}` && b.sectionKey === `defect_${b.stage}` && a.stage === 'black' && b.stage === 'bright' && a.chartable && b.chartable && a.originTurnId === b.originTurnId && comparableScope(a) === comparableScope(b) && JSON.stringify(a.period) === JSON.stringify(b.period) && JSON.stringify(a.comparisonPeriod) === JSON.stringify(b.comparisonPeriod); const selectedRows = (visual: AnalysisVisual) => visual.categories .map((category, index) => ({ category, value: visual.series[0]?.values[index] ?? null, index })) .filter(row => row.value !== null && Number.isFinite(row.value) && row.value !== 0) .sort((a, b) => Math.abs(b.value!) - Math.abs(a.value!) || a.index - b.index) .slice(0, 5); const result: AnalysisVisual[] = []; for (const visual of visuals) { if (used.has(visual.id)) continue; const black = visual.stage === 'black' ? visual : visuals.find(candidate => canPair(candidate, visual)); const bright = visual.stage === 'bright' ? visual : visuals.find(candidate => black !== undefined && canPair(black, candidate)); if (!black || !bright || !canPair(black, bright) || used.has(black.id) || used.has(bright.id)) { result.push(visual); continue; } const rows = [ ...selectedRows(black).map(row => ({ ...row, stage: 'black' as const })), ...selectedRows(bright).map(row => ({ ...row, stage: 'bright' as const })), ].sort((a, b) => Math.abs(b.value!) - Math.abs(a.value!) || (a.stage === 'black' ? -1 : 1)); if (!rows.some(row => row.stage === 'black') || !rows.some(row => row.stage === 'bright')) { result.push(visual); continue; } const { stage: _stage, ...scope } = black.scope; const delta = black.metric === 'source_defect_delta_weight'; const combined = parseAnalysisVisuals([{ id: `combined-${black.id}-${bright.id}`, type: 'bar', title: `黑片与亮片来源具体缺陷${delta ? '报废增减' : '报废重量'}`, subtitle: `按缺陷${delta ? '报废重量增减' : '报废重量'}比较,颜色区分阶段;各阶段最多展示${delta ? '变化较大' : '重量较高'}的 5 项。`, unit: 'kg', categories: rows.map(row => ({ key: `${row.stage}:${row.category.key}`, label: `${row.stage === 'black' ? '黑片' : '亮片'} · ${row.category.label}` })), series: [ { key: 'black', label: '黑片', values: rows.map(row => row.stage === 'black' ? row.value : null) }, { key: 'bright', label: '亮片', values: rows.map(row => row.stage === 'bright' ? row.value : null) }, ], evidenceRefs: [...new Set([...black.evidenceRefs, ...bright.evidenceRefs])], requiredFields: [...new Set([...black.requiredFields, ...bright.requiredFields])], scope, period: black.period, ...(black.comparisonPeriod ? { comparisonPeriod: black.comparisonPeriod } : {}), metric: black.metric, originTurnId: black.originTurnId, sectionKey: 'defect_combined', dimension: 'defect', coverage: { totalRows: black.coverage.totalRows + bright.coverage.totalRows, returnedRows: rows.length, truncated: black.coverage.truncated || bright.coverage.truncated || rows.length < black.coverage.totalRows + bright.coverage.totalRows }, note: `具体缺陷按来源字段统计,仅作核查线索;${delta ? '零变化' : '零重量'}项不占图表空间,完整数据保留在原始依据中。`, }], 1).visuals[0]; if (!combined) { result.push(visual); continue; } used.add(black.id); used.add(bright.id); result.push(combined); } return result; } export function formatVisualValue(value: number | null, unit: AnalysisVisualUnit): string { if (value === null) return '—'; if (!Number.isFinite(value)) return '无效值'; const numberText = new Intl.NumberFormat('en-US', { useGrouping: false, maximumSignificantDigits: 15 }).format(unit === 'ratio' ? value * 100 : value); if (unit === 'ratio') return `${numberText}%`; const signedNumber = `${value > 0 && unit === 'pp' ? '+' : ''}${numberText}`; if (unit === 'kg') return `${signedNumber} kg`; if (unit === 'pp') return `${signedNumber} pp`; return signedNumber; } function chartNumber(value: number): number { return Number(value.toPrecision(10)); } function formatChartValue(value: number | null, unit: AnalysisVisualUnit, showPositiveSign = true): string { if (value === null) return '—'; if (!Number.isFinite(value)) return '无效值'; const plotted = unit === 'ratio' ? value * 100 : value; const numberText = unit === 'kg' || unit === 'pp' || unit === 'ratio' ? new Intl.NumberFormat('zh-CN', { useGrouping: false, maximumFractionDigits: 2 }).format(plotted) : new Intl.NumberFormat('zh-CN', { useGrouping: false, maximumSignificantDigits: 10 }).format(plotted); if (unit === 'ratio') return `${numberText}%`; const signed = unit === 'pp' && showPositiveSign && value > 0 ? `+${numberText}` : numberText; return unit === 'kg' ? `${signed} kg` : unit === 'pp' ? `${signed} pp` : signed; } function paretoWeightLabel(value: number | null, allScopeWeight: boolean): string { const text = formatChartValue(value, 'kg'); return allScopeWeight ? text.replace(/ kg$/, '') : text; } export function visualCategoryLabel(visual: AnalysisVisual, categoryIndex: number): string { const category = visual.categories[categoryIndex]; if (!category) return ''; const duplicateLabel = visual.categories.some((item, index) => index !== categoryIndex && item.label === category.label); return duplicateLabel ? `${category.label} · ${category.key}` : category.label; } export interface AnalysisVisualDonutShare { categoryIndex: number; valueKg: number; share: number; } /** Shares are always relative to the sum of categories visible in this donut. */ export function visualDonutShares(visual: AnalysisVisual): AnalysisVisualDonutShare[] { if (visual.type !== 'donut' || visualSemanticIssue(visual)) return []; const values = visual.series[0]?.values; if (!values) return []; const total = values.reduce((sum, value) => sum + (value as number), 0); if (!(total > 0)) return []; return values.map((value, categoryIndex) => ({ categoryIndex, valueKg: value as number, share: (value as number) / total, })); } export interface AnalysisVisualParetoPoint extends AnalysisVisualDonutShare { cumulativeShare: number; } export function visualParetoPoints(visual: AnalysisVisual): AnalysisVisualParetoPoint[] { if (visual.type !== 'pareto' || visualSemanticIssue(visual)) return []; const values = visual.series[0]?.values; if (!values) return []; const fullPopulation = visual.coverage.shareBasis === 'all_scope_weight'; const total = fullPopulation ? visual.coverage.denominator! : values.reduce((sum, value) => sum + (value as number), 0); let cumulative = 0; return values.map((value, categoryIndex) => { cumulative += value as number; return { categoryIndex, valueKg: value as number, share: (value as number) / total, cumulativeShare: !fullPopulation && categoryIndex === values.length - 1 ? 1 : cumulative / total, }; }); } export function visualDonutShareText(share: number): string { return `${(share * 100).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}%`; } function plainRichText(value: string): string { return value.replace(/[{}]/g, character => character === '{' ? '{' : '}').replace(/[\r\t]/g, ' '); } /** Produce a renderer-only option. No input value is interpreted as HTML or executable code. */ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualChartTheme = {}): EChartsCoreOption { const ink = theme.ink || '#263c5a'; const mutedInk = theme.mutedInk || '#728198'; const line = theme.line || '#dfe5ef'; const colors = theme.colors?.length ? theme.colors : visual.stage === 'black' ? ['#607ae1', '#a8b4c4', '#d58c35', '#8b68c5'] : visual.stage === 'bright' ? ['#008f7d', '#a8b4c4', '#d58c35', '#8b68c5'] : DEFAULT_COLORS; // 坐标数据保留原始业务标签;提示框等富文本区域单独转义 ECharts 标记。 const categories = visual.categories.map((_item, index) => visualCategoryLabel(visual, index)); const categoryAxisLabel = { color: ink, fontSize: 11, hideOverlap: true, overflow: 'truncate' as const, width: 160 }; const numberAxisLabel = (value: number) => visual.unit === 'ratio' ? `${chartNumber(value)}%` : formatChartValue(value, visual.unit, false); const formatter = (raw: unknown): string => { const params = Array.isArray(raw) ? raw : [raw]; const first = params[0]; const object = isRecord(first) ? first : {}; if (visual.type === 'heatmap') { const tuple = Array.isArray(object.data) ? object.data : []; const categoryIndex = typeof tuple[0] === 'number' ? tuple[0] : -1; const seriesIndex = typeof tuple[1] === 'number' ? tuple[1] : -1; const rawValue = tuple[2]; if (categoryIndex < 0 || seriesIndex < 0 || typeof rawValue !== 'number') return ''; return [ plainRichText(visualCategoryLabel(visual, categoryIndex)), plainRichText(visual.series[seriesIndex]?.label || ''), formatVisualValue(visual.series[seriesIndex]?.values[categoryIndex] ?? null, visual.unit), ].filter(Boolean).join('\n'); } const dataIndex = typeof object.dataIndex === 'number' ? object.dataIndex : 0; if (visual.type === 'donut') { const value = visual.series[0]?.values[dataIndex]; const share = visualDonutShares(visual)[dataIndex]?.share; if (value === null || value === undefined || share === undefined) return ''; return [ plainRichText(visualCategoryLabel(visual, dataIndex)), `${plainRichText(visual.series[0].label)}:${formatVisualValue(value, 'kg')}`, `占本图列出类别重量合计:${visualDonutShareText(share)}`, ].join('\n'); } if (visual.type === 'pareto') { const point = visualParetoPoints(visual)[dataIndex]; if (!point) return ''; return [ plainRichText(visualCategoryLabel(visual, dataIndex)), `${plainRichText(visual.series[0].label)}:${formatVisualValue(point.valueKg, 'kg')}`, `${visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '本图类别占比'}:${visualDonutShareText(point.share)}`, `${visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占本图已列类别合计'}:${visualDonutShareText(point.cumulativeShare)}`, ].join('\n'); } if (visual.type === 'waterfall') { const value = visual.series[0]?.values[dataIndex] ?? null; if (value === null) return ''; return [ plainRichText(visualCategoryLabel(visual, dataIndex)), plainRichText(`期间:${plainPeriod(visual.comparisonPeriod || {})} → ${plainPeriod(visual.period)}`), `阶段影响:${formatVisualValue(value, 'pp')}`, ...(dataIndex === 2 ? ['黑片与亮片影响之和构成综合率变化。'] : []), '该拆解不代表生产根因。', ].join('\n'); } const category = visual.categories[dataIndex]; const lines = category ? [plainRichText(visualCategoryLabel(visual, dataIndex))] : []; if (visual.comparisonPeriod) lines.push(plainRichText(`期间:${plainPeriod(visual.comparisonPeriod)} → ${plainPeriod(visual.period)}`)); else lines.push(plainRichText(`期间:${plainPeriod(visual.period)}`)); for (const item of params) { if (!isRecord(item)) continue; const seriesIndex = typeof item.seriesIndex === 'number' ? item.seriesIndex : -1; const series = visual.series[seriesIndex]; if (series) lines.push(`${plainRichText(series.label)}:${formatVisualValue(series.values[dataIndex] ?? null, visual.unit)}`); } return lines.join('\n'); }; if (visual.type === 'waterfall') { const [black, bright, total] = visual.series[0].values as [number, number, number]; const endAfterBlack = black; const endAfterBright = black + bright; const baseline = [Math.min(0, black), Math.min(endAfterBlack, endAfterBright), 0]; const deltaValues = [Math.abs(black), Math.abs(bright), 0]; const minValue = Math.min(0, black, endAfterBright, total); const maxValue = Math.max(0, black, endAfterBright, total); const padding = Math.max((maxValue - minValue) * 0.18, 0.25); const barData = deltaValues.map((value, index) => ({ value, label: { ...(index === 2 ? { show: false } : {}), position: (index === 0 ? black : bright) < 0 ? 'bottom' : 'top' }, itemStyle: { color: index === 0 ? (black < 0 ? '#c66565' : '#607ae1') : (bright < 0 ? '#c66565' : '#008f7d') }, })); const totalData = [{ value: 0, label: { show: false } }, { value: 0, label: { show: false } }, { value: total, label: { position: total < 0 ? 'bottom' : 'top' }, itemStyle: { color: total < 0 ? '#c66565' : '#435d7a' }, }]; return { animation: false, color: ['#607ae1', '#435d7a'], tooltip: { trigger: 'axis', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: 'shadow' }, formatter }, legend: { show: true, selectedMode: false, type: 'plain', top: 8, data: ['阶段影响', '综合变化'], textStyle: { color: mutedInk, fontSize: 11 } }, grid: { left: 72, right: 34, top: 48, bottom: 64, containLabel: true }, xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 12, interval: 0, width: 150, overflow: 'break', lineHeight: 16 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } }, yAxis: { type: 'value', min: minValue - padding, max: maxValue + padding, scale: false, name: '变化(百分点)', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: numberAxisLabel }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } }, series: [ { name: '辅助基线', type: 'bar', stack: 'impact', stackStrategy: 'all', data: baseline, itemStyle: { color: 'transparent' }, emphasis: { disabled: true }, silent: true, tooltip: { show: false }, legendHoverLink: false }, { name: '阶段影响', type: 'bar', stack: 'impact', stackStrategy: 'all', data: barData, barMaxWidth: 56, label: { show: true, position: 'top', color: ink, fontSize: 11, formatter: (params: { dataIndex: number }) => formatChartValue(visual.series[0].values[params.dataIndex] ?? null, 'pp') }, emphasis: { disabled: true } }, { name: '综合变化', type: 'bar', stack: 'impact', stackStrategy: 'all', data: totalData, barMaxWidth: 56, label: { show: true, position: 'top', color: ink, fontSize: 11, formatter: () => formatChartValue(total, 'pp') }, emphasis: { disabled: true } }, ], aria: { enabled: true, decal: { show: false } }, }; } if (visual.type === 'heatmap') { const finiteValues = visual.series.flatMap(item => item.values.filter((value): value is number => value !== null) .map(value => visual.unit === 'ratio' ? chartNumber(value * 100) : chartNumber(value))); const minValue = Math.min(0, ...finiteValues); const maxValue = Math.max(0, ...finiteValues); const maxMagnitude = Math.max(Math.abs(minValue), Math.abs(maxValue)); const hasNegative = minValue < 0; const matrixData: Array<[number, number, number]> = []; visual.series.forEach((item, seriesIndex) => item.values.forEach((value, categoryIndex) => { if (value !== null) matrixData.push([categoryIndex, seriesIndex, visual.unit === 'ratio' ? chartNumber(value * 100) : chartNumber(value)]); })); const visualMin = hasNegative ? -maxMagnitude : 0; const visualMax = hasNegative ? maxMagnitude : maxMagnitude || 1; return { animation: false, tooltip: { trigger: 'item', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, formatter }, grid: { left: 18, right: 92, top: 18, bottom: 58, containLabel: true, backgroundColor: '#eef1f5' }, xAxis: { type: 'category', data: categories, axisLabel: { ...categoryAxisLabel, interval: 0, rotate: categories.length > 8 ? 25 : 0, width: 150 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false }, splitArea: { show: false } }, yAxis: { type: 'category', data: visual.series.map(item => plainRichText(item.label)), axisLabel: { color: ink, fontSize: 11, width: 150, overflow: 'truncate' }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } }, visualMap: { type: 'continuous', min: visualMin, max: visualMax, calculable: false, orient: 'vertical', right: 2, top: 'middle', itemHeight: 120, text: [numberAxisLabel(visualMax), numberAxisLabel(visualMin)], textStyle: { color: mutedInk, fontSize: 10 }, inRange: { color: hasNegative ? ['#557fb3', '#f1f3f5', '#c66565'] : ['#e8ebef', '#557fb3'] }, ...(hasNegative ? {} : { outOfRange: { color: '#e8ebef' } }), }, series: [{ name: plainRichText(visual.series[0]?.label || '数值'), type: 'heatmap', data: matrixData, label: { show: true, color: ink, fontSize: 11, formatter: (params: { data?: unknown }) => { const tuple = Array.isArray(params?.data) ? params.data : []; return typeof tuple[2] === 'number' ? tuple[2].toFixed(2) : ''; } }, itemStyle: { borderColor: '#ffffff', borderWidth: 2 }, emphasis: { disabled: true }, }], aria: { enabled: true, decal: { show: false } }, }; } if (visual.type === 'donut') { const shares = visualDonutShares(visual); const total = shares.reduce((sum, item) => sum + item.valueKg, 0); const pieData = shares.map(({ categoryIndex, valueKg, share }) => ({ name: plainRichText(visualCategoryLabel(visual, categoryIndex)), value: valueKg, visualCategoryIndex: categoryIndex, visualShare: share, itemStyle: { color: colors[categoryIndex % colors.length] }, })); return { animation: false, color: colors, tooltip: { trigger: 'item', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, formatter }, legend: { show: true, selectedMode: false, type: 'scroll', orient: 'horizontal', bottom: 3, left: 10, right: 10, textStyle: { color: mutedInk, fontSize: 11 } }, graphic: [{ type: 'text', left: 'center', top: '39%', silent: true, style: { text: `所列类别合计\n${formatChartValue(total, 'kg')}`, textAlign: 'center', fill: ink, font: '600 15px sans-serif', lineHeight: 24 }, }, { type: 'text', left: 'center', bottom: 30, silent: true, style: { text: '占比以本图列出类别重量合计为分母,不代表正式总报废占比', textAlign: 'center', fill: mutedInk, font: '10px sans-serif', width: 560, overflow: 'break', lineHeight: 15 }, }], series: [{ name: plainRichText(visual.series[0].label), type: 'pie', radius: ['42%', '66%'], center: ['50%', '44%'], avoidLabelOverlap: true, data: pieData, label: { show: true, position: 'outside', alignTo: 'labelLine', edgeDistance: 12, width: 210, overflow: 'break', lineHeight: 16, color: ink, fontSize: 11, formatter: (params: { dataIndex?: number }) => { const index = Number.isInteger(params?.dataIndex) ? params.dataIndex as number : -1; const share = shares[index]; if (!share) return ''; return `${plainRichText(visualCategoryLabel(visual, index))}\n${formatChartValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`; } }, labelLine: { show: true, length: 16, length2: 12, lineStyle: { color: line } }, emphasis: { disabled: true }, }], media: [{ query: { maxWidth: 480 }, option: { legend: { show: false }, series: [{ radius: ['44%', '72%'], center: ['50%', '45%'], label: { show: false }, labelLine: { show: false } }], graphic: [{ type: 'text', left: 'center', top: '39%', silent: true, style: { text: `所列类别合计\n${formatChartValue(total, 'kg')}`, textAlign: 'center', fill: ink, font: '600 15px sans-serif', lineHeight: 23 }, }, { type: 'text', left: 'center', bottom: 8, silent: true, style: { text: '占比以本图列出类别重量合计为分母,不代表正式总报废占比', textAlign: 'center', fill: mutedInk, font: '9px sans-serif', width: 300, overflow: 'break', lineHeight: 13 }, }], }, }], aria: { enabled: true, decal: { show: false } }, }; } if (visual.type === 'pareto') { const points = visualParetoPoints(visual); const allScopeWeight = visual.coverage.shareBasis === 'all_scope_weight'; const cumulativeName = allScopeWeight ? '累计占全部重量' : '累计占本图已列类别合计'; return { animation: false, color: [colors[0], '#435d7a'], tooltip: { trigger: 'axis', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: 'shadow' }, formatter }, legend: { show: true, selectedMode: false, type: 'plain', top: 6, left: 12, data: [plainRichText(visual.series[0].label), cumulativeName], textStyle: { color: mutedInk, fontSize: 10 } }, grid: { left: 56, right: 66, top: 36, bottom: 70, containLabel: true }, xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: allScopeWeight ? 0 : categories.length > 3 ? 34 : 0, width: allScopeWeight ? 80 : 160, overflow: 'break', hideOverlap: false, lineHeight: 13, ...(allScopeWeight ? { formatter: (name: string) => wrapAxisLabel(name, 80, 10, 5).join('\n') } : {}) }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } }, yAxis: [ { type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } }, { type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? cumulativeName : '累计占比', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } }, ], series: [ { name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: colors[0] }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { dataIndex: number }) => paretoWeightLabel(points[params.dataIndex]?.valueKg ?? null, allScopeWeight) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}), emphasis: { disabled: true } }, { name: cumulativeName, type: 'line', yAxisIndex: 1, data: points.map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: ink }, itemStyle: { color: ink }, label: { show: true, position: allScopeWeight ? 'bottom' : 'top', distance: 7, color: ink, fontSize: 10, formatter: (params: { data?: number; dataIndex?: number }) => allScopeWeight && params.dataIndex !== points.length - 1 ? '' : visualDonutShareText((params.data || 0) / 100) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}), emphasis: { disabled: true } }, ], aria: { enabled: true, decal: { show: false } }, }; } const combinedDefects = visual.sectionKey === 'defect_combined' && visual.type === 'bar'; const series = visual.series.map((item, seriesIndex) => ({ name: plainRichText(item.label), type: visual.type === 'area' ? 'line' : visual.type === 'column' ? 'bar' : visual.type, data: item.values.map(value => { if (value === null) return null; const plotted = visual.unit === 'ratio' ? chartNumber(value * 100) : value; return visual.type === 'column' ? { value: plotted, label: { position: value < 0 ? 'bottom' : 'top' } } : plotted; }), itemStyle: { color: colors[seriesIndex % colors.length] }, connectNulls: false, smooth: false, ...(['bar', 'column'].includes(visual.type) ? { barMaxWidth: combinedDefects ? 18 : 32, ...(combinedDefects ? { stack: 'combined-defect-stage', barWidth: 18 } : {}), ...(visual.type === 'column' ? { barCategoryGap: '35%' } : {}), label: { show: true, position: visual.type === 'column' ? 'top' : 'right', color: ink, fontSize: 11, formatter: (raw: { dataIndex: number }) => { const value = item.values[raw.dataIndex]; return formatChartValue(value ?? null, visual.unit); } }, emphasis: { focus: 'series' }, } : { symbol: 'circle', symbolSize: 6, lineStyle: { width: 2.4 }, ...(visual.type === 'area' ? { areaStyle: { opacity: 0.18, color: colors[seriesIndex % colors.length] } } : {}), }), })); const horizontalBar = visual.type === 'bar'; const verticalBar = visual.type === 'column'; const tooltip = { trigger: 'axis' as const, renderMode: 'richText' as const, backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: horizontalBar || verticalBar ? 'shadow' as const : 'line' as const }, formatter }; const legend = { show: visual.series.length > 1 && !combinedDefects, type: 'scroll' as const, top: 8, textStyle: { color: mutedInk, fontSize: 11 } }; const grid = { left: horizontalBar ? 18 : 48, right: horizontalBar ? 96 : 24, top: visual.series.length > 1 && !combinedDefects ? 48 : 18, bottom: verticalBar ? 78 : 24, containLabel: true }; const shared = { animation: false as const, color: colors, tooltip, legend, grid, aria: { enabled: true, decal: { show: false } } }; const valueAxis = { type: 'value' as const, min: visual.unit === 'ratio' ? 0 : undefined, max: ratioAxisMax(visual), scale: visual.unit !== 'ratio' ? false : undefined, splitNumber: 3, axisLabel: { color: mutedInk, formatter: numberAxisLabel, hideOverlap: true }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' as const } }, }; if (horizontalBar) { return { ...shared, xAxis: { ...valueAxis, axisLabel: { ...valueAxis.axisLabel, margin: 10 } }, yAxis: { type: 'category', inverse: true, data: categories, axisLabel: categoryAxisLabel, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } }, series, }; } if (verticalBar) { const columnCategories = categories.map(label => truncateText(label, 16)); return { ...shared, xAxis: { type: 'category', data: columnCategories, axisLabel: { ...categoryAxisLabel, interval: 0, rotate: categories.length > 8 ? 28 : 0, width: 130, lineHeight: 14 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } }, yAxis: { ...valueAxis, axisLabel: { ...valueAxis.axisLabel, margin: 10 }, axisLine: { lineStyle: { color: line } } }, series, }; } return { ...shared, xAxis: { type: 'category', data: categories, boundaryGap: false, axisLabel: { ...categoryAxisLabel, rotate: categories.length > 10 ? 25 : 0, width: 120 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } }, yAxis: valueAxis, series, }; } function truncateText(value: string, maxCharacters: number): string { const characters = Array.from(value); return characters.length > maxCharacters ? `${characters.slice(0, maxCharacters - 1).join('')}…` : value; } function wrapLines(value: string, maxChars: number, maxLines = Number.POSITIVE_INFINITY): string[] { const normalized = value.replace(/\s+/g, ' ').trim(); if (!normalized) return []; const chars = Array.from(normalized); const lines: string[] = []; for (let index = 0; index < chars.length; index += maxChars) { if (lines.length >= maxLines) { const last = lines.length - 1; lines[last] = `${lines[last].replace(/…$/, '')}…`; return lines; } lines.push(chars.slice(index, index + maxChars).join('')); } return lines; } /** Use the same font and column width as the axis so export height includes every rendered line. */ function wrapAxisLabel(value: string, width: number, fontSize: number, maxLines = Number.POSITIVE_INFINITY): string[] { const text = plainRichText(value).replace(/\s+/g, ' ').trim(); if (!text) return []; let context: CanvasRenderingContext2D | null = null; if (typeof document !== 'undefined') { try { context = document.createElement('canvas').getContext('2d'); } catch { /* Conservative SSR fallback below. */ } } if (context) context.font = `${fontSize}px sans-serif`; const measure = (line: string) => context ? context.measureText(line).width : Array.from(line).length * fontSize; const lines: string[] = []; let line = ''; for (const char of Array.from(text)) { if (line && measure(line + char) > width - 2) { lines.push(line); line = ''; if (lines.length >= maxLines) { let tail = lines[lines.length - 1]; while (tail && measure(tail + '…') > width - 2) tail = Array.from(tail).slice(0, -1).join(''); lines[lines.length - 1] = tail + '…'; return lines; } } line += char; } if (line) lines.push(line); return lines; } export function visualUnitLabel(visual: AnalysisVisual): string { const unit = visual.unit; if (unit === 'ratio') return isScrapRateMetric(visual.metric) ? '报废率(%)' : '合格率(%)'; if (unit === 'kg') return '重量(kg)'; if (unit === 'pp') return '变化(百分点)'; return '数量'; } export interface AnalysisVisualExportOption { option: EChartsCoreOption; width: number; height: number; } /** Add static report context around the complete, unfiltered snapshot for PNG export. */ export type AnalysisVisualRenderContext = 'standalone' | 'report'; export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width = 1280, context: AnalysisVisualRenderContext = 'standalone'): AnalysisVisualExportOption { const reportMode = context === 'report'; const titleLines = reportMode ? [] : wrapLines(visual.title, 34, 3); const headerParts = reportMode ? [] : [ visual.subtitle, `期间:${visualPeriodSummary(visual)}`, `范围:${visualScopeSummary(visual.scope) || '按本轮查询条件'}`, `单位:${visualUnitLabel(visual)}`, ...(visual.stage ? [`阶段:${visual.stage === 'black' ? '黑片' : '亮片'}`] : []), visual.coverage.truncated ? `本图展示 ${visual.coverage.returnedRows} / 共 ${visual.coverage.totalRows} 项` : `覆盖:共 ${visual.coverage.totalRows} 项`, ...(visual.type === 'donut' ? ['占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废占比'] : visual.type === 'pareto' ? [visual.coverage.shareBasis === 'all_scope_weight' ? '累计占比口径:以同范围全部重量为分母,Top末项可以低于100%' : '累计占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废累计占比'] : visual.coverage.shareBasis ? [`占比口径:${visual.coverage.shareBasis}`] : []), ].filter(Boolean); const headerLines = headerParts.flatMap(part => wrapLines(part, 96, 4)); const chartTop = reportMode ? 18 : 30 + titleLines.length * 28 + headerLines.length * 17 + 20; const footerParts = [ ...(!reportMode && visual.type === 'donut' ? visualDonutShares(visual).map(({ categoryIndex, valueKg, share }) => `${visualCategoryLabel(visual, categoryIndex)}:${formatChartValue(valueKg, 'kg')}(占本图已列类别重量合计 ${visualDonutShareText(share)})`) : []), ...(visual.type === 'pareto' ? [visual.coverage.shareBasis === 'all_scope_weight' ? '累计占比=所列累计重量÷同范围全部重量;Top未覆盖全量时不补足100%' : '柏拉图累计占比=累计重量÷本图已列类别重量合计;不代表正式总报废累计占比'] : []), ...(visual.type === 'waterfall' ? ['阶段影响是对综合合格率变化的拆解,不代表生产根因。'] : []), ...(!reportMode && visual.note ? [`说明:${visual.note}`] : []), ...(!reportMode && visual.evidenceRefs.length ? [`证据引用:${visual.evidenceRefs.join(' · ')}`] : []), ]; const footerLines = footerParts.flatMap(part => wrapLines(part, 124)); const chartBottom = footerLines.length ? footerLines.length * 15 + (reportMode ? 20 : 28) : (reportMode ? 10 : 24); const allScopeWeight = visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight'; const rankingLabelWidth = Math.max(16, (width - 174) / Math.max(1, visual.categories.length) - 8); const wrappedCategories = visual.categories.map((_category, index) => allScopeWeight ? wrapAxisLabel(visualCategoryLabel(visual, index), rankingLabelWidth, reportMode ? 14 : 10) : wrapLines(visualCategoryLabel(visual, index), 14)); const categoryLabelHeight = wrappedCategories.reduce((total, lines) => total + Math.max(28, lines.length * 14 + 8), 0); const maxCategoryLines = Math.max(1, ...wrappedCategories.map(lines => lines.length)); const combinedDefects = visual.sectionKey === 'defect_combined' && visual.type === 'bar'; const reportCartesian = reportMode && ['column', 'line', 'area'].includes(visual.type); const reportRotation = visual.type === 'column' ? (visual.categories.length > 5 ? 42 : 0) : (visual.categories.length > 12 ? 42 : 0); const reportLabelWidth = Math.min(160, Math.max(1, ...wrappedCategories.flatMap(lines => lines.map(line => Array.from(line).length * 14)))); const reportLabelHeight = Math.ceil(Math.sin(reportRotation * Math.PI / 180) * reportLabelWidth + Math.cos(reportRotation * Math.PI / 180) * maxCategoryLines * 18) + 22; const reportLegendHeight = visual.series.length > 1 ? 30 : 0; const reportPlotHeight = 230; const chartHeight = visual.type === 'donut' ? (reportMode ? Math.max(390, 290 + maxCategoryLines * 20) : Math.max(600, 300 + maxCategoryLines * 20)) : visual.type === 'waterfall' ? (reportMode ? 300 : 480) : visual.type === 'heatmap' ? Math.max(reportMode ? 180 : 240, visual.series.length * (reportMode ? 62 : 90)) : visual.type === 'pareto' ? (allScopeWeight ? 330 + maxCategoryLines * (reportMode ? 18 : 14) : reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight)) : combinedDefects ? Math.max(reportMode ? 350 : 410, visual.categories.length * (reportMode ? 42 : 46)) : reportCartesian ? reportPlotHeight + reportLabelHeight + reportLegendHeight : reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight); const height = chartTop + chartHeight + chartBottom; const base = buildAnalysisVisualOption(visual, { ink: '#263c5a', mutedInk: '#65748b', line: '#dfe5ef', surface: '#ffffff' }); const categories = wrappedCategories.map(lines => lines.join('\n')); const donutShares = visual.type === 'donut' ? visualDonutShares(visual) : []; const valueAxisLabel = (value: number) => visual.unit === 'ratio' ? `${chartNumber(value)}%` : formatChartValue(value, visual.unit, false); const allSeriesSelected = Object.fromEntries(visual.series.map(series => [plainRichText(series.label), true])); const legendOption = visual.type === 'donut' ? { show: true, selectedMode: false, type: 'scroll' as const, orient: 'horizontal' as const, left: 44, right: 44, bottom: chartBottom + 4, textStyle: { color: '#65748b', fontSize: 11 }, formatter: (name: string) => { const index = visual.categories.findIndex((_category, categoryIndex) => plainRichText(visualCategoryLabel(visual, categoryIndex)) === name); const share = donutShares[index]; return index < 0 || !share ? plainRichText(name) : plainRichText(`${name} · ${formatChartValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`); }, } : visual.type === 'pareto' ? { show: true, type: 'plain' as const, top: reportMode ? chartTop + 2 : chartTop - 26, left: 56, data: [plainRichText(visual.series[0].label), allScopeWeight ? '累计占全部重量' : '累计占本图已列类别合计'], textStyle: { color: '#65748b', fontSize: 11 }, } : { show: visual.series.length > 1 && !combinedDefects, type: 'scroll' as const, top: reportMode ? chartTop + 2 : chartTop - 26, left: 56, selected: allSeriesSelected, textStyle: { color: '#65748b', fontSize: 11 }, }; const option: EChartsCoreOption = { ...base, animation: false, tooltip: { show: false }, title: reportMode ? { show: false, text: '', subtext: '' } : { text: plainRichText(titleLines.join('\n')), subtext: plainRichText(headerLines.join('\n')), left: 56, top: 18, textStyle: { color: '#263c5a', fontSize: 19, fontWeight: 650, lineHeight: 27 }, subtextStyle: { color: '#65748b', fontSize: 11, lineHeight: 16 }, }, legend: legendOption, ...(footerLines.length ? { graphic: { elements: [{ type: 'text', left: 56, top: chartTop + chartHeight + 14, silent: true, style: { text: plainRichText(footerLines.join('\n')), fill: '#65748b', font: '11px sans-serif', lineHeight: 15 }, }], }, } : {}), ...(visual.type === 'donut' ? { grid: undefined, graphic: { elements: [ ...(donutShares.length ? [{ type: 'text', left: 'center', top: chartTop + chartHeight * 0.39 - 22, silent: true, style: { text: `所列类别合计\n${formatChartValue(donutShares.reduce((sum, item) => sum + item.valueKg, 0), 'kg')}`, textAlign: 'center', fill: '#263c5a', font: '600 16px sans-serif', lineHeight: 25 }, }] : []), ...(footerLines.length ? [{ type: 'text', left: 56, top: chartTop + chartHeight + 14, silent: true, style: { text: plainRichText(footerLines.join('\n')), fill: '#65748b', font: '11px sans-serif', lineHeight: 15 }, }] : []), ], }, series: [{ ...(Array.isArray((base as any).series) ? (base as any).series[0] : {}), center: [width / 2, chartTop + chartHeight * 0.39], radius: ['21%', '34%'], label: { show: true, position: 'outside', alignTo: 'labelLine', edgeDistance: 26, width: 235, overflow: 'break', lineHeight: 17, color: '#263c5a', fontSize: 11, formatter: (params: { dataIndex?: number }) => { const index = Number.isInteger(params?.dataIndex) ? params.dataIndex as number : -1; const share = donutShares[index]; return share ? plainRichText(`${visualCategoryLabel(visual, index)}\n${formatChartValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`) : ''; }, }, labelLine: { show: true, length: 16, length2: 12, lineStyle: { color: '#dfe5ef' } }, emphasis: { disabled: true }, }], } : visual.type === 'heatmap' ? { grid: { left: 32, right: 148, top: chartTop + 8, bottom: chartBottom + 78, containLabel: true, backgroundColor: '#eef1f5' }, xAxis: { type: 'category', data: categories, axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: categories.length > 10 ? 28 : 0, width: 112, overflow: 'break', interval: 0 }, axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false }, }, yAxis: { type: 'category', data: visual.series.map(series => plainRichText(series.label)), axisLabel: { color: '#263c5a', fontSize: 11, lineHeight: 14, width: 180, overflow: 'break', interval: 0 }, axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false }, }, visualMap: { ...(base as any).visualMap, right: 18, top: chartTop + chartHeight * 0.2, itemHeight: Math.min(220, chartHeight * 0.5) }, series: [{ ...((base as any).series?.[0] || {}), label: { ...((base as any).series?.[0]?.label || {}), show: visual.categories.length <= 16 }, }], } : visual.type === 'pareto' ? { grid: allScopeWeight ? { left: 78, right: 96, top: chartTop + 48, height: 260, containLabel: false } : { left: 78, right: 78, top: chartTop, bottom: chartBottom + 96, containLabel: true }, xAxis: { type: 'category', data: categories, boundaryGap: true, axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: allScopeWeight ? 0 : categories.length > 3 ? 20 : 0, width: allScopeWeight ? rankingLabelWidth : 190, overflow: 'break', interval: 0, ...(allScopeWeight ? { fontFamily: 'sans-serif' } : {}) }, axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false }, }, yAxis: [ { type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } } }, { type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? '累计占全部重量' : '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } }, ], series: [ { name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: '#607ae1' }, label: { show: true, position: 'top', color: '#263c5a', fontSize: 10, formatter: (params: { dataIndex: number }) => paretoWeightLabel(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, allScopeWeight) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}) }, { name: visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占本图已列类别合计', type: 'line', yAxisIndex: 1, data: visualParetoPoints(visual).map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: '#435d7a' }, itemStyle: { color: '#435d7a' }, label: { show: true, position: allScopeWeight ? 'bottom' : 'top', distance: 8, color: '#435d7a', fontSize: 10, formatter: (params: { data?: number; dataIndex?: number }) => allScopeWeight && params.dataIndex !== visual.categories.length - 1 ? '' : visualDonutShareText((params.data || 0) / 100) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}) }, ], } : visual.type === 'waterfall' ? { legend: { show: false }, grid: { left: 76, right: 42, top: chartTop + 8, bottom: chartBottom + 76, containLabel: true }, xAxis: { type: 'category', data: categories, boundaryGap: true, axisLabel: { color: '#263c5a', fontSize: 11, lineHeight: 15, width: 180, overflow: 'break', interval: 0, hideOverlap: false }, axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false }, }, yAxis: { type: 'value', min: (base as any).yAxis?.min, max: (base as any).yAxis?.max, scale: false, name: '变化(百分点)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: valueAxisLabel }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } }, }, series: (base as any).series, } : visual.type === 'bar' ? { xAxis: { type: 'value', min: visual.unit === 'ratio' ? 0 : undefined, max: ratioAxisMax(visual), scale: visual.unit !== 'ratio' ? false : undefined, axisLabel: { color: '#65748b', formatter: valueAxisLabel }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } }, }, yAxis: { type: 'category', inverse: true, data: categories, axisLabel: { color: '#263c5a', fontSize: 11, lineHeight: 14, width: 220, overflow: 'break', interval: 0 }, axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false }, }, grid: { left: 24, right: 42, top: chartTop, bottom: chartBottom, containLabel: true }, } : { xAxis: { type: 'category', data: categories, boundaryGap: visual.type === 'column', axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 13, rotate: reportCartesian ? reportRotation : categories.length > 5 ? 42 : 0, width: 160, overflow: 'break', interval: 0, hideOverlap: false }, axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false }, }, yAxis: { type: 'value', min: visual.unit === 'ratio' ? 0 : undefined, max: ratioAxisMax(visual), scale: visual.unit !== 'ratio' ? false : undefined, axisLabel: { color: '#65748b', formatter: valueAxisLabel }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } }, }, // Keep a real plot rectangle; containLabel may otherwise subtract all available // height for the fixed-width rotated category labels and flatten the series. grid: reportCartesian ? { left: 64, right: 42, top: chartTop + reportLegendHeight, height: reportPlotHeight, containLabel: false } : { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : 68), containLabel: true }, }), }; if (reportMode) { // 图片按报告正文列宽显示,确保缩放后的标签仍然可读。 const enlargeText = (value: unknown): void => { if (!value || typeof value !== 'object') return; for (const [key, child] of Object.entries(value)) { if (key === 'fontSize' && typeof child === 'number') (value as Record)[key] = Math.max(14, child); else if (key === 'lineHeight' && typeof child === 'number') (value as Record)[key] = Math.max(18, child); else enlargeText(child); } }; enlargeText(option); (option as Record).textStyle = { fontSize: 14, fontFamily: '-apple-system,BlinkMacSystemFont,PingFang SC,Microsoft YaHei,sans-serif' }; } return { option, width, height }; } function plainPeriod(period: Record): string { const numeric = parseAnalysisPeriod(period); if (numeric?.monthStart !== undefined && numeric.monthEnd !== undefined) return analysisPeriodLabel(period); if (numeric?.year && numeric.month !== undefined) return `${numeric.year}-${String(numeric.month).padStart(2, '0')}`; if (numeric?.year && numeric.quarter !== undefined) return `${numeric.year}年第${numeric.quarter}季度`; if (numeric?.year) return `${numeric.year} 年`; const label = typeof period.label === 'string' ? period.label : null; if (label) return label; const start = ['start', 'from', 'startMonth', 'begin'].map(key => period[key]).find(value => typeof value === 'string'); const end = ['end', 'to', 'endMonth', 'finish'].map(key => period[key]).find(value => typeof value === 'string'); if (typeof start === 'string' && typeof end === 'string') return start === end ? start : `${start} 至 ${end}`; if (typeof start === 'string') return start; if (typeof end === 'string') return end; return '当前期间'; } export function visualScopeSummary(scope: AnalysisVisual['scope']): string { const labels: Record = { department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组', stage: '阶段', rateBasis: '口径', basis: '口径', includeUnassigned: '含未分类', productSearch: '产品检索', }; const parts = Object.entries(scope) .filter(([key, value]) => key in labels && value !== '' && value !== false) .map(([key, value]) => `${labels[key]}:${key === 'stage' ? ({ black: '黑片', bright: '亮片' }[String(value)] || String(value)) : value === true ? '是' : Array.isArray(value) ? value.join('、') : String(value)}`); const filters = scope.extraFilters; if (filters && typeof filters === 'object' && !Array.isArray(filters) && Object.keys(filters).length > 0) parts.push(`额外筛选 ${Object.keys(filters).length} 项`); parts.push(...analysisExclusionSummary(scope.exclusions)); parts.push(...columnFilterSummary(scope.columnFilters, scope.columnLabels)); return parts.join(' · '); } export function analysisExclusionSummary(value: unknown): string[] { const exclusions = safeExclusions(value); if (!exclusions) return []; const labels: Record = { department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组', }; return (['department', 'group', 'product', 'projectGroup'] as const).flatMap(dimension => { const values = exclusions[dimension]; return values?.length ? [`排除${labels[dimension]}:${values.join('、')}`] : []; }); } export function columnFilterSummary(value: unknown, labelValue: unknown): string[] { if (!Array.isArray(value)) return []; const labels = isRecord(labelValue) ? labelValue : {}; return value.flatMap(rule => { if (!isRecord(rule) || typeof rule.field !== 'string' || !Array.isArray(rule.stages)) return []; const stage = rule.stages.map(item => item === 'black' ? '黑片' : item === 'bright' ? '亮片' : '').filter(Boolean).join('、'); const label = typeof labels[rule.field] === 'string' ? labels[rule.field] : '来源字段'; const operation = ({ in: '为', not_in: '排除', is_empty: '为空', not_empty: '不为空' } as Record)[String(rule.operator)]; if (!operation) return []; const values = Array.isArray(rule.values) ? rule.values.filter(item => typeof item === 'string').join('、') : ''; return [`${stage} ${label}${operation}${values}`.trim()]; }); } export function visualPeriodSummary(visual: AnalysisVisual): string { return visual.comparisonPeriod ? `${plainPeriod(visual.comparisonPeriod)} → ${plainPeriod(visual.period)}` : plainPeriod(visual.period); } export function isVisualCellInvalid(visual: AnalysisVisual, seriesIndex: number, categoryIndex: number): boolean { return visual.invalidValueCells.includes(`${seriesIndex}:${categoryIndex}`); } function escapeHtml(value: string): string { return value.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character] || character); } /** Build a standalone report table from the same snapshot. All dynamic values are HTML-escaped. */ export function renderVisualTableHtml(visualOrUnknown: AnalysisVisual | unknown): string { const visual = parseAnalysisVisuals([visualOrUnknown]).visuals[0]; if (!visual) throw new Error('没有可导出的图表数据'); const period = escapeHtml(visualPeriodSummary(visual)); const scope = escapeHtml(visualScopeSummary(visual.scope)); const subtitle = escapeHtml(visual.subtitle); const donutShares = visual.type === 'donut' ? visualDonutShares(visual) : []; const heading = [escapeHtml(visual.title), subtitle, `期间:${period}`, scope, ...(donutShares.length ? ['占比以本图所列类别重量合计为分母,不代表正式总报废占比'] : [])].filter(Boolean).join(' · '); const headers = ['序号', '对象名称', ...visual.series.map(item => escapeHtml(item.label)), ...(donutShares.length ? ['占本图已列类别合计'] : [])] .map(label => `${label}`).join(''); const rows = visual.categories.map((_category, categoryIndex) => { const values = visual.series.map((series, seriesIndex) => { const label = isVisualCellInvalid(visual, seriesIndex, categoryIndex) ? '无效值' : formatVisualValue(series.values[categoryIndex], visual.unit); return `${escapeHtml(label)}`; }).join(''); const share = donutShares[categoryIndex]; const shareCell = share ? `${escapeHtml(visualDonutShareText(share.share))}` : ''; return `${categoryIndex + 1}${escapeHtml(visualCategoryLabel(visual, categoryIndex))}${values}${shareCell}`; }).join(''); return `${headers}${rows}
${heading}
`; } type EChartsRuntime = typeof import('echarts/core'); let runtimePromise: Promise | undefined; async function loadECharts(): Promise { if (!runtimePromise) { runtimePromise = import('./analysisVisualsECharts').then(module => module.echarts) .catch(error => { runtimePromise = undefined; throw error; }); } return runtimePromise; } export async function loadAnalysisVisualECharts(): Promise { return loadECharts(); } function waitForChartFinished(chart: ReturnType, signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { throwIfAborted(signal); let timer = 0; const finish = () => { window.clearTimeout(timer); chart.off('finished', finish); signal?.removeEventListener('abort', abort); resolve(); }; const abort = () => { window.clearTimeout(timer); chart.off('finished', finish); reject(new DOMException('图表导出已取消', 'AbortError')); }; timer = window.setTimeout(finish, 1200); chart.on('finished', finish); signal?.addEventListener('abort', abort, { once: true }); }); } function throwIfAborted(signal?: AbortSignal): void { if (signal?.aborted) throw new DOMException('图表导出已取消', 'AbortError'); } function waitForFrame(signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { throwIfAborted(signal); const frame = requestAnimationFrame(() => { signal?.removeEventListener('abort', abort); resolve(); }); const abort = () => { cancelAnimationFrame(frame); reject(new DOMException('图表导出已取消', 'AbortError')); }; signal?.addEventListener('abort', abort, { once: true }); }); } function waitForFont(signal?: AbortSignal): Promise { if (!('fonts' in document)) return Promise.resolve(); return new Promise((resolve, reject) => { throwIfAborted(signal); const timeout = window.setTimeout(done, 900); const abort = () => { window.clearTimeout(timeout); reject(new DOMException('图表导出已取消', 'AbortError')); }; function done() { window.clearTimeout(timeout); signal?.removeEventListener('abort', abort); resolve(); } signal?.addEventListener('abort', abort, { once: true }); void document.fonts.ready.then(done, done); }); } function svgToPng(svg: string, width: number, height: number, signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { throwIfAborted(signal); const parsedSvg = new DOMParser().parseFromString(svg, 'image/svg+xml'); const syntaxError = parsedSvg.querySelector('parsererror'); if (syntaxError) { reject(new Error(`图表 SVG 格式错误:${syntaxError.textContent?.slice(0, 240)}`)); return; } const svgUrl = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })); const image = new Image(); const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const context = canvas.getContext('2d'); if (!context) { URL.revokeObjectURL(svgUrl); reject(new Error('当前浏览器无法创建图片画布')); return; } const cleanup = () => { window.clearTimeout(timeout); URL.revokeObjectURL(svgUrl); image.onload = null; image.onerror = null; signal?.removeEventListener('abort', abort); }; const abort = () => { cleanup(); reject(new DOMException('图表导出已取消', 'AbortError')); }; const timeout = window.setTimeout(() => { cleanup(); reject(new Error('PNG 导出渲染超时')); }, 5000); image.onerror = () => { cleanup(); reject(new Error('图表静态图片生成失败')); }; image.onload = () => { try { throwIfAborted(signal); context.fillStyle = '#ffffff'; context.fillRect(0, 0, width, height); context.drawImage(image, 0, 0, width, height); const result = canvas.toDataURL('image/png'); cleanup(); resolve(result); } catch (error) { cleanup(); reject(error); } }; signal?.addEventListener('abort', abort, { once: true }); image.src = svgUrl; }); } /** Render a snapshot independently of any visible chart instance or current legend state. */ export async function renderVisualPng(visualOrUnknown: AnalysisVisual | unknown, signal?: AbortSignal, context: AnalysisVisualRenderContext = 'standalone'): Promise { const parsed = parseAnalysisVisuals([visualOrUnknown]); const visual = parsed.visuals[0]; if (!visual || !visual.chartable) throw new Error(visual?.chartIssue || parsed.issues[0] || '没有可导出的图表数据'); if (typeof document === 'undefined') throw new Error('图表图片只能在浏览器中生成'); throwIfAborted(signal); const { option, width, height } = buildAnalysisVisualExportOption(visual, context === 'report' ? 900 : 1280, context); const node = document.createElement('div'); Object.assign(node.style, { position: 'fixed', left: '-10000px', top: '0', width: `${width}px`, height: `${height}px`, background: '#ffffff', color: '#263c5a', pointerEvents: 'none' }); document.body.appendChild(node); let chart: ReturnType | undefined; try { const echarts = await loadECharts(); throwIfAborted(signal); chart = echarts.init(node, 'light', { renderer: 'svg', width, height }); await waitForFont(signal); throwIfAborted(signal); const finished = waitForChartFinished(chart, signal); chart.setOption(option, { notMerge: true, lazyUpdate: false }); await finished; await waitForFrame(signal); throwIfAborted(signal); const svg = chart.renderToSVGString({ useViewBox: true }); return await svgToPng(svg, width, height, signal); } finally { chart?.dispose(); node.remove(); } }