140 lines
12 KiB
TypeScript
140 lines
12 KiB
TypeScript
import { originalAnalysisBody } from './analysisOriginalBody';
|
||
import { AnalysisOriginalContent } from './AnalysisOriginalContent';
|
||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||
import { Button } from 'antd';
|
||
import { AiMarkdown } from './AiMarkdown';
|
||
import { AnalysisConclusion } from './AnalysisConclusion';
|
||
import { AnalysisVisuals } from './AnalysisVisuals';
|
||
import { buildAnalysisNarrative, useCompactRateComparison, type FocusProductRow, type NarrativeSection } from './analysisReportModel';
|
||
import { visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel';
|
||
import { AnalysisProductDrilldown, type ProductDrilldownSelection } from './ProductDrilldownDrawer';
|
||
import { resolveProductDrilldown, type ProductDrilldownView } from './analysisProductDrilldown';
|
||
import './analysis-narrative.css';
|
||
import { buildAnalysisReadingModel, type AnalysisReadingSummary } from './analysisReadingModel';
|
||
|
||
export function ReadingSummary({ reading, evidenceLabels, evidencePrefix }: {
|
||
reading: AnalysisReadingSummary; evidenceLabels: Record<string, string>; evidencePrefix: string;
|
||
}) {
|
||
const text = (content: string) => <AiMarkdown className="ai-answer" content={content} evidenceLabels={evidenceLabels} evidencePrefix={evidencePrefix} />;
|
||
return <section className="analysis-reading-summary" aria-label="核心结论">
|
||
<h3 className="analysis-narrative-title">核心结论</h3>
|
||
{text(reading.lead)}
|
||
{!!reading.evidence.length && <div className="analysis-reading-evidence"><h4>关键依据</h4><ul>{reading.evidence.map((item, index) => <li key={index}>{text(item)}</li>)}</ul></div>}
|
||
{!!reading.notices.length && <div className="analysis-reading-notices" role="note">{reading.notices.map((item, index) => <div key={index}>{text(item)}</div>)}</div>}
|
||
</section>;
|
||
}
|
||
|
||
function metricName(visual: AnalysisVisual): string {
|
||
return ({ composite_rate: '综合合格率', black_rate: '黑片合格率', bright_rate: '亮片合格率' } as Record<string, string>)[visual.metric] || visual.series[0].label;
|
||
}
|
||
|
||
export function RateComparisonReadout({ visual }: { visual: AnalysisVisual }) {
|
||
const [before, after] = visual.series[0].values as [number, number];
|
||
const delta = (after - before) * 100;
|
||
const changed = Math.abs(delta) >= 0.005;
|
||
const { stage: _stage, ...businessScope } = visual.scope;
|
||
const scopeLabel = visualScopeSummary(businessScope);
|
||
return <div className="analysis-rate-readout" aria-label={`${metricName(visual)}两期比较`}>
|
||
<div className="analysis-rate-name">{metricName(visual)}</div>
|
||
{scopeLabel && <div className="analysis-rate-scope">{scopeLabel}</div>}
|
||
<div className="analysis-rate-values">
|
||
<div className="analysis-rate-previous"><small>{visualPeriodSummary({ ...visual, period: visual.comparisonPeriod!, comparisonPeriod: undefined })}</small><span>{(before * 100).toFixed(2)}<em>%</em></span></div>
|
||
<span className="analysis-rate-arrow" aria-hidden="true">→</span>
|
||
<div className="analysis-rate-current"><small>{visualPeriodSummary({ ...visual, comparisonPeriod: undefined })}</small><strong>{(after * 100).toFixed(2)}<em>%</em></strong></div>
|
||
<div className={`analysis-rate-change ${changed ? delta < 0 ? 'is-worse' : 'is-better' : ''}`}><strong>{changed ? `${delta > 0 ? '+' : ''}${delta.toFixed(2)}` : '0.00'}</strong><span>个百分点 · {changed ? delta < 0 ? '下降' : '上升' : '持平'}</span></div>
|
||
</div>
|
||
</div>;
|
||
}
|
||
|
||
export function NarrativeEvidence({ model, prefix }: { model: ReturnType<typeof buildAnalysisNarrative>; prefix: string }) {
|
||
const details = useRef<HTMLDetailsElement>(null);
|
||
useEffect(() => {
|
||
const revealLinkedEvidence = () => {
|
||
const target = window.location.hash.slice(1);
|
||
if (target.startsWith(prefix) && model.evidence.some(item => `${prefix}${item.ref}` === target) && details.current) {
|
||
details.current.open = true;
|
||
}
|
||
};
|
||
revealLinkedEvidence();
|
||
window.addEventListener('hashchange', revealLinkedEvidence);
|
||
return () => window.removeEventListener('hashchange', revealLinkedEvidence);
|
||
}, [model.evidence, prefix]);
|
||
if (!model.evidence.length) return null;
|
||
return <footer className="analysis-narrative-evidence"><details ref={details}><summary>数据依据</summary><ol>{model.evidence.map(item => <li id={`${prefix}${item.ref}`} key={item.ref}><strong>{item.label}</strong><span>{item.context}</span><code>{item.ref}</code></li>)}</ol></details></footer>;
|
||
}
|
||
|
||
/** The same cited rows are used in chat and exported reports; no metrics are calculated here. */
|
||
export function FocusProductTable({ rows, evidenceLabels, evidencePrefix, onDrilldown, drilldownUnavailableReason }: {
|
||
rows: FocusProductRow[]; evidenceLabels: Record<string, string>; evidencePrefix: string;
|
||
onDrilldown?: (row: FocusProductRow, view: ProductDrilldownView, trigger: HTMLElement) => void;
|
||
drilldownUnavailableReason?: (row: FocusProductRow) => string | undefined;
|
||
}) {
|
||
if (!rows.length) return null;
|
||
const table = (items: FocusProductRow[], offset = 0) => <div className="analysis-focus-table-wrap"><table className="analysis-focus-table">
|
||
<thead><tr><th scope="col" className="is-index">序号</th><th scope="col">产品规格</th><th scope="col" className="is-number">报废增量(kg)</th><th scope="col" className="is-number">合格率变化</th><th scope="col">入选依据</th></tr></thead>
|
||
<tbody>{items.map((row, index) => <tr key={`${offset + index}-${row.evidenceRefs.join('-')}`}>
|
||
<td className="is-index">{offset + index + 1}</td><th scope="row" className="analysis-focus-product" title={row.product}>{row.product}{onDrilldown && (drilldownUnavailableReason?.(row)
|
||
? <span className="analysis-product-unavailable">{drilldownUnavailableReason(row)}</span>
|
||
: <div className="analysis-product-actions">{(['defects', 'trend', 'records'] as ProductDrilldownView[]).map(view => <Button type="link" size="small" key={view} onClick={event => onDrilldown(row, view, event.currentTarget)}>{({ defects: '看缺陷', trend: '看趋势', records: '看来源明细' })[view]}</Button>)}</div>)}</th>
|
||
<td className="is-number">{row.scrapDelta}</td><td className={`is-number analysis-focus-rate ${row.rateChange.startsWith('下降') ? 'is-worse' : row.rateChange.startsWith('上升') ? 'is-better' : ''}`}><span>{row.rateLabel}</span>{row.rateChange}</td>
|
||
<td className="analysis-focus-basis">{row.basis}{row.evidenceRefs.map(ref => <a key={ref} className="analysis-evidence-ref" href={`#${evidencePrefix}${ref}`}>{evidenceLabels[ref] || '数据依据'}</a>)}</td>
|
||
</tr>)}</tbody>
|
||
</table></div>;
|
||
return <div className="analysis-focus-products">
|
||
{table(rows.slice(0, 5))}
|
||
{rows.length > 5 && <details className="analysis-narrative-details analysis-focus-more"><summary>其余重点产品({rows.length - 5})</summary>{table(rows.slice(5), 5)}</details>}
|
||
<details className="analysis-narrative-details analysis-focus-details"><summary>两期投入与阶段数据</summary>{rows.map((row, index) => <AiMarkdown key={index} className="analysis-focus-detail" content={row.detail} evidenceLabels={evidenceLabels} evidencePrefix={evidencePrefix} />)}</details>
|
||
</div>;
|
||
}
|
||
|
||
/** 聊天、HTML 和图片报告共用同一套章节与图表关联。 */
|
||
export function AnalysisNarrative({ answer, visuals, visualState, question, turnId, beforeExport, turn }: {
|
||
answer: string; visuals: unknown; visualState?: unknown; question?: string; turnId?: string; beforeExport?: () => Promise<void>; turn?: Record<string, unknown>;
|
||
}) {
|
||
const [drilldown, setDrilldown] = useState<ProductDrilldownSelection | null>(null);
|
||
const { model, reading, primaryVisuals } = useMemo(() => buildAnalysisReadingModel(answer, visuals, question, turn), [answer, visuals, question, turn]);
|
||
const appendix = useRef<HTMLDetailsElement>(null);
|
||
const turnStatus = String(turn?.status || '').toUpperCase();
|
||
const fallbackVisualState = ['FAILED', 'CANCELLED'].includes(turnStatus) ? undefined : visualState;
|
||
const prefix = `chat-${String(turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`;
|
||
const renderText = (content: string) => <AiMarkdown className="ai-answer" content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />;
|
||
useEffect(() => {
|
||
const reveal = () => {
|
||
if (model.evidence.some(item => `#${prefix}${item.ref}` === window.location.hash) && appendix.current) appendix.current.open = true;
|
||
};
|
||
reveal(); window.addEventListener('hashchange', reveal);
|
||
return () => window.removeEventListener('hashchange', reveal);
|
||
}, [model.evidence, prefix]);
|
||
const original = originalAnalysisBody(turn);
|
||
const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
|
||
const compact = (visual: AnalysisVisual) => !reading.hasAppendix && useCompactRateComparison(visual, question);
|
||
const comparisons = model.sections.flatMap(section => section.visuals).filter(compact);
|
||
const renderSection = (section: NarrativeSection) => {
|
||
const figures = section.visuals.filter(visual => !compact(visual) && !primaryIds.has(visual.id));
|
||
const hasFigures = figures.some(visual => visual.chartable);
|
||
const sectionComparisons = section.visuals.filter(compact);
|
||
if (primaryIds.size > 0 && !section.narrative && !section.tables.length && !section.focusProducts?.length && !figures.length && !sectionComparisons.length) return null;
|
||
return <section key={section.id} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||
{section.title && <h3 className="analysis-narrative-title">{section.title}</h3>}
|
||
{section.focusProducts && <FocusProductTable rows={section.focusProducts} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix}
|
||
drilldownUnavailableReason={turn ? row => resolveProductDrilldown(turn, row).reason : undefined}
|
||
onDrilldown={turn ? (row, view, trigger) => { const resolved = resolveProductDrilldown(turn, row); if (resolved.binding) setDrilldown({ row, view, trigger, binding: resolved.binding }); } : undefined} />}
|
||
{section.narrative && renderText(section.narrative)}
|
||
{!!sectionComparisons.length && <div className="analysis-rate-grid">{sectionComparisons.map(visual => <RateComparisonReadout key={visual.id} visual={visual} />)}</div>}
|
||
{!!figures.length && <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded />}
|
||
{!!section.tables.length && (hasFigures || sectionComparisons.length > 0
|
||
? <details className="analysis-narrative-details"><summary>查看本节数据与明细</summary>{section.tables.map((table, index) => <div key={index}>{renderText(table)}</div>)}</details>
|
||
: section.tables.map((table, index) => <div key={index}>{renderText(table)}</div>))}
|
||
</section>;
|
||
};
|
||
const fullContent = <>
|
||
{model.sections.map(renderSection)}
|
||
{!model.sections.some(section => section.visuals.length) && <AnalysisVisuals visuals={visuals} visualState={fallbackVisualState} beforeExport={beforeExport} />}
|
||
<NarrativeEvidence model={model} prefix={prefix} />
|
||
</>;
|
||
return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}>
|
||
{original ? <AnalysisOriginalContent answer={original.answer} visuals={model.sections.flatMap(section => section.visuals)} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : fullContent}
|
||
{turn && drilldown && <AnalysisProductDrilldown turn={turn} selection={drilldown} onClose={() => setDrilldown(null)} />}
|
||
</div>;
|
||
}
|