import { useEffect, useMemo, useState } from 'react'; import { BookOpen, Box, ChevronDown, ChevronRight, FlaskConical, GitBranch, Search, Wrench, X, } from 'lucide-react'; import { useTheme, type ThemeTokens } from '../../context/ThemeContext'; import { ONTOLOGY_AS_OF } from '../../data/ontologyQap'; import { ROLE_COLOR, roleDocs, type RoleKey } from '../../data/knowledge'; import type { KbRef } from '../../data/kbLinks'; import { getFeatureTree, methodsForRef, type FeatureMethod, type FeatureModel, type FeatureProcess, } from '../../data/featureTree'; import type { MethodSummaryRow } from '../../data/methodSummaries'; import { methodImageSrc } from '../../data/methodImages'; /** * 特征建模舞台:机型 → 工艺 → 生产方法 三级树。 * * 第三级是可执行的生产方法(数控冲孔 / 手工倒角 / 激光焊 / 压铆…)。 * 选中生产方法后,右侧按「每条知识来源一行」列出问题 / 原因 / 对策 / 角色。 * 真实知识只覆盖 SRV-2U-620;其余机型与空方法用方法模板示例补齐,并标「示例」。 * * 与知识库的双向动线: * 知识库点特征码 → 经 featFocus 跳到这里,自动展开并选中对应生产方法 * 这里点「原文」→ 经 onOpenKnowledge 跳回知识库对应切片 */ interface Props { onExit: () => void; /** 从知识库跳回时:指定要聚焦的数据对象/实例 */ focus?: { objKey: string; instanceId?: string } | null; /** 点击知识来源时跳回知识库 */ onOpenKnowledge?: (role: RoleKey, chunkId: string) => void; } type Path = { modelId: string; processId?: string; methodId?: string }; const ROLE_LABEL: Record = { PE: '工艺', IE: '工业', QE: '质量', ME: '制造', }; const ROLE_FULL: Record = { PE: '工艺工程师', IE: '工业工程师', QE: '质量工程师', ME: '制造工程师', }; const KB_MODEL = 'SRV-2U-620'; const cardBase = (tk: ThemeTokens, on: boolean): React.CSSProperties => ({ width: '100%', textAlign: 'left', cursor: 'pointer', padding: '6px 8px', borderRadius: 8, marginBottom: 4, background: on ? tk.accentBg : 'transparent', border: `1px solid ${on ? tk.accent : 'transparent'}`, transition: 'background .15s ease, border-color .15s ease', }); export default function FeatureTreeView({ onExit, focus, onOpenKnowledge }: Props) { const { tokens } = useTheme(); const tree = useMemo(getFeatureTree, []); const initialSelection = useMemo(() => { const model = tree.models.find(m => m.id === KB_MODEL) ?? tree.models[0]; if (!model) return { modelId: '' }; const proc = model.processes.find(p => p.id === 'NCT') ?? model.processes[0]; const method = proc?.methods.find(m => m.label === '手工倒角') ?? proc?.methods[0]; return method ? { modelId: model.id, processId: proc.id, methodId: method.id } : proc ? { modelId: model.id, processId: proc.id } : { modelId: model.id }; }, [tree]); const validSelection = (path: Path | null): boolean => { if (!path) return false; const model = tree.models.find(m => m.id === path.modelId); if (!model) return false; if (!path.processId) return true; const proc = model.processes.find(p => p.id === path.processId); if (!proc) return false; if (!path.methodId) return true; return proc.methods.some(m => m.id === path.methodId); }; /* 从知识库跳回时优先用上次的选中,否则用默认方法 */ const [selected, setSelected] = useState(() => { const last = readLastSelection(); return validSelection(last) ? last! : initialSelection; }); const [expanded, setExpanded] = useState>(() => { const first = tree.models.find(m => m.id === KB_MODEL) ?? tree.models[0]; const set = new Set(); if (first) { set.add(first.id); for (const p of first.processes) set.add(`${first.id}/${p.id}`); } return set; }); const [query, setQuery] = useState(''); /* 外部跳入:知识库点特征码 → 定位到对应生产方法 */ useEffect(() => { if (!focus) return; const methods = methodsForRef(focus.objKey, focus.instanceId); if (methods.length === 0) return; const target = methods.find(m => m.modelId === KB_MODEL) ?? methods[0]; setSelected({ modelId: target.modelId, processId: target.processId, methodId: target.id }); setExpanded(prev => { const next = new Set(prev); next.add(target.modelId); next.add(`${target.modelId}/${target.processId}`); return next; }); }, [focus]); /* 记住舞台内最后一次选中,退出再进入时保持不变 */ useEffect(() => { if (selected.modelId) writeLastSelection(selected); }, [selected]); const q = query.trim().toLowerCase(); const match = (text: string) => text.toLowerCase().includes(q); const methodVisible = (m: FeatureMethod) => !q || match(m.label) || m.summary.some(r => match(r.problem) || match(r.cause) || match(r.action) || match(r.role)); const selectedNode = useMemo(() => { const model = tree.models.find(m => m.id === selected.modelId); if (!model) return null; if (!selected.processId) return { kind: 'model' as const, node: model }; const proc = model.processes.find(p => p.id === selected.processId); if (!proc) return { kind: 'model' as const, node: model }; if (!selected.methodId) return { kind: 'process' as const, node: proc }; const method = proc.methods.find(m => m.id === selected.methodId); return method ? { kind: 'method' as const, node: method } : { kind: 'process' as const, node: proc }; }, [selected, tree]); const totalLeaves = useMemo( () => tree.models.reduce((a, m) => a + m.processes.reduce((b, p) => b + p.methods.length, 0), 0), [tree], ); const totalKb = useMemo( () => tree.models.reduce((a, m) => a + m.kbRefs.length, 0), [tree], ); const toggleExpand = (id: string) => { setExpanded(prev => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; const isSelected = (path: Path) => selected.modelId === path.modelId && selected.processId === path.processId && selected.methodId === path.methodId; const box: React.CSSProperties = { minWidth: 0, display: 'flex', flexDirection: 'column', borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`, }; return (
{/* ── 标题栏 ── */}
特征建模 快照日 {ONTOLOGY_AS_OF} · 机型 → 工艺 → 生产方法
{[ { l: '机型', v: tree.models.length }, { l: '工艺', v: tree.models.reduce((a, m) => a + m.processes.length, 0) }, { l: '生产方法', v: totalLeaves }, { l: '知识挂载', v: totalKb, hot: true }, ].map(s => ( {s.l} {s.v} ))}
setQuery(e.target.value)} placeholder="搜索机型 / 工艺 / 方法 / 问题" style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', color: tokens.text, fontSize: 13.5 }} /> {query && ( )}
{/* ── 主区:左树 + 右详情 ── */}
{/* 左侧树 */}
特征树 叶子=生产方法
{tree.models.map(model => { const modelOpen = q ? true : expanded.has(model.id); const modelVisible = !q || match(model.label) || model.processes.some(p => match(p.label) || p.methods.some(methodVisible), ); if (!modelVisible) return null; const modelSel = isSelected({ modelId: model.id }); return (
{modelOpen && model.processes.map(proc => { const procOpen = q ? true : expanded.has(`${model.id}/${proc.id}`); const procVisible = !q || match(proc.label) || proc.methods.some(methodVisible); if (!procVisible) return null; const procSel = isSelected({ modelId: model.id, processId: proc.id }); return (
{procOpen && proc.methods.map(method => { if (!methodVisible(method)) return null; const methodSel = isSelected({ modelId: model.id, processId: proc.id, methodId: method.id }); const hasReal = method.realCount > 0; const thumb = methodImageSrc(method.label); return ( ); })}
); })}
); })}
{/* 右侧详情 */}
setSelected({ modelId: method.modelId, processId: method.processId, methodId: method.id, })} />
); } /* ── 选中记忆(仅本舞台,刷新后保留) ─────────────────────────────────── */ const LAST_KEY = 'qap.featureTree.lastSelection'; function readLastSelection(): Path | null { try { const raw = sessionStorage.getItem(LAST_KEY); if (!raw) return null; const p = JSON.parse(raw) as Path; return p && typeof p.modelId === 'string' ? p : null; } catch { return null; } } function writeLastSelection(p: Path) { try { sessionStorage.setItem(LAST_KEY, JSON.stringify(p)); } catch { /* 忽略存储不可用 */ } } function KbBadge({ n, tokens }: { n: number; tokens: ThemeTokens }) { if (n === 0) return null; return ( {n} ); } function DetailPanel({ node, onOpenKnowledge, onSelect, onSelectMethod, }: { node: { kind: 'model'; node: FeatureModel } | { kind: 'process'; node: FeatureProcess } | { kind: 'method'; node: FeatureMethod } | null; onOpenKnowledge?: (role: RoleKey, chunkId: string) => void; onSelect: (p: Path) => void; onSelectMethod: (m: FeatureMethod) => void; }) { const { tokens } = useTheme(); const label: React.CSSProperties = { fontSize: 12, fontWeight: 700, color: tokens.textMuted, letterSpacing: '0.06em' }; const kv: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 10 }; if (!node) { return (
在左侧特征树选择一个节点
); } const { kind, node: n } = node; const tag = kind === 'model' ? '机型' : kind === 'process' ? '工艺' : '生产方法'; const tagColor = kind === 'model' ? tokens.accent : kind === 'process' ? tokens.info : tokens.success; const title = n.label; const subtitle = kind === 'method' ? `${(n as FeatureMethod).modelId} / ${(n as FeatureMethod).processId}` : kind === 'process' ? (n as FeatureProcess).modelId : ''; const kbList = kind === 'model' ? (n as FeatureModel).kbRefs : kind === 'process' ? (n as FeatureProcess).kbRefs : (n as FeatureMethod).kbRefs; return (
{tag} {title} {subtitle && ( {subtitle} )} {kind === 'method' && ( )}
{kind === 'method' ? : ( <> {kind === 'model' && (
工艺 {(n as FeatureModel).processes.length} 个
{(n as FeatureModel).processes.map(p => ( ))}
)} {kind === 'process' && (
生产方法 {(n as FeatureProcess).methods.length} 个
{(n as FeatureProcess).methods.map(m => ( ))}
)} )}
); } function MethodStats({ method, tokens }: { method: FeatureMethod; tokens: ThemeTokens }) { return (
0 ? tokens.warning : tokens.textMuted, background: method.realCount > 0 ? tokens.warningBg : tokens.panelBgAlt, border: `1px solid ${method.realCount > 0 ? `${tokens.warning}44` : tokens.border}`, fontVariantNumeric: 'tabular-nums', }}>真实知识 {method.realCount} 示例 {method.exampleCount} 共 {method.summary.length} 行
); } /* ── 生产方法详情:问题 / 原因 / 对策 / 角色 总结表 ───────────────────── */ function MethodDetail({ method, tokens, label, onOpenKnowledge, onSelectMethod, }: { method: FeatureMethod; tokens: ThemeTokens; label: React.CSSProperties; onOpenKnowledge?: (role: RoleKey, chunkId: string) => void; onSelectMethod: (m: FeatureMethod) => void; }) { const hasExample = method.exampleCount > 0; const hasReal = method.realCount > 0; const siblings = (() => { const model = getFeatureTree().models.find(m => m.id === method.modelId); const proc = model?.processes.find(p => p.id === method.processId); return proc?.methods.filter(m => m.id !== method.id) ?? []; })(); return ( <> {hasExample && (
示例 {hasReal ? `有 ${method.exampleCount} 行是示例补齐(不是知识库原文),其余来自知识库切片。` : `该生产方法暂无知识库切片,以下 ${method.exampleCount} 行按方法模板生成,仅用于演示结构,不作为知识事实。`}
)}
{['角色', '问题', '原因', '对策', '来源'].map((h, i) => ( ))} {method.summary.map((row, i) => ( ))}
{h}
{method.refs.length > 0 && (
关联数据 {method.refs.length} 项
{method.refs.map((r, i) => ( {r.objKey} {r.instanceId ? ` · ${r.instanceId}` : ''} ))}
)}
{siblings.length > 0 && (
同工艺其他方法 {siblings.length} 个
{siblings.map(m => ( ))}
)} ); } const kvBlock: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 10 }; const chunkText = (role: RoleKey, chunkId: string) => roleDocs.find(d => d.role === role)?.chunks.find(c => c.id === chunkId)?.text ?? ''; /* 角色覆盖:一眼看出该方法有哪些角色在管、哪些还空着 */ function RoleCoverage({ method, tokens, label }: { method: FeatureMethod; tokens: ThemeTokens; label: React.CSSProperties }) { const roles: RoleKey[] = ['PE', 'IE', 'QE', 'ME']; return (
角色覆盖 {roles.filter(r => method.summary.some(x => x.role === r)).length} / 4 角色已挂载
{roles.map(role => { const rows = method.summary.filter(r => r.role === role); const real = rows.filter(r => r.source.kind === 'kb').length; const example = rows.length - real; const empty = rows.length === 0; return (
{role} {ROLE_FULL[role]} {empty ? '未覆盖' : `${rows.length} 行`}
{empty ? 无知识行 : <>真实 {real}示例 {example}}
); })}
); } /* 知识原文节选:表格是提炼行,这里保留可核对的原文 */ function SourceExcerpts({ method, tokens, label, onOpenKnowledge, }: { method: FeatureMethod; tokens: ThemeTokens; label: React.CSSProperties; onOpenKnowledge?: (role: RoleKey, chunkId: string) => void; }) { const rows = method.summary.filter(r => r.source.kind === 'kb'); if (rows.length === 0) { const checklist: [RoleKey, string][] = [ ['PE', '工艺参数卡 / DFM 检查表'], ['IE', 'SOP 与标准节拍 / 工装方案'], ['QE', '检验标准 / 抽检频次'], ['ME', '设备参数卡 / 点检表'], ]; return (
该生产方法还没有知识库切片
上表 {method.exampleCount} 行全部是示例。补齐路径:① 在知识库上传该方法的 SOP / 检验标准; ② 给切片标注「所属特征树」;③ 回到这里即可换成带来源的真实总结。
{checklist.map(([role, items]) => (
{role} {items}
))}
); } return (
知识原文节选 {rows.length} 条 点卡片回到知识库切片
{rows.map(row => { if (row.source.kind !== 'kb') return null; const text = chunkText(row.role, row.source.chunkId); return ( ); })}
); } function SummaryTableRow({ row, tokens, zebra, onOpenKnowledge, }: { row: MethodSummaryRow; tokens: ThemeTokens; zebra: boolean; onOpenKnowledge?: (role: RoleKey, chunkId: string) => void; }) { const isKb = row.source.kind === 'kb'; const cell: React.CSSProperties = { padding: '8px 9px', verticalAlign: 'top', fontSize: 12.5, lineHeight: 1.6, color: tokens.text, borderBottom: `1px solid ${tokens.borderSub}`, wordBreak: 'break-word', }; return (
{row.role} {ROLE_LABEL[row.role]}
{row.problem} {row.cause} {row.action} {isKb ? ( ) : ( 示例 )} ); } function ContextDetails({ title, attrs, tokens }: { title: string; attrs: { label: string; value: string }[]; tokens: ThemeTokens }) { if (attrs.length === 0) return null; return (
{title} · {attrs.length} 项
{attrs.map(a => (
{a.label} {a.value}
))}
); } function AttrGrid({ attrs, tokens, label }: { attrs: { label: string; value: string }[]; tokens: ThemeTokens; label: React.CSSProperties }) { if (attrs.length === 0) return null; return (
属性 {attrs.length} 项
{attrs.map(a => (
{a.label}
{a.value}
))}
); } function KbList({ list, onOpenKnowledge, tokens, label, }: { list: KbRef[]; onOpenKnowledge?: (role: RoleKey, chunkId: string) => void; tokens: ThemeTokens; label: React.CSSProperties; }) { if (list.length === 0 || !onOpenKnowledge) return null; return (
知识挂载 {list.length} 条
{list.map((r, i) => ( ))}
); } const chipBtn = (tokens: ThemeTokens): React.CSSProperties => ({ display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer', padding: '2px 7px', borderRadius: 6, fontSize: 12, color: tokens.textSub, background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, });