import { useEffect, useState } from 'react'; import { Alert, Button, Drawer, Empty, Segmented, Spin } from 'antd'; import { api } from './api'; import { AnalysisVisuals } from './AnalysisVisuals'; import { QualityTable } from './QualityTable'; import { authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot'; import { productDrilldownQuery, productTrendVisual, resolveProductDrilldown, type ProductDrilldownBinding, type ProductDrilldownView } from './analysisProductDrilldown'; import { publicJson } from './publicDataDisplay'; import type { AnalysisVisual } from './analysisVisualsModel'; import type { FocusProductRow } from './analysisReportModel'; import type { FineDefectTopResponse, RecordsResponse, Stage } from './types'; import './analysis-product-drilldown.css'; export interface ProductDrilldownSelection { binding: ProductDrilldownBinding; row: FocusProductRow; view: ProductDrilldownView; trigger: HTMLElement; } type Loaded = { kind: 'defects'; data: FineDefectTopResponse } | { kind: 'trend'; visuals: AnalysisVisual[] } | { kind: 'records'; data: RecordsResponse }; const titles = { defects: '看缺陷', trend: '看趋势', records: '看来源明细' }; const numberText = (value: number | null) => value === null ? '—' : value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); /** Keeps the report mounted and its scroll position intact while querying the * clicked row's immutable filters through the existing read-only APIs. */ export function AnalysisProductDrilldown({ turn, selection, onClose }: { turn: Record; selection: ProductDrilldownSelection; onClose: () => void }) { const { binding } = selection; const [open, setOpen] = useState(true); const [view, setView] = useState(selection.view); const [stage, setStage] = useState(binding.stages[0]); const [periodIndex, setPeriodIndex] = useState(0); const [page, setPage] = useState(1); const [revision, setRevision] = useState(0); const [loaded, setLoaded] = useState(null); const [error, setError] = useState(''); const [loading, setLoading] = useState(true); useEffect(() => { if (!open) return; const controller = new AbortController(); setLoading(true); setLoaded(null); setError(''); const load = async (): Promise => { // Permission and stored-answer changes are checked before every request, // including retries and paging; the backend also enforces current access. const snapshot = await api.analysisTurnSnapshot(binding.turnId); if (!['COMPLETED', 'PARTIAL', 'CANCELLED'].includes(String(snapshot.status || '').toUpperCase()) || reportSnapshotIdentity(snapshot) !== reportSnapshotIdentity(turn)) throw new Error('分析结果或访问权限已变化,请重新打开本轮分析。'); if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError'); const current = resolveProductDrilldown(snapshot, selection.row); if (!current.binding || JSON.stringify(current.binding) !== JSON.stringify(binding)) throw new Error('本条查询范围已变化,请关闭后重新打开。'); const query = productDrilldownQuery(binding, binding.periods[periodIndex].period); if (view === 'records') return { kind: 'records', data: await api.records({ ...query, stage, page, pageSize: 25 }, controller.signal) }; if (view === 'defects') { const { view: _view, trendGranularity: _granularity, ...filters } = query; const data = await api.fineDefectTop({ ...filters, stage, mode: 'top', dimension: 'defect', limit: 100 }, controller.signal); if (data.releaseId !== binding.query.releaseId) throw new Error('查询返回的数据版本已变化,请重新打开本轮分析。'); return { kind: 'defects', data }; } const snapshots = await Promise.all(binding.periods.map(period => api.metrics(productDrilldownQuery(binding, period.period), controller.signal))); return { kind: 'trend', visuals: productTrendVisual(binding, snapshots) }; }; load().then(value => { if (!controller.signal.aborted) setLoaded(value); }) .catch(value => { if (!controller.signal.aborted) setError(value instanceof Error ? value.message : '读取失败,请重试。'); }) .finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); }, [open, view, stage, periodIndex, page, revision, binding, turn, selection.row]); const restoreFocus = (visible: boolean) => { if (visible) return; if (selection.trigger.isConnected) selection.trigger.focus({ preventScroll: true }); onClose(); }; const sourceColumns = [ { title: '来源文件', dataIndex: 'sourceFile', width: 220 }, { title: '工作表', dataIndex: 'sheet', width: 130 }, { title: '原始行号', dataIndex: 'rowNumber', width: 90, align: 'center' as const }, { title: '产业部', dataIndex: 'department', width: 150 }, { title: '业务分组', dataIndex: 'group', width: 170 }, { title: '原始字段', key: 'raw', width: 220, render: (_: unknown, row: RecordsResponse['rows'][number]) =>
查看原始字段
{Object.entries(JSON.parse(publicJson(row.raw || {}) || '{}') as Record).map(([name, value]) =>
{name}
{value === null ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(value)}
)}
}, ]; return setOpen(false)} afterOpenChange={restoreFocus} width="min(1080px, 100vw)" destroyOnHidden>
({ label: titles[value], value }))} onChange={value => { setView(value as ProductDrilldownView); setPage(1); }} /> {view !== 'trend' && binding.stages.length > 1 && ({ label: value === 'black' ? '黑片' : '亮片', value }))} onChange={value => { setStage(value as Stage); setPage(1); }} />} {view !== 'trend' && binding.periods.length > 1 && ({ label: period.label, value: index }))} onChange={value => { setPeriodIndex(Number(value)); setPage(1); }} />}
{(view === 'trend' || binding.periods.length === 1 || binding.stages.length === 1) &&

{view === 'trend' ? [...binding.periods].reverse().map(period => period.label).join(' → ') : binding.periods.length === 1 ? binding.periods[0].label : ''}{binding.stages.length === 1 ? `${binding.periods.length === 1 || view === 'trend' ? ' · ' : ''}${binding.stages[0] === 'black' ? '黑片' : '亮片'}` : ''}

} {error ? setRevision(value => value + 1)}>重试} /> : loading ?
正在读取{titles[view].slice(1)}…
: loaded?.kind === 'trend' ? loaded.visuals.length ? authorizeAnalysisSnapshot(turn)} /> : : loaded?.kind === 'defects' ? <>

来源细分重量(kg),用于缺陷核查。

{loaded.data.sourceRows > 0 && loaded.data.coverage?.available !== false && loaded.data.rows.length ? : } {loaded.data.coverage?.categories?.some(category => category.reconciliationStatus !== 'RECONCILED') &&

部分来源细分尚不能与正式报废重量核对一致,不能据此计算总体贡献。

} : loaded?.kind === 'records' ? `共 ${total} 条`, onChange: next => setPage(next) }} /> : null}
; }