Files
ai-platform/src/modules/jieya-ibp/components/DigitalStaffPanel.tsx
T
2026-10-18 15:27:02 +08:00

452 lines
23 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from 'react';
import { ArrowLeft, Bot, Check, ChevronDown, MessagesSquare, Radar, Target, Users } from 'lucide-react';
import PanelShell, { PanelBody, CountBadge } from './layout/PanelShell';
import { useTheme } from '../context/ThemeContext';
import { useText } from '../i18n/useText';
import type { DigitalStaff, MetricNode } from '../data/sqlite';
import { customTeam, presetTeams } from '../lib/teams';
import type { ExpertTeam } from '../lib/teams';
interface Props {
expanded: boolean;
onToggle: () => void;
staff: DigitalStaff[];
byCode: Map<string, MetricNode>;
selected: string;
onViewMetric: (code: string) => void;
onWake: (s: DigitalStaff) => void;
/** 专家团:当前已就位的团队 + 组建回调 */
activeTeam: ExpertTeam | null;
onConvene: (t: ExpertTeam) => void;
}
type Status = DigitalStaff['status'];
export default function DigitalStaffPanel({
expanded, onToggle, staff, byCode, selected, onViewMetric, onWake, activeTeam, onConvene,
}: Props) {
const { tokens } = useTheme();
const { t } = useText();
const [filter, setFilter] = useState<Status | 'all'>('all');
const [open, setOpen] = useState<string | null>('METRIX');
const [view, setView] = useState<'staff' | 'team'>('staff'); // 数字员工列表 / 专家团组建
const [selCodes, setSelCodes] = useState<string[]>([]); // 自由勾选的成员(首位为牵头)
const [presetKey, setPresetKey] = useState<string | null>(null); // 当前选中的预设团
const [tick, setTick] = useState(0);
const scrollRef = useRef<HTMLDivElement | null>(null);
const hoverRef = useRef(false); // 鼠标进入列表即暂停,方便点卡
const coolRef = useRef(0); // 滚轮手动滚动后的冷却截止时刻
const statusMeta = (s: Status) => ({
working: { label: t.staff.busy, color: tokens.accent },
idle: { label: t.staff.idle, color: tokens.textMuted },
alert: { label: t.staff.alert, color: tokens.danger },
offline: { label: t.staff.offline, color: tokens.warning },
}[s]);
const list = useMemo(() => (filter === 'all' ? staff : staff.filter(s => s.status === filter)), [staff, filter]);
const online = staff.filter(s => s.status !== 'offline').length;
const totalTasks = staff.reduce((a, s) => a + s.tasks_today, 0);
const avgConf = staff.filter(s => s.confidence > 0).reduce((a, s, _i, arr) => a + s.confidence / arr.length, 0);
const escalations = staff.filter(s => s.status === 'alert').length;
// 动作轮播:只轮播在岗员工,避免"停用"卡片抢镜
const feed = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
useEffect(() => {
if (feed.length < 2) return;
const id = setInterval(() => setTick(v => (v + 1) % feed.length), 3400);
return () => clearInterval(id);
}, [feed.length]);
const active = feed.length ? feed[tick % feed.length] : null;
// 鼠标进入 / 滚轮手动滚动时暂停自动滚动,避免和用户抢滚动条
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const onWheel = () => { coolRef.current = performance.now() + 2200; };
const onEnter = () => { hoverRef.current = true; };
const onLeave = () => { hoverRef.current = false; };
el.addEventListener('wheel', onWheel, { passive: true });
el.addEventListener('pointerenter', onEnter);
el.addEventListener('pointerleave', onLeave);
return () => {
el.removeEventListener('wheel', onWheel);
el.removeEventListener('pointerenter', onEnter);
el.removeEventListener('pointerleave', onLeave);
};
}, []);
// 自动滚动:营造"员工一个个在干活"的现场感;到底停留 1.4s 后回顶循环。
// pos 是浮点累加器:26px/s 摊到 120Hz 每帧只有 0.22px,直接读改写 scrollTop 会被量化舍入吞掉而停摆
useEffect(() => {
let raf = 0;
let last = performance.now();
let pos = scrollRef.current ? scrollRef.current.scrollTop : 0;
let phase: 'down' | 'holdB' | 'up' | 'holdT' = 'down';
let until = 0;
const step = (now: number) => {
raf = requestAnimationFrame(step);
const el = scrollRef.current;
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
if (!el || el.scrollHeight <= el.clientHeight + 4) return;
// 被门控暂停期间以真实 scrollTop 为准(用户可能滚轮动过),恢复时从那里续跑
if (hoverRef.current || now < coolRef.current) { pos = el.scrollTop; return; }
if (phase === 'down') {
if (pos + el.clientHeight >= el.scrollHeight - 2) { phase = 'holdB'; until = now + 1400; pos = el.scrollTop; }
else { pos += 26 * dt; el.scrollTop = pos; }
} else if (phase === 'holdB') {
pos = el.scrollTop;
if (now >= until) phase = 'up';
} else if (phase === 'up') {
pos -= pos * Math.min(1, dt * 5);
el.scrollTop = pos;
if (pos <= 0.5) { el.scrollTop = 0; pos = 0; phase = 'holdT'; until = now + 500; }
} else {
pos = el.scrollTop;
if (now >= until) phase = 'down';
}
};
raf = requestAnimationFrame(step);
return () => cancelAnimationFrame(raf);
}, []);
const chip = (key: Status | 'all', label: string, color?: string) => {
const on = filter === key;
return (
<button
key={key}
onClick={() => setFilter(key)}
style={{
fontSize: 11.5, padding: '2px 7px', borderRadius: 9, cursor: 'pointer', lineHeight: '17px', whiteSpace: 'nowrap' as const,
background: on ? `${color ?? tokens.accent}22` : 'transparent',
color: on ? (color ?? tokens.accent) : tokens.textMuted,
border: `1px solid ${on ? `${color ?? tokens.accent}55` : tokens.border}`,
}}
>{label}</button>
);
};
const presets = useMemo(() => presetTeams(), []);
// 预设团语义色 → 主题 token,让五张卡片有各自的色彩识别(不硬编码色值)
const toneColor = (tone: ExpertTeam['tone']) =>
({ success: tokens.success, danger: tokens.danger, info: tokens.info, warning: tokens.warning, accent: tokens.accent }[tone] ?? tokens.accent);
const nameOfStaff = (x: DigitalStaff) => (x.name_zh);
// 选中一个预设团:填充成员并停留在组建视图,便于直接发起或再微调
const pickPreset = (tm: ExpertTeam) => { setPresetKey(tm.id); setSelCodes(tm.memberCodes); };
// 勾选/取消一个智能体:脱离预设,转为自定义团
const toggleCode = (code: string) => {
setPresetKey(null);
setSelCodes(prev => (prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]));
};
const convene = () => {
if (selCodes.length < 2) return;
const preset = presetKey ? presets.find(x => x.id === presetKey) : null;
const tm = preset ?? customTeam(selCodes);
if (tm) onConvene(tm);
};
const openTeamView = () => { if (!expanded) onToggle(); setView('team'); };
return (
<PanelShell
side="right" expanded={expanded} onToggle={onToggle}
widthCollapsed={268} widthExpanded={468}
icon={expanded ? (view === 'team' ? <Users size={15} /> : <Bot size={15} />) : undefined}
title={view === 'team' ? t.team.panel : t.staff.title}
badge={view === 'team' ? <CountBadge n={selCodes.length} /> : <CountBadge n={`${online}/${staff.length}`} />}
extra={
<>
<button
onClick={() => (view === 'team' ? setView('staff') : openTeamView())}
title={t.team.entry}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
width: 22, height: 22, borderRadius: 5, cursor: 'pointer',
color: view === 'team' ? tokens.onAccent : tokens.accent,
background: view === 'team' ? tokens.accent : `${tokens.accent}1f`,
border: `1px solid ${view === 'team' ? tokens.accent : `${tokens.accent}55`}`,
}}
>
<Users size={12} />
</button>
</>
}
animClass="space-animate-right"
>
{view === 'staff' && (
<>
<div style={{ display: 'flex', gap: 3, flexWrap: 'wrap', marginBottom: 8, flex: '0 0 auto' }}>
{chip('all', t.staff.filterAll)}
{chip('working', t.staff.busy, tokens.accent)}
{chip('idle', t.staff.idle)}
{chip('alert', t.staff.alert, tokens.danger)}
{chip('offline', t.staff.offline, tokens.warning)}
</div>
<div style={{
display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, marginBottom: 8, flex: '0 0 auto',
background: tokens.border, border: `1px solid ${tokens.border}`, borderRadius: 8, overflow: 'hidden',
}}>
{[
{ k: t.staff.online, v: String(online) },
{ k: t.staff.tasks, v: String(totalTasks) },
{ k: t.staff.confidence, v: `${avgConf.toFixed(0)}%` },
{ k: t.staff.alert, v: String(escalations), warn: escalations > 0 },
].map(c => (
<div key={c.k} style={{ background: tokens.panelBgAlt, padding: '5px 4px', textAlign: 'center' }}>
<div style={{ fontSize: 17, fontWeight: 800, color: c.warn ? tokens.danger : tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.15 }}>{c.v}</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 1 }}>{c.k}</div>
</div>
))}
</div>
<PanelBody ref={scrollRef}>
{list.length === 0 && (
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>{t.staff.emptyFilter}</div>
)}
{list.map((s, i) => {
const meta = statusMeta(s.status);
const isOpen = open === s.code;
const bound = byCode.get(s.bound_metric);
const nm = (n: MetricNode | undefined) => (n ? (n.name_zh) : s.bound_metric);
return (
<div
key={s.code}
className="card-in"
style={{
animationDelay: `${i * 45}ms`,
border: `1px solid ${s.status === 'alert' ? `${tokens.danger}66` : isOpen ? tokens.borderAccent : tokens.border}`,
background: isOpen ? tokens.cardBg : tokens.panelBgAlt,
borderRadius: 10, marginBottom: 7, overflow: 'hidden',
}}
>
<div
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 9px', cursor: 'pointer' }}
onClick={() => {
// 收起态没有详情空间:先展开面板再开详情,避免"点了没反应"
if (!expanded) { onToggle(); setOpen(s.code); }
else setOpen(isOpen ? null : s.code);
}}
>
<span
className={s.status === 'working' || s.status === 'alert' ? 'dot-blink' : undefined}
style={{ width: 7, height: 7, borderRadius: 7, background: meta.color, flex: '0 0 7px', boxShadow: `0 0 7px ${meta.color}88` }}
/>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
<span
title={s.name_zh}
style={{ fontSize: 14.5, fontWeight: 700, color: tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}
>
{s.name_zh}
</span>
{/* 收起态 268px 放不下「9 字名 + code」,code 只在展开态显示 */}
{expanded && (
<span style={{ fontSize: 10, color: tokens.textMuted, fontFamily: 'ui-monospace, monospace' }}>{s.code}</span>
)}
</div>
<div style={{ fontSize: 11.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{s.role_zh}
</div>
</div>
<div style={{ textAlign: 'right', flex: '0 0 auto' }}>
<div style={{ fontSize: 11.5, color: meta.color, fontWeight: 600 }}>{meta.label}</div>
<div style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.tasks_today} {t.staff.tasks}</div>
</div>
<ChevronDown size={13} style={{ color: tokens.textMuted, transform: `rotate(${isOpen ? 180 : 0}deg)`, transition: 'transform 0.2s', flex: '0 0 13px' }} />
</div>
<div style={{ padding: '0 9px 6px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
<div style={{ flex: 1, height: 3, borderRadius: 3, background: `${tokens.border}`, overflow: 'hidden' }}>
<div style={{ width: `${s.load_pct}%`, height: '100%', background: meta.color, transition: 'width 0.4s ease' }} />
</div>
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', width: 34, textAlign: 'right' }}>{s.load_pct}%</span>
</div>
{expanded && (
<div style={{ fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
<Radar size={9} style={{ verticalAlign: -1, marginRight: 3, color: meta.color }} />
{s.cur_zh}
</div>
)}
</div>
{isOpen && expanded && (
<div style={{ padding: '2px 9px 9px', borderTop: `1px dashed ${tokens.border}`, marginTop: 2 }}>
<Row label={t.staff.skills} value={s.skill_zh} tokens={tokens} text={tokens.textSub} />
<Row label={t.staff.success} value={`${s.success_rate}%`} tokens={tokens} text={tokens.text} mono />
<Row label={t.staff.confidence} value={`${s.confidence}%`} tokens={tokens} text={tokens.text} mono />
<Row label={t.staff.lastRun} value={s.last_run} tokens={tokens} text={tokens.textMuted} />
<Row label={t.staff.current} value={s.cur_zh} tokens={tokens} text={tokens.textSub} />
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
<button
onClick={() => onViewMetric(s.bound_metric)}
className="ghost-btn"
style={{
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
padding: '4px 6px', fontSize: 12, borderRadius: 7, cursor: 'pointer',
border: `1px solid ${selected === s.bound_metric ? tokens.accent : tokens.border}`,
color: tokens.accent, background: tokens.accentBg,
}}
>
<Target size={11} />{nm(bound)}
</button>
<button
onClick={() => onWake(s)}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
padding: '4px 10px', fontSize: 12, borderRadius: 7, cursor: 'pointer',
border: `1px solid ${tokens.accent}`, color: tokens.onAccent, background: tokens.accent,
opacity: s.status === 'offline' ? 0.45 : 1,
}}
>
<MessagesSquare size={11} />{t.staff.wake}
</button>
</div>
</div>
)}
</div>
);
})}
</PanelBody>
{active && (
<div style={{
flex: '0 0 auto', marginTop: 6, padding: '6px 9px', borderRadius: 9,
background: tokens.accentBg, border: `1px solid ${tokens.border}`,
display: 'flex', alignItems: 'center', gap: 7, minWidth: 0,
}}>
<Radar size={13} style={{ color: tokens.accent, flex: '0 0 13px' }} className="dot-blink" />
<div key={active.code} className="content-reveal" style={{ minWidth: 0 }}>
<div style={{ fontSize: 11.5, color: tokens.accent, fontWeight: 700 }}>
{active.name_zh} · {active.last_run}
</div>
<div style={{ fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{active.cur_zh}
</div>
</div>
</div>
)}
</>
)}
{view === 'team' && (
<div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, flex: 1, gap: 7 }}>
<button
onClick={() => setView('staff')}
className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 5, alignSelf: 'flex-start', fontSize: 12, color: tokens.textMuted, background: 'transparent', border: 'none', cursor: 'pointer', padding: '2px 4px', flex: '0 0 auto' }}
>
<ArrowLeft size={13} />{t.team.back}
</button>
<div style={{ flex: '0 0 auto' }}>
<div style={{ fontSize: 12, fontWeight: 700, color: tokens.textSub, letterSpacing: '0.02em' }}>{t.team.presetTitle}</div>
<div style={{ fontSize: 11, color: tokens.textMuted, marginTop: 2, lineHeight: 1.5 }}>{t.team.presetHint}</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: '0 0 auto' }}>
{presets.map(tm => {
const on = presetKey === tm.id;
const isActive = activeTeam?.id === tm.id;
const c = toneColor(tm.tone);
return (
<button
key={tm.id} onClick={() => pickPreset(tm)} className="ghost-btn"
style={{
textAlign: 'left', padding: '8px 10px', borderRadius: 10, cursor: 'pointer',
background: on ? `${c}17` : `linear-gradient(135deg, ${c}0f, ${tokens.panelBgAlt} 60%)`,
border: `1px solid ${on ? `${c}88` : `${c}30`}`,
boxShadow: on ? `0 0 0 1px ${c}33, 0 2px 12px ${c}22` : 'none',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<span style={{
width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center', flexShrink: 0,
background: `${c}1f`, border: `1px solid ${c}44`, color: c,
}}>
<Users size={12} />
</span>
<span style={{ fontSize: 13.5, fontWeight: 700, color: on ? c : tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tm.nameZh}</span>
<span style={{ fontSize: 10.5, color: c, marginLeft: 'auto', flexShrink: 0, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{tm.memberCodes.length} 位</span>
{isActive && <Check size={13} color={c} style={{ flexShrink: 0 }} />}
</div>
<div style={{ fontSize: 11, color: tokens.textMuted, marginTop: 4, lineHeight: 1.45, paddingLeft: 29 }}>{tm.topicZh}</div>
</button>
);
})}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginTop: 2 }}>
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.textSub }}>{t.team.customTitle}</span>
{selCodes.length > 0 && (
<button
onClick={() => { setSelCodes([]); setPresetKey(null); }}
className="ghost-btn"
style={{ marginLeft: 'auto', fontSize: 11, color: tokens.textMuted, background: 'transparent', border: 'none', cursor: 'pointer', padding: '1px 4px' }}
>{t.team.clearSel}</button>
)}
</div>
<div style={{ fontSize: 11, color: tokens.textMuted, lineHeight: 1.5, flex: '0 0 auto' }}>{t.team.customHint}</div>
<PanelBody>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{feed.map(x => {
const idx = selCodes.indexOf(x.code);
const on = idx >= 0;
return (
<button
key={x.code} onClick={() => toggleCode(x.code)}
style={{
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11.5, padding: '3px 8px', borderRadius: 16, cursor: 'pointer',
background: on ? `${tokens.accent}22` : 'transparent',
color: on ? tokens.accent : tokens.textSub,
border: `1px solid ${on ? `${tokens.accent}66` : tokens.border}`,
}}
>
{on && (
<span style={{ width: 14, height: 14, borderRadius: 4, background: tokens.accent, color: tokens.onAccent, display: 'grid', placeItems: 'center', fontSize: 9, fontWeight: 800, flexShrink: 0 }}>{idx + 1}</span>
)}
{nameOfStaff(x)}
</button>
);
})}
</div>
</PanelBody>
<button
onClick={convene} disabled={selCodes.length < 2}
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
padding: '9px 12px', borderRadius: 10, border: 'none', fontSize: 13, fontWeight: 700,
cursor: selCodes.length < 2 ? 'default' : 'pointer',
background: selCodes.length < 2 ? tokens.border : tokens.accent,
color: selCodes.length < 2 ? tokens.textMuted : tokens.onAccent,
boxShadow: selCodes.length >= 2 ? `0 2px 10px ${tokens.accent}40` : 'none',
}}
>
<Users size={14} />
{selCodes.length < 2 ? t.team.needTwo : t.team.conveneN.replace('{n}', String(selCodes.length))}
</button>
</div>
)}
</PanelShell>
);
}
function Row({ label, value, tokens, text, mono }: {
label: string; value: string; tokens: { textMuted: string }; text: string; mono?: boolean;
}) {
return (
<div style={{ display: 'flex', gap: 8, fontSize: 11.5, lineHeight: '19px', minWidth: 0 }}>
<span style={{ color: tokens.textMuted, flex: '0 0 64px' }}>{label}</span>
<span style={{
color: text, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
...(mono ? { fontFamily: 'ui-monospace, monospace', fontVariantNumeric: 'tabular-nums' } : {}),
}}>{value}</span>
</div>
);
}