1451 lines
98 KiB
TypeScript
1451 lines
98 KiB
TypeScript
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||
import * as echarts from 'echarts/core';
|
||
import { BarChart, LineChart } from 'echarts/charts';
|
||
import { GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from 'echarts/components';
|
||
import { SVGRenderer } from 'echarts/renderers';
|
||
import {
|
||
Alert,
|
||
App,
|
||
Button,
|
||
Checkbox,
|
||
Drawer,
|
||
Empty,
|
||
Input,
|
||
Modal,
|
||
Pagination,
|
||
Select,
|
||
Segmented,
|
||
Spin,
|
||
Table,
|
||
Tooltip,
|
||
} from 'antd';
|
||
import type { ColumnsType } from 'antd/es/table';
|
||
import { DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||
import type {
|
||
DefectMetric,
|
||
FineDefectTopResponse,
|
||
MetricRow,
|
||
MetricsResponse,
|
||
OptionsResponse,
|
||
PeriodKind,
|
||
QueryParams,
|
||
RecordExportParams,
|
||
RecordRow,
|
||
RecordsResponse,
|
||
Stage,
|
||
TrendMetricRow,
|
||
ViewKind,
|
||
} from './types';
|
||
import type { PageKey } from './QualityWorkspace';
|
||
import { M01Insights } from './AnalyticsCompletion';
|
||
import { readableSelectPopup } from './readableSelectPopup';
|
||
import { isInternalDataField } from './publicDataDisplay';
|
||
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||
import { defectWeightRate } from './trendMetrics';
|
||
import './query-motion.css';
|
||
import { ExtraQueryFilters } from './ExtraQueryFilters';
|
||
|
||
echarts.use([BarChart, LineChart, GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
|
||
|
||
const MONTHS = Array.from({ length: 12 }, (_, index) => `${String(index + 1).padStart(2, '0')}月`);
|
||
const TABLE_PAGE_SIZE = 20;
|
||
const SUMMARY_PAGE_SIZE = 15;
|
||
const SUMMARY_PAGE_SIZE_OPTIONS = ['10', '15', '20', '50', '100'];
|
||
const EMPTY_PRODUCT_SEARCH = '__codex_no_product_search_match__';
|
||
const SCOPE: Record<string, ViewKind> = { overall: 'overall', department: 'department', group: 'group', product: 'product' };
|
||
const SCOPE_NAMES: Record<string, string> = { overall: '总体', department: '产业部', group: '产业部-业务分组', product: '产品' };
|
||
const RETIRED_DEPARTMENTS = new Set(['美洲产业部', '欧洲产业部', '欧洲磁钢']);
|
||
const ORIGINAL_GROUP_ORDER = ['工业电机-VCM', '工业电机-美洲', '工业电机-欧洲', '工业电机-亚太', '工业电机-中国区', '汽车交通-国内', '汽车交通-海外', '消费电子-3C', '消费电子-电声', '消费电子-美洲'];
|
||
const groupRank = (value?: string | null) => { const index = ORIGINAL_GROUP_ORDER.indexOf(value || ''); return index < 0 ? ORIGINAL_GROUP_ORDER.length : index; };
|
||
|
||
function numberText(value: unknown, digits = 1): string {
|
||
return typeof value === 'number' && Number.isFinite(value)
|
||
? value.toLocaleString('zh-CN', { minimumFractionDigits: digits, maximumFractionDigits: digits })
|
||
: '—';
|
||
}
|
||
|
||
function rateText(value: number | null | undefined): string {
|
||
return typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||
}
|
||
|
||
function rateNumber(value: number | null | undefined): number | null {
|
||
return typeof value === 'number' && Number.isFinite(value) ? value * 100 : null;
|
||
}
|
||
|
||
const SYSTEM_SOURCE_VERSION_KEYS = new Set([
|
||
'sourcerevisionid', 'targetrevisionid', 'expectedrevisionid', 'currentrevisionid', 'candidaterevisionid', 'baserevisionid',
|
||
]);
|
||
const SYSTEM_SOURCE_VERSION_LABELS = new Set([
|
||
'数据版本', '数据版本号', '发布版本', '发布版本号', '规则版本', '规则版本号', '映射版本', '映射版本号',
|
||
]);
|
||
function isSystemVersionField(key: string): boolean {
|
||
const normalized = key.replace(/[^a-z0-9]/gi, '').toLowerCase();
|
||
return isInternalDataField(key) || SYSTEM_SOURCE_VERSION_KEYS.has(normalized) || SYSTEM_SOURCE_VERSION_LABELS.has(key.trim());
|
||
}
|
||
|
||
function withoutSystemVersionFields(value: unknown): unknown {
|
||
if (Array.isArray(value)) return value.map(withoutSystemVersionFields);
|
||
if (!value || typeof value !== 'object') return value;
|
||
return Object.fromEntries(Object.entries(value as Record<string, unknown>)
|
||
.filter(([key]) => !isSystemVersionField(key))
|
||
.map(([key, child]) => [key, withoutSystemVersionFields(child)]));
|
||
}
|
||
|
||
function hasStageRows(row: MetricRow | undefined, stage: Stage): boolean {
|
||
return (row?.coverage?.[stage === 'black' ? 'blackRows' : 'brightRows'] ?? 0) > 0;
|
||
}
|
||
|
||
function hasValidRateDenominator(row: MetricRow | undefined, stage: Stage): boolean {
|
||
if (!row) return false;
|
||
if (stage === 'black') return row.black.totalWeight != null && row.black.totalWeight !== 0;
|
||
const qualified = row.bright.qualifiedWeight;
|
||
const scrap = row.bright.scrapWeight;
|
||
return (qualified != null || scrap != null) && (qualified ?? 0) + (scrap ?? 0) !== 0;
|
||
}
|
||
|
||
function visibleStageRate(row: MetricRow | undefined, stage: Stage, rateBasis: 'original' | 'withoutHeadquartersScrap' = 'original'): number | null {
|
||
if (!hasStageRows(row, stage)) return null;
|
||
if (stage === 'bright' && rateBasis === 'withoutHeadquartersScrap') {
|
||
return (row?.bright as MetricRow['bright'] & { rateWithoutHeadquartersScrap?: number | null })?.rateWithoutHeadquartersScrap ?? null;
|
||
}
|
||
return row?.[stage]?.rate ?? null;
|
||
}
|
||
|
||
function visibleCompositeRate(row: MetricRow | undefined, rateBasis: 'original' | 'withoutHeadquartersScrap' = 'original'): number | null {
|
||
if (!(hasStageRows(row, 'black') || hasStageRows(row, 'bright'))) return null;
|
||
return rateBasis === 'withoutHeadquartersScrap'
|
||
? (row as (MetricRow & { compositeRateWithoutHeadquartersScrap?: number | null }) | undefined)?.compositeRateWithoutHeadquartersScrap ?? null
|
||
: row?.compositeRate ?? null;
|
||
}
|
||
|
||
function monthNumber(value: number | string): number | null {
|
||
if (typeof value === 'number' && value >= 1 && value <= 12) return value;
|
||
const raw = String(value).trim();
|
||
const yearMonth = raw.match(/^\d{4}[-/]\s*(\d{1,2})$/);
|
||
const match = yearMonth || raw.match(/\d{1,2}/);
|
||
if (!match) return null;
|
||
const result = Number(match[1] ?? match[0]);
|
||
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>();
|
||
for (const row of rows) {
|
||
const key = String(row.period ?? row.month);
|
||
const normalized = granularity === 'quarter'
|
||
? key.match(/^(\d{4})-Q([1-4])$/)?.[0]
|
||
: key.match(/^(\d{4})-(\d{1,2})$/)?.slice(1);
|
||
const periodKey = Array.isArray(normalized) ? `${normalized[0]}-${String(Number(normalized[1])).padStart(2, '0')}` : normalized;
|
||
if (periodKey?.startsWith(`${year}-`)) byPeriod.set(periodKey, row);
|
||
}
|
||
return Array.from({ length: granularity === 'quarter' ? 4 : 12 }, (_, index) => {
|
||
const number = index + 1;
|
||
const key = granularity === 'quarter' ? `${year}-Q${number}` : `${year}-${String(number).padStart(2, '0')}`;
|
||
const label = granularity === 'quarter' ? `第${number}季度` : MONTHS[index];
|
||
if (byPeriod.has(key)) return { ...byPeriod.get(key)!, periodLabel: label };
|
||
const empty = blankMonthRow(year, granularity === 'quarter' ? number * 3 : number);
|
||
return { ...empty, key: `empty-${key}`, month: key, period: key,
|
||
periodLabel: label, granularity };
|
||
});
|
||
}
|
||
|
||
function blankMonthRow(year: number, month: number): TrendMetricRow {
|
||
const current = new Date();
|
||
const monthStatus: TrendMetricRow['monthStatus'] = year > current.getFullYear() || (year === current.getFullYear() && month > current.getMonth() + 1)
|
||
? 'future'
|
||
: year === current.getFullYear() && month === current.getMonth() + 1
|
||
? 'in_progress'
|
||
: 'unavailable';
|
||
const emptyStage = { qualifiedWeight: null, scrapWeight: null, totalWeight: null, rate: null, defects: [] };
|
||
return {
|
||
key: `empty-month-${year}-${month}`, label: MONTHS[month - 1], department: null, group: null, product: null,
|
||
compositeRate: null, black: { ...emptyStage, defects: [] }, bright: { ...emptyStage, defects: [] },
|
||
coverage: { blackRows: 0, brightRows: 0 }, month, monthStatus, noData: true,
|
||
};
|
||
}
|
||
|
||
function objectLabel(row: MetricRow, view: ViewKind): string {
|
||
if (view === 'overall') return row.label;
|
||
if (view === 'department') return row.department || row.label;
|
||
if (view === 'group') return row.group || row.label;
|
||
if (view === 'projectGroup') return row.projectGroup || row.label;
|
||
return row.product || row.label;
|
||
}
|
||
|
||
function stageValue(row: MetricRow | undefined, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight'): number | null {
|
||
return row?.[stage]?.[field] ?? null;
|
||
}
|
||
|
||
function defectList(row: MetricRow | undefined, stage: Stage): DefectMetric[] {
|
||
return row?.[stage]?.defects || [];
|
||
}
|
||
|
||
function defectsFor(rows: MetricRow[], stage: Stage): string[] {
|
||
return Array.from(new Set(rows.flatMap(row => defectList(row, stage).map(item => item.name))));
|
||
}
|
||
|
||
interface ChartTooltipParam {
|
||
name?: string | number;
|
||
axisValue?: string | number;
|
||
dataIndex?: number;
|
||
seriesName?: string;
|
||
marker?: string;
|
||
value?: unknown;
|
||
}
|
||
|
||
function chooseError(error: unknown): string {
|
||
return error instanceof Error ? error.message : '服务请求失败';
|
||
}
|
||
|
||
function escapeTooltipText(value: string): string {
|
||
return value.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]!);
|
||
}
|
||
|
||
function queryFromLocation(): Partial<QueryParams> {
|
||
const context = new URLSearchParams(window.location.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 {}; }
|
||
}
|
||
|
||
function toApiParams(args: {
|
||
year: number;
|
||
period: PeriodKind;
|
||
month: number;
|
||
quarter: number;
|
||
department?: string[];
|
||
group?: string[];
|
||
product?: string[];
|
||
productSearch?: string;
|
||
projectGroup?: string[];
|
||
extraFilters?: Record<string, string[]>;
|
||
trendGranularity: 'month' | 'quarter' | 'year';
|
||
view: ViewKind;
|
||
includeUnassigned: boolean;
|
||
}): QueryParams {
|
||
return {
|
||
year: args.year,
|
||
...(args.extraFilters && Object.keys(args.extraFilters).length ? { extraFilters: args.extraFilters } : {}),
|
||
...(args.period === 'month' ? { month: args.month } : {}),
|
||
...(args.period === 'quarter' ? { quarter: args.quarter } : {}),
|
||
...(encodeQueryValueList(args.department) ? { department: encodeQueryValueList(args.department) } : {}),
|
||
...(encodeQueryValueList(args.group) ? { group: encodeQueryValueList(args.group) } : {}),
|
||
...(encodeQueryValueList(args.product) ? { product: encodeQueryValueList(args.product) } : {}),
|
||
...(args.productSearch?.trim() ? { productSearch: args.productSearch.trim() } : {}),
|
||
...(encodeQueryValueList(args.projectGroup) ? { projectGroup: encodeQueryValueList(args.projectGroup) } : {}),
|
||
...(args.includeUnassigned ? { includeUnassigned: true } : {}),
|
||
trendGranularity: args.trendGranularity,
|
||
view: args.view,
|
||
};
|
||
}
|
||
|
||
function applyTrendObject(query: QueryParams, trendObject: string, view: ViewKind): QueryParams {
|
||
if (!trendObject) return query;
|
||
const params: QueryParams = { ...query };
|
||
if (view === 'department') params.department = trendObject;
|
||
if (view === 'group') params.group = trendObject;
|
||
if (view === 'product') {
|
||
const selectedProducts = decodeQueryValueList(params.product);
|
||
params.product = selectedProducts.length === 0 || selectedProducts.includes(trendObject) ? trendObject : EMPTY_PRODUCT_SEARCH;
|
||
}
|
||
if (view === 'projectGroup') params.projectGroup = trendObject;
|
||
return params;
|
||
}
|
||
|
||
type TopResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||
export default function QueryPage({ page, onUnauthorized }: {
|
||
page: PageKey;
|
||
onUnauthorized: (error: unknown) => boolean;
|
||
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
|
||
}) {
|
||
const { message } = App.useApp();
|
||
const baseView = SCOPE[page] || 'overall';
|
||
const initialQuery = queryFromLocation();
|
||
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
|
||
const routeViewOverride = initialQuery.view && initialQuery.view !== baseView ? initialQuery.view : undefined;
|
||
const viewOverride = routeViewOverride || (viewOverrideState?.page === page ? viewOverrideState.view : undefined);
|
||
const setViewOverride = (next?: ViewKind) => setViewOverrideState(next ? { page, view: next } : undefined);
|
||
const view = viewOverride || baseView;
|
||
const scopeName = viewOverride ? ({ overall: '总体', department: '产业部', group: '产业部-业务分组', product: '产品', projectGroup: '项目组' } as Record<ViewKind, string>)[viewOverride] : SCOPE_NAMES[page] || '总体';
|
||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||
const [optionsError, setOptionsError] = useState('');
|
||
const [optionsLoading, setOptionsLoading] = useState(true);
|
||
const defaultMonth = previousCompleteMonth();
|
||
const defaultQuarter = previousCompleteQuarter();
|
||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : page === 'overall' ? 'year' : 'month');
|
||
const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear()));
|
||
const [month, setMonth] = useState(initialQuery.month || defaultMonth.month);
|
||
const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter);
|
||
const [department, setDepartment] = useState<string[]>(() => decodeQueryValueList(initialQuery.department));
|
||
const [group, setGroup] = useState<string[]>(() => decodeQueryValueList(initialQuery.group));
|
||
const [product, setProduct] = useState<string[]>(() => decodeQueryValueList(initialQuery.product));
|
||
const [projectGroup, setProjectGroup] = useState<string[]>(() => decodeQueryValueList(initialQuery.projectGroup));
|
||
const [extraFilters, setExtraFilters] = useState<Record<string,string[]>>(initialQuery.extraFilters || {});
|
||
const [includeUnassigned, setIncludeUnassigned] = useState(initialQuery.includeUnassigned === true);
|
||
const [trendGranularity, setTrendGranularity] = useState<'month' | 'quarter' | 'year'>(initialQuery.trendGranularity || (initialQuery.quarter ? 'quarter' : 'month'));
|
||
const [search, setSearch] = useState('');
|
||
const [appliedSearch, setAppliedSearch] = useState('');
|
||
const [fullFields, setFullFields] = useState(false);
|
||
const [data, setData] = useState<MetricsResponse | null>(null);
|
||
const [dataKey, setDataKey] = useState('');
|
||
const [trendData, setTrendData] = useState<TrendMetricRow[]>([]);
|
||
const [trendDataKey, setTrendDataKey] = useState('');
|
||
const [trendTarget, setTrendTarget] = useState<number | null>(null);
|
||
const [trendTargetKey, setTrendTargetKey] = useState('');
|
||
const [trendObject, setTrendObject] = useState('');
|
||
const [drilledProduct, setDrilledProduct] = useState('');
|
||
const [trendObjectMetrics, setTrendObjectMetrics] = useState<{ key: string; data: MetricsResponse } | null>(null);
|
||
const [trendObjectMetricsLoading, setTrendObjectMetricsLoading] = useState(false);
|
||
const [trendObjectMetricsError, setTrendObjectMetricsError] = useState('');
|
||
const [trendMode, setTrendMode] = useState<'production' | 'defects' | 'data'>('production');
|
||
const [trendStage, setTrendStage] = useState<Stage>('bright');
|
||
const [rateBasis, setRateBasis] = useState<'original' | 'withoutHeadquartersScrap'>('original');
|
||
const [loading, setLoading] = useState(false);
|
||
const [trendLoading, setTrendLoading] = useState(false);
|
||
const [error, setError] = useState('');
|
||
const [errorKey, setErrorKey] = useState('');
|
||
const [queryRevision, setQueryRevision] = useState(0);
|
||
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
|
||
const [recordsOpen, setRecordsOpen] = useState(false);
|
||
const [recordStage, setRecordStage] = useState<Stage>('black');
|
||
const [recordMonth, setRecordMonth] = useState<number>();
|
||
const [basisOpen, setBasisOpen] = useState(false);
|
||
const trendAnchorTop = useRef<number | null>(null);
|
||
|
||
useEffect(() => {
|
||
const timer = window.setTimeout(() => setAppliedSearch(search), 300);
|
||
return () => window.clearTimeout(timer);
|
||
}, [search]);
|
||
|
||
useEffect(() => {
|
||
setTrendObject('');
|
||
setDrilledProduct('');
|
||
setSearch('');
|
||
setAppliedSearch('');
|
||
setViewOverrideState(undefined);
|
||
setRecordsOpen(false);
|
||
setSelectedRecord(null);
|
||
}, [page]);
|
||
|
||
useEffect(() => {
|
||
let alive = true;
|
||
api.options().then(result => {
|
||
if (!alive) return;
|
||
setOptions(result);
|
||
const yearOptions = (result.years || []).map(value => Number(String(value).match(/\d{4}/)?.[0])).filter(Number.isFinite);
|
||
if (yearOptions.length && !yearOptions.includes(year)) setYear(Math.max(...yearOptions));
|
||
setOptionsError('');
|
||
}).catch(errorValue => {
|
||
if (onUnauthorized(errorValue)) return;
|
||
if (alive) setOptionsError(chooseError(errorValue));
|
||
}).finally(() => { if (alive) setOptionsLoading(false); });
|
||
return () => { alive = false; };
|
||
}, [onUnauthorized]);
|
||
|
||
const allowedGroups = useMemo(() => {
|
||
const parents = new Set(department);
|
||
return (options?.groups || []).filter(name => !parents.size || parents.has(options?.groupDepartments?.[name] || ''));
|
||
}, [department, options]);
|
||
const allowedGroupSet = useMemo(() => new Set(allowedGroups), [allowedGroups]);
|
||
|
||
useEffect(() => {
|
||
if (!options || !department.length) return;
|
||
const activeDepartments = department.filter(name => !RETIRED_DEPARTMENTS.has(name));
|
||
if (activeDepartments.length !== department.length) {
|
||
setDepartment(activeDepartments);
|
||
setGroup([]);
|
||
setProduct([]);
|
||
return;
|
||
}
|
||
const next = group.filter(name => allowedGroupSet.has(name));
|
||
if (next.length !== group.length) { setGroup(next); setProduct([]); }
|
||
}, [options, department, group, allowedGroupSet]);
|
||
|
||
const exactProductSearch = useMemo(() => {
|
||
const term = view === 'product' ? appliedSearch.trim().toLocaleLowerCase() : '';
|
||
return term ? (options?.products || []).find(name => name.trim().toLocaleLowerCase() === term) || '' : '';
|
||
}, [view, appliedSearch, options]);
|
||
const productFilterForQuery = useMemo(() => {
|
||
if (!exactProductSearch) return product;
|
||
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 queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
|
||
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
|
||
useEffect(() => {
|
||
setDrilledProduct('');
|
||
}, [drilldownContextKey]);
|
||
const metricParams = useMemo<QueryParams>(() => ({ ...queryParams, trendGranularity: 'month' }), [queryParams]);
|
||
const metricKey = useMemo(() => JSON.stringify(metricParams), [metricParams]);
|
||
const currentMetricsData = dataKey === metricKey ? data : null;
|
||
const currentMetricsError = errorKey === metricKey ? error : '';
|
||
const queryPending = !currentMetricsData && !currentMetricsError;
|
||
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;
|
||
delete params.quarter;
|
||
if (trendGranularity === 'year') Reflect.deleteProperty(params, 'year');
|
||
return params;
|
||
}, [queryKey, trendObject, trendGranularity, view]);
|
||
const defectQueryParams = useMemo<QueryParams>(() => applyTrendObject(queryParams, trendObject, view), [queryKey, trendObject, view]);
|
||
const defectQueryKey = JSON.stringify(defectQueryParams);
|
||
const trendKey = JSON.stringify(trendParams);
|
||
const trendKeyRef = useRef(trendKey);
|
||
trendKeyRef.current = trendKey;
|
||
|
||
useEffect(() => {
|
||
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 }));
|
||
let binary = '';
|
||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||
url.searchParams.set('context', context);
|
||
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);
|
||
}, [queryKey]);
|
||
|
||
useEffect(() => {
|
||
const controller = new AbortController();
|
||
setLoading(true);
|
||
setError('');
|
||
setErrorKey('');
|
||
api.metrics(metricParams, controller.signal).then(result => {
|
||
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 => {
|
||
if (controller.signal.aborted) return;
|
||
if (onUnauthorized(errorValue)) return;
|
||
setError(chooseError(errorValue));
|
||
setErrorKey(metricKey);
|
||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||
return () => controller.abort();
|
||
}, [metricKey, queryRevision, onUnauthorized]);
|
||
|
||
useEffect(() => {
|
||
if (!trendObject || defectQueryKey === queryKey) {
|
||
setTrendObjectMetrics(null);
|
||
setTrendObjectMetricsLoading(false);
|
||
setTrendObjectMetricsError('');
|
||
return;
|
||
}
|
||
const controller = new AbortController();
|
||
setTrendObjectMetrics(null);
|
||
setTrendObjectMetricsLoading(true);
|
||
setTrendObjectMetricsError('');
|
||
api.metrics({ ...defectQueryParams, trendGranularity: 'month' }, controller.signal)
|
||
.then(result => setTrendObjectMetrics({ key: defectQueryKey, data: result }))
|
||
.catch(errorValue => {
|
||
if (controller.signal.aborted) return;
|
||
if (!onUnauthorized(errorValue)) setTrendObjectMetricsError(chooseError(errorValue));
|
||
})
|
||
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
|
||
return () => controller.abort();
|
||
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
||
|
||
useEffect(() => {
|
||
if (useSummaryTrend) {
|
||
setTrendLoading(false);
|
||
return;
|
||
}
|
||
const controller = new AbortController();
|
||
setTrendLoading(true);
|
||
api.metrics(trendParams, controller.signal).then(result => {
|
||
if (trendKeyRef.current !== trendKey) return;
|
||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
||
setTrendDataKey(trendKey);
|
||
})
|
||
.catch(errorValue => {
|
||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(`趋势加载失败:${chooseError(errorValue)}`);
|
||
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
||
return () => controller.abort();
|
||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message]);
|
||
|
||
useEffect(() => {
|
||
let alive = true;
|
||
setTrendTarget(null);
|
||
setTrendTargetKey('');
|
||
const targetContext = Object.fromEntries(Object.entries(trendParams).filter(([key]) => key !== 'view' && key !== 'trendGranularity'));
|
||
api.analyticsTarget({ ...targetContext, metric: 'COMPOSITE_RATE' }).then(result => {
|
||
const target = result.target && typeof result.target === 'object' ? result.target as Record<string, unknown> : {};
|
||
const value = typeof target.value === 'number' ? target.value : target.targetRate;
|
||
if (!alive) return;
|
||
setTrendTarget(result.status === 'CONFIGURED' && typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1 ? value * 100 : null);
|
||
setTrendTargetKey(trendKey);
|
||
}).catch(errorValue => {
|
||
if (!alive) return;
|
||
if (!onUnauthorized(errorValue)) {
|
||
setTrendTarget(null);
|
||
setTrendTargetKey(trendKey);
|
||
}
|
||
});
|
||
return () => { alive = false; };
|
||
}, [trendKey, onUnauthorized]);
|
||
|
||
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
|
||
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
|
||
const drilledTrendData = useMemo(
|
||
() => trendDataKey === trendKey ? visibleTrendData : fullYearTrend([], year, 'month'),
|
||
[trendDataKey, trendKey, visibleTrendData, year],
|
||
);
|
||
const selectedTrendPeriod = trendGranularity === 'month' && period === 'month'
|
||
? `${year}-${String(month).padStart(2, '0')}`
|
||
: trendGranularity === 'quarter' && period === 'quarter' ? `${year}-Q${quarter}` : undefined;
|
||
|
||
const visibleRows = useMemo(() => {
|
||
const rawRows: MetricRow[] = page === 'overall' && period === 'year'
|
||
? (() => {
|
||
const byMonth = new Map<number, TrendMetricRow>();
|
||
for (const item of currentMetricsData?.trend || []) { const parsed = monthNumber(item.month); if (parsed) byMonth.set(parsed, item); }
|
||
return Array.from({ length: 12 }, (_, index) => byMonth.get(index + 1) || blankMonthRow(year, index + 1));
|
||
})()
|
||
: page === 'overall' && currentMetricsData
|
||
? currentMetricsData.rows.length ? currentMetricsData.rows : [currentMetricsData.summary]
|
||
: currentMetricsData?.rows || [];
|
||
const scopedRows = view === 'department'
|
||
? rawRows.filter(row => !RETIRED_DEPARTMENTS.has(row.department || row.label))
|
||
: view === 'group' && department.length
|
||
? rawRows.filter(row => !!row.group && allowedGroupSet.has(row.group)) : rawRows;
|
||
const orderedRows = view === 'group'
|
||
? [...scopedRows].sort((a, b) => groupRank(a.group) - groupRank(b.group))
|
||
: view === 'product'
|
||
? [...scopedRows].sort((a, b) => {
|
||
const aWeight = a.bright.qualifiedWeight;
|
||
const bWeight = b.bright.qualifiedWeight;
|
||
return (typeof bWeight === 'number' && Number.isFinite(bWeight) ? bWeight : -Infinity)
|
||
- (typeof aWeight === 'number' && Number.isFinite(aWeight) ? aWeight : -Infinity) || 0;
|
||
})
|
||
: scopedRows;
|
||
if (!appliedSearch.trim()) return orderedRows;
|
||
const term = appliedSearch.trim().toLocaleLowerCase();
|
||
return orderedRows.filter(row => [row.label, row.department, row.group, row.product, row.projectGroup].filter(Boolean).join(' ').toLocaleLowerCase().includes(term));
|
||
}, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]);
|
||
|
||
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number) => {
|
||
setSelectedRecord(row);
|
||
setRecordStage(stage);
|
||
setRecordMonth(selectedMonth);
|
||
setRecordsOpen(true);
|
||
}, []);
|
||
const captureTrendAnchor = useCallback(() => {
|
||
trendAnchorTop.current = document.getElementById('monthly-trend')?.getBoundingClientRect().top ?? null;
|
||
}, []);
|
||
const selectTrendPeriod = useCallback((value: number | string) => {
|
||
const raw = String(value);
|
||
const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/);
|
||
const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||
const yearMatch = raw.match(/^(\d{4})$/);
|
||
if (quarterMatch) {
|
||
if (period === 'quarter' && year === Number(quarterMatch[1]) && quarter === Number(quarterMatch[2])) {
|
||
captureTrendAnchor(); setPeriod('year'); return;
|
||
}
|
||
if (period !== 'quarter' || year !== Number(quarterMatch[1]) || quarter !== Number(quarterMatch[2])) captureTrendAnchor();
|
||
setYear(Number(quarterMatch[1])); setQuarter(Number(quarterMatch[2])); setPeriod('quarter');
|
||
} else if (yearMonth) {
|
||
if (period === 'month' && year === Number(yearMonth[1]) && month === Number(yearMonth[2])) {
|
||
captureTrendAnchor(); setPeriod('year'); return;
|
||
}
|
||
if (period !== 'month' || year !== Number(yearMonth[1]) || month !== Number(yearMonth[2])) captureTrendAnchor();
|
||
setYear(Number(yearMonth[1])); setMonth(Number(yearMonth[2])); setPeriod('month');
|
||
} else if (yearMatch) {
|
||
if (period !== 'year' || year !== Number(yearMatch[1])) captureTrendAnchor();
|
||
setYear(Number(yearMatch[1])); setPeriod('year');
|
||
} else {
|
||
const selected = monthNumber(value);
|
||
if (selected) {
|
||
if (period === 'month' && month === selected) {
|
||
captureTrendAnchor(); setPeriod('year'); return;
|
||
}
|
||
if (period !== 'month' || month !== selected) captureTrendAnchor();
|
||
setPeriod('month'); setMonth(selected);
|
||
}
|
||
}
|
||
}, [period, year, month, quarter, captureTrendAnchor]);
|
||
|
||
useLayoutEffect(() => {
|
||
if (trendAnchorTop.current == null) return;
|
||
const nextTop = document.getElementById('monthly-trend')?.getBoundingClientRect().top;
|
||
if (nextTop != null) window.scrollBy(0, nextTop - trendAnchorTop.current);
|
||
trendAnchorTop.current = null;
|
||
}, [period, year, month, quarter]);
|
||
|
||
const years = (options?.years || []).map(value => { const numeric = Number(String(value).match(/\d{4}/)?.[0]); return { label: `${numeric}年`, value: numeric }; }).filter(item => Number.isFinite(item.value));
|
||
const filterSelect = (label: string, value: string[], choices: string[] | undefined, change: (value: string[]) => void, allowUnassigned = true) => (
|
||
<label className="query-field query-primary-field" key={label}>
|
||
<span>{label}</span>
|
||
<Select
|
||
maxTagCount="responsive"
|
||
mode="multiple"
|
||
allowClear
|
||
showSearch
|
||
optionFilterProp="label"
|
||
{...readableSelectPopup}
|
||
placeholder="全部"
|
||
value={value}
|
||
options={[...(label === '业务分组' ? [...(choices || [])].sort((a, b) => groupRank(a) - groupRank(b)) : choices || []).map(item => ({ label: item, value: item })), ...(allowUnassigned ? [{ label: '未分类', value: '__UNASSIGNED__' }] : [])]}
|
||
onChange={change}
|
||
aria-label={label}
|
||
/>
|
||
</label>
|
||
);
|
||
|
||
const activeDefectData = trendObject
|
||
? defectQueryKey === queryKey ? currentMetricsData : trendObjectMetrics?.key === defectQueryKey ? trendObjectMetrics.data : null
|
||
: currentMetricsData;
|
||
const rowForSummary = currentMetricsData?.summary;
|
||
const rawFormulaDescriptions = currentMetricsData?.context.metricFormulaDescriptions;
|
||
const formulaDescriptions = rawFormulaDescriptions && typeof rawFormulaDescriptions === 'object' && !Array.isArray(rawFormulaDescriptions) ? rawFormulaDescriptions as Record<string, unknown> : {};
|
||
const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap'];
|
||
const brightFormula = formulaDescriptions[rateBasis === 'original' ? 'brightRate' : 'brightRateWithoutHeadquartersScrap'];
|
||
const formulaText = (description: unknown) => typeof description === 'string' && description.trim() ? description : '当前指标服务未提供公式说明';
|
||
const blackDefectItems = activeDefectData?.defects?.black || [];
|
||
const brightDefectItems = activeDefectData?.defects?.bright || [];
|
||
const organizationPaths = options?.organizationPaths || [];
|
||
const organizationPathOptions = useMemo(() => {
|
||
const departments = new Set(department);
|
||
const groups = new Set(group);
|
||
const scoped = organizationPaths.filter(path =>
|
||
(!departments.size || (departments.has(path.department || '__UNASSIGNED__') && allowedGroupSet.has(path.group || '')
|
||
&& options?.groupDepartments?.[path.group || ''] === path.department))
|
||
&& (!groups.size || groups.has(path.group || '__UNASSIGNED__')));
|
||
return {
|
||
products: [...new Set(scoped.map(path => path.product).filter((value): value is string => !!value))],
|
||
};
|
||
}, [organizationPaths, department, group, allowedGroupSet, options]);
|
||
const trendOptions = useMemo(() => {
|
||
const base = view === 'department' ? options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)) : view === 'group' ? allowedGroups : view === 'product'
|
||
? department.length || group.length ? organizationPathOptions.products : options?.products : [];
|
||
return (base || []).map(value => ({ label: value, value }));
|
||
}, [view, options, allowedGroups, department, group, organizationPathOptions]);
|
||
useEffect(() => {
|
||
if (options && trendObject && !trendOptions.some(item => item.value === trendObject)) {
|
||
setTrendObject('');
|
||
if (search.trim().toLocaleLowerCase() === trendObject.toLocaleLowerCase()) setSearch('');
|
||
}
|
||
}, [options, trendOptions, trendObject, search]);
|
||
const setSynchronizedSearch = (value: string) => {
|
||
setSearch(value);
|
||
const normalized = value.trim().toLocaleLowerCase();
|
||
const exactOption = normalized ? trendOptions.find(item => item.value.trim().toLocaleLowerCase() === normalized) : undefined;
|
||
setTrendObject(exactOption?.value || '');
|
||
};
|
||
const setSynchronizedTrendObject = (value?: string) => {
|
||
const selected = value || '';
|
||
setTrendObject(selected);
|
||
setSearch(selected);
|
||
};
|
||
const organizationSummary = [
|
||
department.length ? `产业部:${department.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
|
||
group.length ? `业务分组:${group.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
|
||
product.length ? `产品:${product.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
|
||
].filter(Boolean);
|
||
|
||
return (
|
||
<div className="query-page">
|
||
{optionsError && <Alert showIcon type="error" message="查询选项加载失败" description={optionsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => { setOptionsLoading(true); api.options().then(result => { setOptions(result); setOptionsError(''); }).catch(e => { if (!onUnauthorized(e)) setOptionsError(chooseError(e)); }).finally(() => setOptionsLoading(false)); }}>重试</Button>} />}
|
||
<section className="query-toolbar panel" aria-label="查询条件">
|
||
<Segmented
|
||
value={period}
|
||
options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]}
|
||
onChange={value => {
|
||
const nextPeriod = value as PeriodKind;
|
||
setPeriod(nextPeriod);
|
||
setTrendGranularity(nextPeriod === 'quarter' ? 'quarter' : 'month');
|
||
if (nextPeriod === 'month') {
|
||
const previous = previousCompleteMonth();
|
||
setYear(previous.year);
|
||
setMonth(previous.month);
|
||
} else if (nextPeriod === 'quarter') {
|
||
const previous = previousCompleteQuarter();
|
||
setYear(previous.year);
|
||
setQuarter(previous.quarter);
|
||
}
|
||
}}
|
||
aria-label="统计周期"
|
||
/>
|
||
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={setYear} loading={optionsLoading} /></label>
|
||
{period === 'month' && <label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={setMonth} /></label>}
|
||
{period === 'quarter' && <label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={setQuarter} /></label>}
|
||
{filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })}
|
||
{filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)}
|
||
{filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)}
|
||
|
||
<ExtraQueryFilters projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
|
||
<Checkbox className="query-unassigned" checked={includeUnassigned} onChange={event => setIncludeUnassigned(event.target.checked)}>包含未分类行</Checkbox>
|
||
<div className="query-toolbar-tail">
|
||
<span className={`query-status ${queryBusy ? 'busy' : currentMetricsError ? 'failed' : ''}`}><i />{queryBusy ? '正在查询' : currentMetricsError ? '查询失败' : '查询完成'}</span>
|
||
<Button type="text" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setIncludeUnassigned(false); setSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
|
||
</div>
|
||
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
|
||
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
|
||
{organizationSummary.map((label, index) => <span className="organization-crumb" key={label}>{index > 0 && <i>›</i>}<span>{label}</span><Button type="link" onClick={() => index === 0 ? (setDepartment([]), setGroup([]), setProduct([])) : index === 1 ? (setGroup([]), setProduct([])) : setProduct([])}>清除此层</Button></span>)}
|
||
</div>}
|
||
</section>
|
||
|
||
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||
<section className="metric-strip" aria-label="质量指标">
|
||
<div className="rate-basis-control"><span>亮片本部报废调整</span><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
|
||
<MetricCard primary label={rateBasis === 'original' ? '综合合格率' : '综合调整率'} value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
|
||
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
|
||
<MetricCard label={rateBasis === 'original' ? '亮片合格率' : '亮片调整率'} value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
|
||
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText((rowForSummary.black.scrapWeight ?? 0) + (rowForSummary.bright.scrapWeight ?? 0))} kg` : '—'} note={hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(rowForSummary?.bright?.scrapWeight)} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
|
||
</section>
|
||
|
||
{['department', 'group', 'product'].includes(page) && <>
|
||
{options?.projectGroupStatus === 'UNCONFIGURED' && <Alert showIcon type="info" message="项目组映射尚未配置" description="项目组与源 Excel 业务分组是不同维度。映射启用前,此处不会将业务分组冒充项目组,也不会提供项目组筛选。" />}
|
||
</>}
|
||
|
||
<>
|
||
<section className="panel section-panel table-panel">
|
||
<div className="section-heading-row">
|
||
<SectionHeading title={drilledProduct ? '产品月度质量数据' : page === 'overall' ? `${period === 'year' ? '年度月度' : period === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={drilledProduct ? `${year} 年 · ${drilledProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
|
||
<div className="table-tools">
|
||
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSynchronizedSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||
<Tooltip title="点击综合合格率可查看计算依据"><Button type="text" icon={<InfoCircleOutlined />} aria-label="查看计算依据" onClick={() => setBasisOpen(true)} /></Tooltip>
|
||
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
|
||
</div>
|
||
</div>
|
||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||
{drilledProduct ? (
|
||
<MetricTable
|
||
rows={drilledTrendData}
|
||
view="overall"
|
||
layoutView="product"
|
||
pageSizeOverride={12}
|
||
period="year"
|
||
month={month}
|
||
quarter={quarter}
|
||
fullFields={fullFields}
|
||
rateBasis={rateBasis}
|
||
onDetail={openRecords}
|
||
onBasis={() => setBasisOpen(true)}
|
||
onDrilldown={() => undefined}
|
||
/>
|
||
) : queryPending ? <div className="loading-panel query-metrics-loading"><Spin />正在查询真实指标数据…</div> : visibleRows.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'} /> : (
|
||
<MetricTable
|
||
rows={visibleRows}
|
||
view={view}
|
||
period={period}
|
||
month={month}
|
||
quarter={quarter}
|
||
fullFields={fullFields}
|
||
rateBasis={rateBasis}
|
||
onDetail={openRecords}
|
||
onBasis={() => setBasisOpen(true)}
|
||
onDrilldown={row => {
|
||
if (view === 'overall') setViewOverride('department');
|
||
else if (view === 'department' && row.department) { setDepartment([row.department]); setViewOverride('group'); }
|
||
else if (view === 'group' && row.group) { setGroup([row.group]); setViewOverride('product'); }
|
||
else if (view === 'product') {
|
||
const selectedProduct = row.product || row.label;
|
||
if (!selectedProduct) return;
|
||
setDrilledProduct(selectedProduct);
|
||
setTrendObject(selectedProduct);
|
||
setTrendGranularity('month');
|
||
setTrendMode('production');
|
||
}
|
||
}}
|
||
/>
|
||
)}
|
||
<div className="table-footer"><span>{drilledProduct ? trendLoading && trendDataKey !== trendKey ? `${drilledProduct} · 正在查询月度数据` : `${drilledProduct} · 共 ${drilledTrendData.length} 个月` : page === 'overall' && period === 'year' ? `年度月份 12 行 · 已有数据 ${new Set((currentMetricsData?.trend || []).map(item => String(item.month))).size} 个月` : `共 ${visibleRows.length} 行`}</span></div>
|
||
</section>
|
||
|
||
<div className="analysis-stack">
|
||
<section className="panel section-panel trend-panel" id="monthly-trend">
|
||
<div className="section-heading-row trend-heading-row">
|
||
<SectionHeading title={`${trendGranularity === 'month' ? '月度' : trendGranularity === 'quarter' ? '季度' : '年度'}变化趋势`} subtitle={`${trendGranularity === 'year' ? '全部实际数据年份' : `${year} 年`} · ${trendObject || `当前${scopeName}筛选`}`} />
|
||
<Segmented value={trendMode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${trendGranularity === 'quarter' ? '季度' : trendGranularity === 'year' ? '年度' : '月度'}数据`, value: 'data' }]} onChange={value => setTrendMode(value as typeof trendMode)} aria-label="趋势视图" />
|
||
</div>
|
||
<div className="trend-controls">
|
||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={value => setTrendGranularity(value)} aria-label="趋势粒度" /></label>
|
||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={trendObject || undefined} options={trendOptions} onChange={setSynchronizedTrendObject} aria-label="趋势对象" />
|
||
</label>
|
||
{trendMode !== 'data' && <Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}
|
||
</div>
|
||
<div className="trend-chart-shell" aria-busy={trendLoading}>
|
||
{trendMode === 'data'
|
||
? <TrendTable rows={visibleTrendData} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||
{(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
||
</div>
|
||
<div className="chart-footnote"><span>全年期间均显示;无数据期间留空,指标由源分量重新汇总。</span><span>点击期间筛选,再次点击可取消</span></div>
|
||
</section>
|
||
|
||
<section className="panel section-panel defects-panel">
|
||
<div className="section-heading-row">
|
||
<SectionHeading title="不良具体构成" subtitle={`${year}年${period === 'month' ? MONTHS[month - 1] : period === 'quarter' ? `第${quarter}季度` : '全年'}${trendObject ? ` · ${trendObject}` : ''} · 占比为分类报废内占比;废率为该类重量 ÷ 同阶段适用总重量`} />
|
||
</div>
|
||
{trendObjectMetricsLoading && <div className="defect-pareto-status"><Spin size="small" />正在更新当前趋势对象的不良数据</div>}
|
||
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
|
||
<div className="defect-stage-grid">
|
||
{(['black', 'bright'] as const).map(stage => {
|
||
const items = stage === 'black' ? blackDefectItems : brightDefectItems;
|
||
return <section className="defect-stage-column" key={stage} aria-label={`${stage === 'black' ? '黑片' : '亮片'}不良构成`}>
|
||
<h3 className={`defect-stage-title ${stage}`}><i />{stage === 'black' ? '黑片' : '亮片'}</h3>
|
||
{trendObjectMetricsLoading || trendObjectMetricsError
|
||
? null
|
||
: items.length
|
||
? <DefectBreakdown items={items} stage={stage} totalWeight={activeDefectData?.summary?.[stage]?.totalWeight} maximum={Math.max(0, ...items.map(item => item.weight ?? 0))} onDetail={() => openRecords(null, stage)} />
|
||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件下暂无不良分类数据" />}
|
||
</section>;
|
||
})}
|
||
</div>
|
||
<DefectParetoPanel key={defectQueryKey} releaseId={currentMetricsData?.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} />
|
||
</section>
|
||
</div>
|
||
</>
|
||
|
||
<M01Insights key={queryKey} query={queryParams} onUnauthorized={onUnauthorized} />
|
||
|
||
<div className="query-footer"><span>查询数据由服务端按当前数据返回</span><Button type="link" onClick={() => setBasisOpen(true)}>计算口径</Button></div>
|
||
|
||
<Modal open={basisOpen} title={`${rateBasis === 'original' ? '综合合格率' : '综合调整率'}计算依据`} onCancel={() => setBasisOpen(false)} footer={<Button onClick={() => setBasisOpen(false)}>关闭</Button>} width={680}>
|
||
<div className="basis-card"><span>当前服务返回的{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</span><strong>{rateText(visibleCompositeRate(rowForSummary, rateBasis))}</strong><span>黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · {rateBasis === 'original' ? '亮片' : '亮片调整率'} {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}</span></div>
|
||
<p className="basis-copy">正式指标按当前数据绑定的规则与筛选条件计算。以下公式及空值处理说明来自指标服务;缺少阶段来源时不展示对应率。</p>
|
||
<dl className="basis-details">
|
||
<dt>综合公式</dt><dd>{formulaText(compositeFormula)}</dd>
|
||
<dt>黑片公式</dt><dd>{formulaText(formulaDescriptions.blackRate)}</dd>
|
||
<dt>{rateBasis === 'original' ? '亮片公式' : '亮片调整公式'}</dt><dd>{formulaText(brightFormula)}</dd>
|
||
<dt>统计范围</dt><dd>{year}年{period === 'month' ? ` ${MONTHS[month - 1]}` : period === 'quarter' ? ` 第${quarter}季度` : '度'} · {scopeName}</dd>
|
||
<dt>适用总重量</dt><dd>黑片 {numberText(rowForSummary?.black?.totalWeight)} kg · 亮片 {numberText(rowForSummary?.bright?.totalWeight)} kg</dd>
|
||
<dt>覆盖行数</dt><dd>黑片 {rowForSummary?.coverage.blackRows ?? '—'} · 亮片 {rowForSummary?.coverage.brightRows ?? '—'}</dd>
|
||
<dt>来源行覆盖</dt><dd>原始 {data?.coverage.rawRows ?? '—'} · 参与 {data?.coverage.includedRows ?? '—'} · 未分类排除 {data?.coverage.excludedBlankRows ?? '—'}</dd>
|
||
<dt>映射状态</dt><dd>未映射 {data?.coverage.unmappedRows ?? '—'} · 项目组配置未就绪 {data?.coverage.projectGroupUnconfiguredRows ?? '—'}</dd>
|
||
</dl>
|
||
</Modal>
|
||
|
||
<RecordsDrawer
|
||
open={recordsOpen}
|
||
row={selectedRecord}
|
||
stage={recordStage}
|
||
onStage={setRecordStage}
|
||
onClose={() => { setSelectedRecord(null); setRecordMonth(undefined); setRecordsOpen(false); }}
|
||
query={queryParams}
|
||
view={view}
|
||
month={recordMonth}
|
||
onUnauthorized={onUnauthorized}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: string; value: string; note?: string; stage?: Stage; onClick: () => void }) {
|
||
const parts = value.match(/^(.*?)(%| kg)$/);
|
||
return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}>
|
||
<span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span>
|
||
<strong className="metric-value">{parts ? <>{parts[1]}<span className="metric-unit">{parts[2]}</span></> : value}</strong>
|
||
{note && <small>{note}</small>}
|
||
</button>;
|
||
}
|
||
|
||
function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||
return <div className="defect-list">
|
||
<div className="defect-header"><span>不良分类</span><span aria-hidden="true" /><span>重量 / kg</span><span>占比</span><span>废率</span></div>
|
||
{items.map(item => <button className="defect-row" key={item.name} onClick={onDetail}>
|
||
<span className="defect-name">{item.name}</span>
|
||
<span className="defect-track"><i className={stage} style={{ width: `${maximum > 0 ? Math.max(0, (item.weight || 0) / maximum * 100) : 0}%` }} /></span>
|
||
<span className="defect-weight">{numberText(item.weight)}</span>
|
||
<span className="defect-rate">{rateText(item.rate)}</span>
|
||
<span className="defect-rate">{rateText(defectWeightRate(item.weight, totalWeight))}</span>
|
||
</button>)}
|
||
</div>;
|
||
}
|
||
|
||
const FINE_DEFECT_FIELD_COUNT = 33;
|
||
|
||
function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized }: {
|
||
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean;
|
||
}) {
|
||
const container = useRef<HTMLDivElement>(null);
|
||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse } | null>(null);
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState('');
|
||
const [themeRevision, setThemeRevision] = useState(0);
|
||
const fineQuery = useMemo(() => ({
|
||
year: query.year,
|
||
...(query.productSearch ? { productSearch: query.productSearch } : {}),
|
||
...(query.extraFilters ? { extraFilters: query.extraFilters } : {}),
|
||
...(query.month != null ? { month: query.month } : {}),
|
||
...(query.quarter != null ? { quarter: query.quarter } : {}),
|
||
...(query.department ? { department: query.department } : {}),
|
||
...(query.group ? { group: query.group } : {}),
|
||
...(query.product ? { product: query.product } : {}),
|
||
...(query.projectGroup ? { projectGroup: query.projectGroup } : {}),
|
||
...(query.includeUnassigned ? { includeUnassigned: true } : {}),
|
||
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.includeUnassigned]);
|
||
const fineQueryKey = JSON.stringify(fineQuery);
|
||
|
||
useEffect(() => {
|
||
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
|
||
const controller = new AbortController();
|
||
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
|
||
setResponses(null);
|
||
setLoading(true);
|
||
setError('');
|
||
Promise.all([
|
||
api.fineDefectTop({ ...base, stage: 'black' }, controller.signal),
|
||
api.fineDefectTop({ ...base, stage: 'bright' }, controller.signal),
|
||
]).then(([black, bright]) => setResponses({ black, bright }))
|
||
.catch(value => {
|
||
if (controller.signal.aborted) return;
|
||
if (onUnauthorized(value)) return;
|
||
setError(value instanceof ApiError && value.status === 403 ? '当前账号没有查看细分缺陷源字段的权限' : chooseError(value));
|
||
})
|
||
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||
return () => controller.abort();
|
||
}, [releaseId, fineQueryKey, onUnauthorized]);
|
||
|
||
useEffect(() => {
|
||
const observer = new MutationObserver(() => setThemeRevision(value => value + 1));
|
||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||
return () => observer.disconnect();
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
const node = container.current;
|
||
if (!node) return;
|
||
const instance = echarts.init(node, undefined, { renderer: 'svg' });
|
||
chart.current = instance;
|
||
const observer = new ResizeObserver(() => instance.resize());
|
||
observer.observe(node);
|
||
return () => { observer.disconnect(); instance.dispose(); if (chart.current === instance) chart.current = null; };
|
||
}, []);
|
||
|
||
const items = useMemo(() => {
|
||
if (!responses) return [];
|
||
const raw: Array<{ key: string; label: string; category: string; weight: number | null; kind: 'source' | 'category' }> = (['black', 'bright'] as const).flatMap(stage => responses[stage].rows.map(row => ({
|
||
key: `${stage}:${row.key}`,
|
||
label: `${stage === 'black' ? '黑片' : '亮片'}·${row.label || row.key}`,
|
||
category: row.category,
|
||
weight: row.weight,
|
||
kind: 'source' as const,
|
||
})));
|
||
if (typeof externalScrapWeight === 'number' && Number.isFinite(externalScrapWeight) && externalScrapWeight > 0) {
|
||
raw.push({ key: 'black:externalScrap', label: '黑片·外废(仅大类重量)', category: '外废', weight: externalScrapWeight, kind: 'category' });
|
||
}
|
||
return raw.filter(item => typeof item.weight === 'number' && Number.isFinite(item.weight) && item.weight > 0)
|
||
.sort((left, right) => right.weight! - left.weight! || left.label.localeCompare(right.label, 'zh-CN'));
|
||
}, [responses, externalScrapWeight]);
|
||
const totalWeight = items.reduce((total, item) => total + (item.weight || 0), 0);
|
||
const visibleFieldCount = responses ? (responses.black.sourceFields?.length || 0) + (responses.bright.sourceFields?.length || 0) : 0;
|
||
|
||
useEffect(() => {
|
||
const instance = chart.current;
|
||
if (!instance) return;
|
||
if (!items.length) { instance.clear(); return; }
|
||
const styles = getComputedStyle(document.documentElement);
|
||
const ink = styles.getPropertyValue('--ink').trim() || '#222222';
|
||
const line = styles.getPropertyValue('--line').trim() || '#dfe5ef';
|
||
const blue = styles.getPropertyValue('--blue').trim() || '#607ae1';
|
||
const teal = styles.getPropertyValue('--teal').trim() || '#008f7d';
|
||
const surface = styles.getPropertyValue('--surface').trim() || '#ffffff';
|
||
let accumulated = 0;
|
||
const cumulative = items.map(item => {
|
||
accumulated += item.weight || 0;
|
||
return Number((accumulated / totalWeight * 100).toFixed(3));
|
||
});
|
||
const option: echarts.EChartsCoreOption = {
|
||
animationDuration: 420,
|
||
animationDurationUpdate: 520,
|
||
grid: { left: 68, right: 72, top: 48, bottom: items.length > 12 ? 92 : 62, containLabel: true },
|
||
legend: { top: 8, data: ['报废重量', '累计占比'], textStyle: { color: ink, fontSize: 11 } },
|
||
tooltip: {
|
||
trigger: 'axis',
|
||
axisPointer: { type: 'shadow' },
|
||
backgroundColor: surface,
|
||
borderColor: line,
|
||
textStyle: { color: ink },
|
||
formatter: (rawParams: unknown) => {
|
||
const list = (Array.isArray(rawParams) ? rawParams : [rawParams]) as Array<{ dataIndex?: number }>;
|
||
const index = Number(list[0]?.dataIndex);
|
||
const item = items[index];
|
||
if (!item) return '';
|
||
const share = totalWeight > 0 ? (item.weight || 0) / totalWeight * 100 : 0;
|
||
return `<strong>${escapeTooltipText(item.label)}</strong><br/>分类:${escapeTooltipText(item.category)}<br/>报废重量:${numberText(item.weight)} kg<br/>综合占比:${share.toFixed(2)}%<br/>累计占比:${cumulative[index].toFixed(2)}%${item.kind === 'category' ? '<br/>来源仅提供大类重量' : '<br/>来自源表细分重量字段'}`;
|
||
},
|
||
},
|
||
xAxis: {
|
||
type: 'category',
|
||
data: items.map(item => item.label),
|
||
axisLabel: { color: ink, rotate: 35, interval: 0, hideOverlap: true, fontSize: 10 },
|
||
axisLine: { lineStyle: { color: line } },
|
||
axisTick: { alignWithLabel: true, lineStyle: { color: line } },
|
||
},
|
||
yAxis: [
|
||
{ type: 'value', name: '报废重量 / kg', nameTextStyle: { color: ink, fontSize: 10 }, axisLabel: { color: ink, fontSize: 10 }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize: 10 }, axisLabel: { color: ink, fontSize: 10, formatter: '{value}%' }, splitLine: { show: false } },
|
||
],
|
||
series: [
|
||
{ name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
|
||
{ name: '累计占比', type: 'line', z: 10, yAxisIndex: 1, symbol: 'circle', symbolSize: 5, lineStyle: { width: 2, color: '#d58c35' }, itemStyle: { color: '#d58c35', borderColor: surface, borderWidth: 1 }, data: cumulative },
|
||
],
|
||
};
|
||
instance.setOption(option, { notMerge: true, lazyUpdate: false });
|
||
}, [items, totalWeight, themeRevision]);
|
||
|
||
const incompleteCategories = responses
|
||
? (['black', 'bright'] as const).flatMap(stage => responses[stage].coverage?.categories || [])
|
||
.filter(item => item.reconciliationStatus !== 'RECONCILED' && item.reconciliationStatus !== 'UNAVAILABLE').length
|
||
: 0;
|
||
|
||
return <section className="defect-pareto-section" aria-label="综合报废重量柏拉图">
|
||
<div className="defect-pareto-heading"><strong>黑片与亮片综合报废重量柏拉图</strong><span>{responses ? `细分源字段 ${visibleFieldCount} / ${FINE_DEFECT_FIELD_COUNT} 项${incompleteCategories ? ` · ${incompleteCategories} 类细分数据未与正式大类完全核对` : ''}` : '按当前筛选范围汇总全部可见细分报废重量'}</span></div>
|
||
{loading && <div className="defect-pareto-status"><Spin size="small" />正在汇总细分报废重量</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="当前筛选下没有正值细分报废重量" />}
|
||
<div className="defect-pareto-chart" ref={container} style={{ display: !releaseId || error || (responses && !items.length) ? 'none' : undefined }} aria-label="按报废重量降序排列,折线表示累计占比" />
|
||
</section>;
|
||
}
|
||
|
||
function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) {
|
||
return <div className="section-heading"><h2>{title}</h2>{subtitle && <span>{subtitle}</span>}</div>;
|
||
}
|
||
|
||
function useCompactTable() {
|
||
const [compact, setCompact] = useState(() => window.matchMedia('(max-width: 760px)').matches);
|
||
useEffect(() => {
|
||
const media = window.matchMedia('(max-width: 760px)');
|
||
const update = () => setCompact(media.matches);
|
||
media.addEventListener('change', update);
|
||
return () => media.removeEventListener('change', update);
|
||
}, []);
|
||
return compact;
|
||
}
|
||
|
||
function MetricTable({
|
||
rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown,
|
||
}: {
|
||
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; 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;
|
||
}) {
|
||
const compact = useCompactTable();
|
||
const blackDefects = fullFields ? defectsFor(rows, 'black') : [];
|
||
const brightDefects = fullFields ? defectsFor(rows, 'bright') : [];
|
||
const isOverall = view === 'overall';
|
||
const title = (row: MetricRow) => isOverall && period === 'year'
|
||
? (monthNumber((row as TrendMetricRow).month) ? MONTHS[monthNumber((row as TrendMetricRow).month)! - 1] : row.label)
|
||
: isOverall && period === 'month' ? MONTHS[month - 1]
|
||
: isOverall && period === 'quarter' ? `第${quarter}季度` : objectLabel(row, view);
|
||
const openRow = (row: MetricRow, stage: Stage) => {
|
||
if ((row as TrendMetricRow).noData) return;
|
||
onDetail(row, stage, isOverall && period === 'year' ? monthNumber((row as TrendMetricRow).month) || undefined : isOverall && period === 'month' ? month : undefined);
|
||
};
|
||
const numeric = (label: string, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', className = '') => ({
|
||
title: compact ? `${stage === 'black' ? '黑片' : '亮片'}${label}` : label,
|
||
key: `${stage}-${field}`,
|
||
align: 'center' as const,
|
||
width: field === 'rate' ? 116 : 145,
|
||
className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`,
|
||
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" onClick={() => openRow(row, stage)}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : numberText(stageValue(row, stage, field))}</Button>,
|
||
});
|
||
const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({
|
||
title: compact ? `${stage === 'black' ? '黑片' : '亮片'}${name}` : name,
|
||
key: `${stage}-defect-${name}`,
|
||
align: 'center' as const,
|
||
width: 130,
|
||
render: (_: unknown, row: MetricRow) => {
|
||
const value = defectList(row, stage).find(item => item.name === name);
|
||
return <Button type="link" className="table-value" onClick={() => openRow(row, stage)}>{numberText(value?.weight ?? null)}</Button>;
|
||
},
|
||
}));
|
||
const columns: ColumnsType<MetricRow> = [
|
||
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : layoutView === 'product' ? 300 : layoutView === 'group' ? 260 : 220, render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" onClick={() => onDrilldown(row)}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}{view === 'product' && row.group && <small>{row.group}</small>}</span> },
|
||
{ title: <button className="header-link" onClick={onBasis}>{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</button>, key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'left', width: 140, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" onClick={onBasis}>{rateText(visibleCompositeRate(row, rateBasis))}</button> },
|
||
{ title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('合格重量', 'black', 'qualifiedWeight'), ...(fullFields ? [numeric('适用总重量', 'black', 'totalWeight')] : []), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
|
||
{ title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('合格重量', 'bright', 'qualifiedWeight'), ...(fullFields ? [numeric('适用总重量', 'bright', 'totalWeight')] : []), numeric('报废重量', 'bright', 'scrapWeight'), ...(fullFields ? [numeric('本部报废重量', 'bright', 'headquartersScrapWeight')] : []), ...defectColumns('bright', brightDefects), { ...numeric(rateBasis === 'original' ? '合格率' : '不含本部报废调整率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" onClick={() => openRow(row, 'bright')}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] },
|
||
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 100, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, 'black')}>来源明细</Button> },
|
||
];
|
||
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 effectivePageSize = pageSizeOverride ?? pageSize;
|
||
useEffect(() => setCurrentPage(1), [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);
|
||
}
|
||
return typeof column.width === 'number' && Number.isFinite(column.width) ? column.width : 120;
|
||
};
|
||
const scrollWidth = Math.ceil(columns.reduce((total, column) => total + columnWidth(column), 0));
|
||
const scroll = { x: scrollWidth };
|
||
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 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); }} />}
|
||
</div>;
|
||
}
|
||
|
||
function MetricTablePagination({ current, total, pageSize, onChange }: { current: number; total: number; pageSize: number;
|
||
onChange: (page: number, pageSize: number) => void }) {
|
||
if (total <= Math.min(pageSize, SUMMARY_PAGE_SIZE)) return null;
|
||
return <div className="metric-table-pagination"><Pagination current={current} total={total} pageSize={pageSize} showSizeChanger pageSizeOptions={SUMMARY_PAGE_SIZE_OPTIONS}
|
||
showTotal={(count, range) => `显示 ${range[0]}–${range[1]} 行,共 ${count.toLocaleString('zh-CN')} 行`} onChange={onChange} /></div>;
|
||
}
|
||
|
||
function trendBarWidth(chartWidth: number, count: number): number {
|
||
return Math.max(12, Math.min(64, Math.floor(((chartWidth - 132) / Math.max(count, 1)) * 0.8)));
|
||
}
|
||
|
||
function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void }) {
|
||
const container = useRef<HTMLDivElement>(null);
|
||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||
const onMonthRef = useRef(onMonth);
|
||
const rowsRef = useRef(rows);
|
||
const modeRef = useRef(mode);
|
||
const stageRef = useRef(stage);
|
||
const graphicIds = useRef(new Set<string>());
|
||
const previousSelection = useRef<string | undefined>(undefined);
|
||
const selectionReady = useRef(false);
|
||
const [lineSelectedPeriod, setLineSelectedPeriod] = useState<string | undefined>(undefined);
|
||
const [barMasks, setBarMasks] = useState<Array<{ period: string; left: number; top: number; width: number; height: number }>>([]);
|
||
const [themeRevision, setThemeRevision] = useState(0);
|
||
const hasRows = rows.length > 0;
|
||
onMonthRef.current = onMonth;
|
||
rowsRef.current = rows;
|
||
modeRef.current = mode;
|
||
stageRef.current = stage;
|
||
|
||
const refreshBarMasks = useCallback(() => {
|
||
const instance = chart.current;
|
||
if (!instance || modeRef.current !== 'production') { setBarMasks([]); return; }
|
||
const zero = Number(instance.convertToPixel({ yAxisIndex: 0 }, 0));
|
||
const width = trendBarWidth(instance.getWidth(), rowsRef.current.length);
|
||
const next = rowsRef.current.flatMap(row => {
|
||
const currentStage = row[stageRef.current];
|
||
if (!hasStageRows(row, stageRef.current)) return [];
|
||
const total = (currentStage.qualifiedWeight ?? 0) + (currentStage.scrapWeight ?? 0);
|
||
if (total <= 0) return [];
|
||
const x = Number(instance.convertToPixel({ xAxisIndex: 0 }, row.periodLabel || String(row.month)));
|
||
const top = Number(instance.convertToPixel({ yAxisIndex: 0 }, total));
|
||
if (!Number.isFinite(x) || !Number.isFinite(top) || !Number.isFinite(zero)) return [];
|
||
return [{ period: String(row.period ?? row.month), left: x - width / 2, top, width, height: Math.max(0, zero - top) }];
|
||
});
|
||
setBarMasks(previous => previous.length === next.length && previous.every((mask, index) =>
|
||
mask.period === next[index].period && mask.left === next[index].left && mask.top === next[index].top && mask.width === next[index].width && mask.height === next[index].height
|
||
) ? previous : next);
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
const observer = new MutationObserver(() => setThemeRevision(value => value + 1));
|
||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||
return () => observer.disconnect();
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
if (!container.current || !hasRows) return;
|
||
const instance = echarts.init(container.current, undefined, { renderer: 'svg' });
|
||
chart.current = instance;
|
||
graphicIds.current.clear();
|
||
instance.on('click', params => {
|
||
if (params.componentType !== 'series' && params.componentType !== 'xAxis') return;
|
||
const currentRows = rowsRef.current;
|
||
const index = params.dataIndex ?? currentRows.findIndex(row => (row.periodLabel || String(row.month)) === String(params.value ?? params.name));
|
||
const item = index >= 0 ? currentRows[index] : undefined;
|
||
const value = item?.month ?? params.name ?? params.axisValue ?? params.value;
|
||
if (value != null) {
|
||
setLineSelectedPeriod(params.componentType === 'series' && params.seriesType === 'line' ? String(item?.period ?? item?.month ?? value) : undefined);
|
||
onMonthRef.current(value);
|
||
}
|
||
});
|
||
const observer = new ResizeObserver(() => {
|
||
if (!container.current) return;
|
||
const { clientWidth, clientHeight } = container.current;
|
||
if (clientWidth !== instance.getWidth() || clientHeight !== instance.getHeight()) {
|
||
instance.resize();
|
||
if (modeRef.current === 'production') {
|
||
const barWidth = trendBarWidth(instance.getWidth(), rowsRef.current.length);
|
||
instance.setOption({ series: [{ id: 'qualified-weight', barWidth }, { id: 'scrap-weight', barWidth }] });
|
||
}
|
||
refreshBarMasks();
|
||
}
|
||
});
|
||
observer.observe(container.current);
|
||
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
||
}, [hasRows, refreshBarMasks]);
|
||
|
||
useEffect(() => {
|
||
const instance = chart.current;
|
||
if (!instance || !container.current) return;
|
||
const css = getComputedStyle(container.current);
|
||
const ink = css.getPropertyValue('--ink').trim() || '#111111';
|
||
const blue = css.getPropertyValue('--blue').trim() || '#5368d7';
|
||
const barColor = css.getPropertyValue('--blue-muted').trim() || '#b0bcee';
|
||
const teal = css.getPropertyValue('--teal').trim() || '#008f7d';
|
||
const line = css.getPropertyValue('--line').trim() || '#dfe5ef';
|
||
const surface = css.getPropertyValue('--surface').trim() || '#ffffff';
|
||
const labels = rows.map(row => row.periodLabel || String(row.month));
|
||
const barData = (field: 'qualifiedWeight' | 'scrapWeight') => rows.map(row => ({
|
||
value: hasStageRows(row, stage) ? row[stage][field] ?? null : null,
|
||
}));
|
||
const formatTooltip = (params: unknown, onlyRates = false) => {
|
||
const items: ChartTooltipParam[] = Array.isArray(params) ? params as ChartTooltipParam[] : [params as ChartTooltipParam];
|
||
const title = String(items[0]?.name || items[0]?.axisValue || '');
|
||
return [escapeTooltipText(title), ...items.map(item => {
|
||
const name = String(item.seriesName || '');
|
||
const formatted = item.value == null ? '—' : onlyRates || name.includes('率') ? `${Number(item.value).toFixed(2)}%` : `${numberText(item.value)} kg`;
|
||
return `${item.marker || ''}${escapeTooltipText(name)}:${formatted}`;
|
||
})].join('<br/>');
|
||
};
|
||
const base: echarts.EChartsCoreOption = {
|
||
animation: false,
|
||
textStyle: { fontFamily: '-apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif', color: ink, fontSize: 12 },
|
||
grid: { left: 65, right: mode === 'production' ? 67 : 32, top: 70, bottom: 38 },
|
||
legend: { type: 'scroll', top: 0, left: 9, right: 9, itemWidth: 14, itemHeight: 7, itemGap: 20, textStyle: { color: ink, fontSize: 12 } },
|
||
tooltip: { trigger: 'axis', backgroundColor: surface, borderColor: line, borderWidth: 1, padding: [10, 13], textStyle: { color: ink, fontSize: 12 }, transitionDuration: 0, axisPointer: { type: 'line', lineStyle: { color: blue, width: 1, type: 'dashed' } }, formatter: (params: unknown) => formatTooltip(params, mode === 'defects') },
|
||
xAxis: { type: 'category', data: labels, triggerEvent: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, margin: 12 }, axisTick: { show: false } },
|
||
};
|
||
let option: echarts.EChartsCoreOption;
|
||
const pointStyle = { z: 10, symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false };
|
||
if (mode === 'production') {
|
||
const rates = [...rows.flatMap(row => [visibleCompositeRate(row, rateBasis), visibleStageRate(row, 'black'), visibleStageRate(row, 'bright', rateBasis)]).filter((value): value is number => value != null).map(value => value * 100), ...(targetRate == null ? [] : [targetRate])];
|
||
const minRate = rates.length ? Math.max(0, Math.floor(Math.min(...rates) - 2)) : 0;
|
||
const maxRate = rates.length ? Math.max(100, Math.ceil(Math.max(...rates) + 1)) : 100;
|
||
const stageName = stage === 'black' ? '黑片' : '亮片';
|
||
const barWidth = trendBarWidth(instance.getWidth(), rows.length);
|
||
const targetLine = targetRate == null ? {} : { markLine: {
|
||
silent: true,
|
||
symbol: 'none',
|
||
lineStyle: { color: '#c47a47', width: 1.5, type: 'dashed' as const },
|
||
label: { show: true, formatter: `综合率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize: 11 },
|
||
data: [{ yAxis: targetRate }],
|
||
} };
|
||
option = {
|
||
...base,
|
||
yAxis: [
|
||
{ type: 'value', name: '重量 / kg', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: 11 }, axisLabel: { color: ink, fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||
{ type: 'value', name: '合格率 / %', nameGap: 18, min: minRate, max: maxRate, nameTextStyle: { color: ink, align: 'right', fontSize: 11 }, axisLabel: { color: ink, formatter: '{value}%', fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } },
|
||
],
|
||
series: [
|
||
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: blue } }, data: barData('qualifiedWeight') },
|
||
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: '#edaa83' }, emphasis: { itemStyle: { color: '#e58e5d' } }, data: barData('scrapWeight') },
|
||
{ id: 'composite-rate', name: rateBasis === 'original' ? '综合合格率' : '综合调整率', type: 'line', yAxisIndex: 1, ...pointStyle, ...targetLine, lineStyle: { width: 2.5, color: blue }, itemStyle: { color: blue, borderColor: surface, borderWidth: 1.5 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
|
||
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: '#9278bf' }, itemStyle: { color: '#9278bf', borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
|
||
{ id: 'bright-rate', name: rateBasis === 'original' ? '亮片合格率' : '亮片不含本部报废调整率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: teal }, itemStyle: { color: teal, borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
|
||
],
|
||
};
|
||
} else {
|
||
const names = Array.from(new Set(rows.flatMap(row => row[stage].defects.map(defect => defect.name))));
|
||
const palette = [blue, teal, '#bf7d58', '#9278bf', '#598eae'];
|
||
option = {
|
||
...base,
|
||
yAxis: [{ type: 'value', name: '不良率 / %', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: 11 }, axisLabel: { color: ink, formatter: '{value}%', fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } }],
|
||
series: names.map((name, index) => ({ id: `defect-${stage}-${name}`, name, type: 'line' as const, ...pointStyle, lineStyle: { width: 2, color: palette[index % palette.length] }, itemStyle: { color: palette[index % palette.length] }, data: rows.map(row => { const defect = row[stage].defects.find(item => item.name === name); return rateNumber(defectWeightRate(defect?.weight, row[stage].totalWeight)); }) })),
|
||
};
|
||
}
|
||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||
refreshBarMasks();
|
||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks]);
|
||
|
||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||
|
||
useEffect(() => {
|
||
if (lineSelectedPeriod && selectedPeriod !== lineSelectedPeriod) setLineSelectedPeriod(undefined);
|
||
}, [lineSelectedPeriod, selectedPeriod]);
|
||
|
||
useLayoutEffect(() => {
|
||
const instance = chart.current;
|
||
if (!instance || !container.current) return;
|
||
const previous = previousSelection.current;
|
||
const changed = selectionReady.current && previous !== dimmedPeriod;
|
||
const animate = changed && !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||
const surface = getComputedStyle(container.current).getPropertyValue('--surface').trim() || '#ffffff';
|
||
const masks = mode === 'production' ? barMasks : [];
|
||
const nextIds = new Set(masks.flatMap(mask => [`wash-${mask.period}`, `focus-${mask.period}`]));
|
||
// Keep the animated bar treatment inside the chart's paint order: bars 1,
|
||
// wash 2, focus 3, lines 10. A DOM overlay would also cover every line.
|
||
const elements = masks.flatMap(mask => {
|
||
const dimmed = dimmedPeriod != null && mask.period !== dimmedPeriod;
|
||
return [
|
||
{ id: `wash-${mask.period}`, type: 'rect', silent: true, z: 2, transition: ['shape'],
|
||
shape: { x: mask.left, y: mask.top, width: mask.width, height: dimmed ? mask.height : 0 }, style: { fill: surface, opacity: .72 } },
|
||
{ id: `focus-${mask.period}`, type: 'rect', silent: true, z: 3, transition: ['style'],
|
||
shape: { x: mask.left, y: mask.top, width: mask.width, height: mask.height },
|
||
style: { fill: 'transparent', stroke: 'rgba(137,165,255,.7)', lineWidth: 1, shadowBlur: 11, shadowColor: 'rgba(117,151,255,.26)', opacity: dimmedPeriod === mask.period ? 1 : 0 } },
|
||
];
|
||
});
|
||
const removed = [...graphicIds.current].filter(id => !nextIds.has(id)).map(id => ({ id, $action: 'remove' as const }));
|
||
instance.setOption({ graphic: { animation: animate, animationDurationUpdate: 340, animationEasingUpdate: 'cubicOut', elements: [...elements, ...removed] } });
|
||
graphicIds.current = nextIds;
|
||
previousSelection.current = dimmedPeriod;
|
||
selectionReady.current = true;
|
||
}, [dimmedPeriod, barMasks, mode, themeRevision]);
|
||
|
||
return <div className="chart-viewport">
|
||
<div className="chart-surface">
|
||
<div className={`chart-container ${rows.length ? '' : 'chart-empty'}`} ref={container} role="img" aria-label={mode === 'production' ? '重量和合格率趋势' : `${stage === 'black' ? '黑片' : '亮片'}不良率趋势`} />
|
||
</div>
|
||
{!rows.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />}
|
||
</div>;
|
||
}
|
||
|
||
function TrendTable({ rows, rateBasis, onMonth, showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; showMonthLinks?: boolean }) {
|
||
const [currentPage, setCurrentPage] = useState(1);
|
||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||
useEffect(() => setCurrentPage(1), [rows]);
|
||
const columns: ColumnsType<TrendMetricRow> = [
|
||
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
|
||
{ title: rateBasis === 'original' ? '综合合格率' : '综合调整率', dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 130, className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) },
|
||
{ title: '黑片合格重量 / kg', dataIndex: ['black', 'qualifiedWeight'], key: 'blackQualified', align: 'center', width: 160, render: value => numberText(value) },
|
||
{ title: '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: value => numberText(value) },
|
||
{ title: '黑片合格率', dataIndex: ['black', 'rate'], key: 'blackRate', align: 'center', width: 130, render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'black')) },
|
||
{ title: '亮片合格重量 / kg', dataIndex: ['bright', 'qualifiedWeight'], key: 'brightQualified', align: 'center', width: 160, render: value => numberText(value) },
|
||
{ title: '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: value => numberText(value) },
|
||
{ title: rateBasis === 'original' ? '亮片合格率' : '亮片不含本部报废调整率', dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: 180, render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) },
|
||
];
|
||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered columns={columns} dataSource={rows} rowKey={row => String(row.month)} pagination={{ current: currentPage, pageSize, showSizeChanger: rows.length > SUMMARY_PAGE_SIZE, pageSizeOptions: SUMMARY_PAGE_SIZE_OPTIONS, showTotal: (total, range) => `显示 ${range[0]}–${range[1]} 行,共 ${total} 个月`, onChange: (nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); } }} scroll={{ x: 1130 }} />
|
||
{showMonthLinks && <div className="trend-month-links">{rows.map(row => <Button key={row.key} type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || row.month}汇总</Button>)}</div>}
|
||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
|
||
}
|
||
|
||
function RecordsDrawer({
|
||
open, row, stage, onStage, onClose, query, view, month, onUnauthorized,
|
||
}: {
|
||
open: boolean; row: MetricRow | null; stage: Stage; onStage: (stage: Stage) => void; onClose: () => void;
|
||
query: QueryParams; view: ViewKind; month?: number; onUnauthorized: (error: unknown) => boolean;
|
||
}) {
|
||
const { message } = App.useApp();
|
||
const [page, setPage] = useState(1);
|
||
const [result, setResult] = useState<RecordsResponse | null>(null);
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState('');
|
||
const [field, setField] = useState<string>();
|
||
const [fieldSearch, setFieldSearch] = useState('');
|
||
const [sort, setSort] = useState<string>();
|
||
const [direction, setDirection] = useState<'asc' | 'desc'>('asc');
|
||
const [selectedColumns, setSelectedColumns] = useState<string[]>();
|
||
const [rawFields, setRawFields] = useState<string[]>([]);
|
||
const [exporting, setExporting] = useState(false);
|
||
|
||
const recordQuery = useMemo(() => {
|
||
const params: QueryParams = { ...query };
|
||
if (month) { params.month = month; delete params.quarter; }
|
||
if (row) {
|
||
if (view === 'department') params.department = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.department || row.key);
|
||
if (view === 'group') params.group = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.group || row.key);
|
||
if (view === 'product') params.product = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.product || row.key);
|
||
if (view === 'projectGroup') params.projectGroup = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.projectGroup || row.key);
|
||
}
|
||
return params;
|
||
}, [query, row, view, month]);
|
||
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
const controller = new AbortController();
|
||
setLoading(true);
|
||
setError('');
|
||
api.records({ ...recordQuery, stage, page, pageSize: TABLE_PAGE_SIZE,
|
||
...(field ? { field } : {}), ...(field && fieldSearch.trim() ? { search: fieldSearch.trim() } : {}),
|
||
...(sort ? { sort, direction } : {}),
|
||
}, controller.signal).then(value => {
|
||
setResult(value);
|
||
const pageFields = value.rows.flatMap(record => Object.keys(record.raw || {}).filter(key => !isSystemVersionField(key)));
|
||
if (pageFields.length) setRawFields(existing => [...new Set([...existing, ...pageFields])]);
|
||
})
|
||
.catch(errorValue => {
|
||
if (controller.signal.aborted) return;
|
||
if (!onUnauthorized(errorValue)) setError(chooseError(errorValue));
|
||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||
return () => controller.abort();
|
||
}, [open, recordQuery, stage, page, field, fieldSearch, sort, direction, onUnauthorized]);
|
||
|
||
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
|
||
const exportRecords = async () => {
|
||
const params: RecordExportParams = {
|
||
year: recordQuery.year,
|
||
...(recordQuery.extraFilters ? { extraFilters: recordQuery.extraFilters } : {}),
|
||
...(recordQuery.month !== undefined ? { month: recordQuery.month } : {}),
|
||
...(recordQuery.quarter !== undefined ? { quarter: recordQuery.quarter } : {}),
|
||
...(recordQuery.department !== undefined ? { department: recordQuery.department } : {}),
|
||
...(recordQuery.group !== undefined ? { group: recordQuery.group } : {}),
|
||
...(recordQuery.product !== undefined ? { product: recordQuery.product } : {}),
|
||
...(recordQuery.productSearch !== undefined ? { productSearch: recordQuery.productSearch } : {}),
|
||
...(recordQuery.projectGroup !== undefined ? { projectGroup: recordQuery.projectGroup } : {}),
|
||
...(recordQuery.includeUnassigned !== undefined ? { includeUnassigned: recordQuery.includeUnassigned } : {}),
|
||
...(recordQuery.releaseId !== undefined ? { releaseId: recordQuery.releaseId } : {}),
|
||
};
|
||
setExporting(true);
|
||
try {
|
||
const { blob, filename } = await api.exportRecords(params);
|
||
const url = URL.createObjectURL(blob);
|
||
const link = document.createElement('a');
|
||
link.href = url;
|
||
link.download = filename;
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
message.success('明细 Excel 已开始下载,含黑片和亮片两个工作表');
|
||
} catch (errorValue) {
|
||
message.error(chooseError(errorValue));
|
||
} finally {
|
||
setExporting(false);
|
||
}
|
||
};
|
||
const fixedColumns: ColumnsType<RecordRow> = [
|
||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', fixed: 'left', width: 220, ellipsis: true },
|
||
{ title: '原始行数据', key: 'rawRecord', fixed: 'left', width: 200, render: (_: unknown, record: RecordRow) => {
|
||
const raw = withoutSystemVersionFields(record.raw || {}) as Record<string, unknown>;
|
||
const fieldCount = Object.keys(raw).length;
|
||
return <details className="source-fields source-raw-fields">
|
||
<summary>查看全部原始字段({fieldCount})</summary>
|
||
<p>以下为该来源行导入时保存的字段值,按当前字段授权筛选。</p>
|
||
<pre className="json-cell">{JSON.stringify(raw, null, 2)}</pre>
|
||
</details>;
|
||
} },
|
||
{ title: '工作表', dataIndex: 'sheet', key: 'sheet', width: 120 },
|
||
{ title: '行号', dataIndex: 'rowNumber', key: 'rowNumber', align: 'right', width: 85 },
|
||
{ title: '月份', dataIndex: 'month', key: 'month', align: 'center', width: 100, render: value => {
|
||
const month = monthNumber(value);
|
||
return month ? MONTHS[month - 1] : String(value || '—');
|
||
} },
|
||
{ title: '产业部', dataIndex: 'department', key: 'department', width: 160 },
|
||
{ title: '业务分组', dataIndex: 'group', key: 'group', width: 190 },
|
||
{ title: '产品', dataIndex: 'product', key: 'product', width: 190 },
|
||
...visibleRawFields.map(name => ({ title: name, key: `raw:${name}`, width: 180, ellipsis: true, render: (_: unknown, record: RecordRow) => String(record.raw?.[name] ?? '—') })),
|
||
{ title: '规范化值与转换说明', key: 'transform', width: 260, render: (_: unknown, record: RecordRow) => <details className="source-fields"><summary>查看本行转换</summary><strong>规范化值</strong><pre className="json-cell">{JSON.stringify(withoutSystemVersionFields(record.normalized || {}), null, 2)}</pre><strong>转换说明</strong><ul>{(record.transformNotes || []).map((note, index) => <li key={index}>{typeof note === 'string' ? note : JSON.stringify(withoutSystemVersionFields(note))}</li>)}</ul></details> },
|
||
{ title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value => <details className="source-fields"><summary>查看计算分量</summary><pre className="json-cell">{JSON.stringify(withoutSystemVersionFields(value), null, 2)}</pre></details> },
|
||
];
|
||
|
||
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 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="导出当前查询范围全部来源明细,含黑片和亮片两个工作表">导出明细 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); }} />
|
||
<label><span>显示列</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" placeholder="默认显示前 8 个字段" value={selectedColumns} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setSelectedColumns(value); setPage(1); }} /></label>
|
||
<label><span>排序字段</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="默认顺序" value={sort} options={[
|
||
{ label: '月份', value: 'month' }, { label: '来源文件', value: 'sourceFile' }, { label: '工作表', value: 'sheet' }, { label: '行号', value: 'rowNumber' },
|
||
{ label: '产业部', value: 'department' }, { label: '业务分组', value: 'group' }, { label: '项目组', value: 'projectGroup' }, { label: '产品', value: 'product' },
|
||
...(field ? [{ label: `原始字段:${field}`, value: 'rawField' }] : []),
|
||
]} 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} />}
|
||
{loading && !result ? <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 }} /> : !loading && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
|
||
{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>;
|
||
}
|