统一全系统资源加载、轻量趋势与缓存恢复

This commit is contained in:
2026-11-02 09:54:01 +08:00
parent 8b8f9b7728
commit b711327c8e
58 changed files with 3150 additions and 661 deletions
+58 -56
View File
@@ -1,9 +1,12 @@
import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope';
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
import { trendBarPalette } from './trendBarPalette';
import { getWorkspaceTheme } from './ui-themes';
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
import { BusinessValue } from './BusinessValue';
import { usePageCache } from './pageCache';
import { useDelayedIndicator } from './useDelayedBusy';
import { useResourceVisibility } from './useResourceVisibility';
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
@@ -153,6 +156,7 @@ function monthNumber(value: number | string): number | null {
return result >= 1 && result <= 12 ? result : null;
}
function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] {
if (granularity === 'year') return rows;
const byPeriod = new Map<string, TrendMetricRow>();
@@ -228,16 +232,7 @@ function escapeTooltipText(value: string): string {
}
export function queryFromLocation(search = window.location.search): Partial<QueryParams> {
const context = new URLSearchParams(search).get('context');
if (!context) return {};
try {
const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4));
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, character => character.charCodeAt(0)))) as { query?: unknown };
if (!parsed.query || typeof parsed.query !== 'object') return {};
const query = { ...(parsed.query as Partial<QueryParams>) };
delete query.releaseId;
return query;
} catch { return {}; }
return readQueryLocation(search);
}
function toApiParams(args: {
@@ -291,7 +286,7 @@ export default function QueryPage({ page, onUnauthorized }: {
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
}) {
const { message } = App.useApp();
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
const { active, initialSearch, refreshKey, onLocationChange, currentReleaseId } = usePageCache();
const baseView = SCOPE[page] || 'overall';
const [initialQuery] = useState(() => queryFromLocation(initialSearch));
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
@@ -340,6 +335,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const [error, setError] = useState('');
const [errorKey, setErrorKey] = useState('');
const [queryRevision, setQueryRevision] = useState(0);
const [trendRevision, setTrendRevision] = useState(0);
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
const [recordsOpen, setRecordsOpen] = useState(false);
const [recordStage, setRecordStage] = useState<Stage>('black');
@@ -361,8 +357,10 @@ export default function QueryPage({ page, onUnauthorized }: {
useEffect(() => {
if (!active) return;
let alive = true;
api.options().then(result => {
const controller = new AbortController();
api.options(controller.signal).then(result => {
if (!alive) return;
setOptions(result);
if (automaticPeriod.current) {
@@ -375,8 +373,8 @@ export default function QueryPage({ page, onUnauthorized }: {
if (onUnauthorized(errorValue)) return;
if (alive) setOptionsError(chooseError(errorValue));
}).finally(() => { if (alive) setOptionsLoading(false); });
return () => { alive = false; };
}, [onUnauthorized, queryRevision]);
return () => { alive = false; controller.abort(); };
}, [active, onUnauthorized, queryRevision]);
const allowedGroups = useMemo(() => {
const parents = new Set(department);
@@ -406,7 +404,7 @@ export default function QueryPage({ page, onUnauthorized }: {
if (product.length && !product.includes(exactProductSearch)) return [EMPTY_PRODUCT_SEARCH];
return [exactProductSearch];
}, [exactProductSearch, product]);
const queryParams = useMemo(() => toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity]);
const queryParams = useMemo(() => ({ ...toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), releaseId: initialQuery.releaseId || currentReleaseId || undefined }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity, initialQuery.releaseId, currentReleaseId]);
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
useEffect(() => {
@@ -420,7 +418,6 @@ export default function QueryPage({ page, onUnauthorized }: {
const queryBusy = loading || queryPending;
const metricKeyRef = useRef(metricKey);
metricKeyRef.current = metricKey;
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
const trendParams = useMemo<QueryParams>(() => {
const params = applyTrendObject(queryParams, trendObject, view);
delete params.month;
@@ -438,7 +435,7 @@ export default function QueryPage({ page, onUnauthorized }: {
if (!active) return;
const url = new URL(window.location.href);
if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || '')) return;
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryParams }));
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryForLocation(queryParams, initialQuery.releaseId) }));
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
@@ -448,7 +445,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [queryKey, active]);
useEffect(() => {
if (optionsLoading) return;
if (!active || optionsLoading || optionsError) return;
const controller = new AbortController();
setLoading(true);
setError('');
@@ -457,10 +454,6 @@ export default function QueryPage({ page, onUnauthorized }: {
if (controller.signal.aborted || metricKeyRef.current !== metricKey) return;
setData(result);
setDataKey(metricKey);
if (useSummaryTrend && trendKeyRef.current === trendKey) {
setTrendData(Array.isArray(result.trend) ? result.trend : []);
setTrendDataKey(trendKey);
}
setError('');
setErrorKey('');
}).catch(errorValue => {
@@ -470,9 +463,10 @@ export default function QueryPage({ page, onUnauthorized }: {
setErrorKey(metricKey);
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [metricKey, queryRevision, onUnauthorized, optionsLoading]);
}, [active, metricKey, queryRevision, onUnauthorized, optionsLoading, optionsError]);
useEffect(() => {
if (!active) return;
if (!trendObject || defectQueryKey === queryKey) {
setTrendObjectMetrics(null);
setTrendObjectMetricsLoading(false);
@@ -491,18 +485,14 @@ export default function QueryPage({ page, onUnauthorized }: {
})
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
return () => controller.abort();
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
}, [active, trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
useEffect(() => {
if (optionsLoading) return;
if (!active || optionsLoading || optionsError) return;
setTrendFailure(null);
if (useSummaryTrend) {
setTrendLoading(false);
return;
}
const controller = new AbortController();
setTrendLoading(true);
api.metrics(trendParams, controller.signal).then(result => {
api.trend(trendParams, controller.signal).then(result => {
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
setTrendData(Array.isArray(result.trend) ? result.trend : []);
setTrendDataKey(trendKey);
@@ -511,9 +501,10 @@ export default function QueryPage({ page, onUnauthorized }: {
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
return () => controller.abort();
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, optionsLoading]);
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
useEffect(() => {
if (!active || optionsLoading || optionsError) return;
let alive = true;
setTrendTarget(null);
setTrendTargetKey('');
@@ -532,14 +523,15 @@ export default function QueryPage({ page, onUnauthorized }: {
}
});
return () => { alive = false; };
}, [trendKey, queryRevision, onUnauthorized]);
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
const trendRefreshing = trendLoading || (useSummaryTrend && queryBusy) || (trendDataKey !== trendKey && !(useSummaryTrend ? currentMetricsError : currentTrendError));
const trendRefreshing = !currentTrendError && (trendLoading || trendDataKey !== trendKey);
const showTrendLoading = useDelayedIndicator(trendRefreshing);
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget } : null);
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget, query: trendParams } : null);
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
const drilledTrendData = useMemo(
@@ -585,7 +577,7 @@ export default function QueryPage({ page, onUnauthorized }: {
view: drilledProduct ? 'overall' as const : view,
layoutView: drilledProduct ? 'product' as const : view,
period: drilledProduct ? 'year' as const : period,
year, month, quarter, drilledProduct,
year, month, quarter, drilledProduct, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
} : null);
const tableRows = retainedTable?.rows || [];
const tablePeriod = retainedTable?.period || period;
@@ -755,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: {
</div>}
</section>
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{currentMetricsError && <Alert showIcon type="error" message={data ? "更新失败,当前显示上次结果" : "质量指标查询失败"} description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
@@ -776,12 +768,12 @@ export default function QueryPage({ page, onUnauthorized }: {
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject}
objects={trendOptions} scopeName={scopeName}
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
{currentTrendError && <Alert type="warning" showIcon message="趋势读取失败" description={currentTrendError} action={<Button onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
{trendMode === 'data'
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{trendRefreshing && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
</div>
</QueryTrendPanel>
@@ -792,7 +784,7 @@ export default function QueryPage({ page, onUnauthorized }: {
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length}
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
onExport={async () => {
setSummaryExporting(true);
try { await summaryExport.current?.exportExcel(); }
@@ -802,6 +794,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
<MetricTable
ref={summaryExport}
paginationScope={retainedTable?.paginationScope}
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
rows={tableRows}
view={tableView}
@@ -929,8 +922,11 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
...(query.includeUnassigned ? { includeUnassigned: true } : {}),
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]);
const fineQueryKey = JSON.stringify(fineQuery);
const visible = useResourceVisibility(container, active);
const showLoading = useDelayedIndicator(loading);
useEffect(() => {
if (!active || !visible) return;
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
const controller = new AbortController();
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
@@ -947,7 +943,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
})
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
}, [active, visible, releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
useEffect(() => {
const refresh = () => setThemeRevision(value => value + 1);
@@ -1049,7 +1045,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
}, [items, totalWeight, themeRevision, active]);
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{showLoading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
@@ -1078,10 +1074,10 @@ const totalWeightTitle = (label: string) => <span className="query-total-weight-
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
export function MetricTable({
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
}: {
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; paginationScope?: string; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
rateBasis: 'original' | 'withoutHeadquartersScrap';
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
@@ -1149,9 +1145,9 @@ export function MetricTable({
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
const effectivePage = pageSizeOverride == null ? currentPage : 1;
const effectivePage = pageSizeOverride == null ? Math.min(currentPage, Math.max(1, Math.ceil(rows.length / pageSize))) : 1;
const effectivePageSize = pageSizeOverride ?? pageSize;
useEffect(() => setCurrentPage(1), [rows]);
useEffect(() => setCurrentPage(1), [paginationScope ?? rows]);
const columnWidth = (column: ColumnsType<MetricRow>[number]): number => {
if ('children' in column && column.children?.length) {
return column.children.reduce((total, child) => total + columnWidth(child), 0);
@@ -1163,7 +1159,7 @@ export function MetricTable({
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
{pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
{pageSizeOverride == null && <MetricTablePagination current={effectivePage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
</div>;
}
@@ -1181,6 +1177,7 @@ function trendBarWidth(chartWidth: number, count: number): number {
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
const { active } = usePageCache();
const container = useRef<HTMLDivElement>(null);
const visible = useResourceVisibility(container, active);
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
const onMonthRef = useRef(onMonth);
const rowsRef = useRef(rows);
@@ -1228,7 +1225,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
}, []);
useEffect(() => {
if (!container.current || !hasRows || !active) return;
if (!container.current || !hasRows || !visible) return;
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
chart.current = instance;
graphicIds.current.clear();
@@ -1260,7 +1257,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
});
observer.observe(container.current);
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
}, [hasRows, refreshBarMasks, active]);
}, [hasRows, refreshBarMasks, visible]);
useEffect(() => {
const instance = chart.current;
@@ -1350,7 +1347,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
}
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
refreshBarMasks();
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active]);
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active, visible]);
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
@@ -1420,7 +1417,7 @@ export function RecordsDrawer({
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
}) {
const { message } = App.useApp();
const { refreshKey } = usePageCache();
const { active, refreshKey } = usePageCache();
const recordPages = useRef(new Map<string, RecordsResponse>());
const [page, setPage] = useState(1);
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
@@ -1445,14 +1442,16 @@ export function RecordsDrawer({
const result = response?.key === requestKey ? response.data : null;
const error = failure?.key === requestKey ? failure.message : '';
const fetching = loading || !result && !error;
const retainedResult = useRetainedResult(result);
const showRecordLoading = useDelayedIndicator(fetching && open);
useEffect(() => {
if (!open) return;
if (!open || !active) return;
const cached = recordPages.current.get(requestKey);
if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; }
const controller = new AbortController();
setLoading(true);
setResponse(null); setFailure(null);
setFailure(null);
api.records(requestParams, controller.signal).then(value => {
if (controller.signal.aborted) return;
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
@@ -1468,7 +1467,7 @@ export function RecordsDrawer({
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [open, requestKey, revision, onUnauthorized]);
}, [open, active, requestKey, revision, onUnauthorized]);
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
const exportRecords = async () => {
@@ -1536,7 +1535,7 @@ export function RecordsDrawer({
];
return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose>
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} disabled={fetching || !result || !!error} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
<div className="record-query-tools">
<label><span>字段检索</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></label>
<Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
@@ -1548,8 +1547,11 @@ export function RecordsDrawer({
]} onChange={value => { setSort(value); setPage(1); }} /></label>
<Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
</div>
{error && <Alert type="error" showIcon message="来源明细加载失败" description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
{fetching ? <div className="loading-panel"><Spin />正在读取来源行…</div> : result?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={result.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
{error && <Alert type="error" showIcon message={retainedResult ? "更新失败,当前显示上次结果" : "来源明细加载失败"} description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
{showRecordLoading && <div role="status">{retainedResult ? '正在更新,当前显示上次来源结果' : <><Spin size="small" />正在读取来源行…</>}</div>}
<div aria-busy={fetching} inert={!result || !!error}>
{retainedResult?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={retainedResult.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : !fetching && !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有来源记录" />}
</div>
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
</Drawer>;
}