import { useCallback, useEffect, useRef, useState } from 'react'; import { Alert, App, Button, Dropdown, Form, Input, Select, Spin, Tooltip, } from 'antd'; import { AppstoreOutlined, ApartmentOutlined, BgColorsOutlined, CheckOutlined, DatabaseOutlined, DownOutlined, DeploymentUnitOutlined, KeyOutlined, LineChartOutlined, LoadingOutlined, LogoutOutlined, RobotOutlined, SettingOutlined, TeamOutlined, ToolOutlined, UserOutlined, } from '@ant-design/icons'; import { ApiError, api } from './api'; import type { AuthUser, QueryParams } from './types'; import { workspaceThemes, type WorkspaceThemeId } from './ui-themes'; import { readableSelectPopup } from './readableSelectPopup'; import PersonalAccount, { type AccountTab } from './PersonalAccount'; import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages'; export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access'; const pageNames: Record = { overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总', basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验', rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计', }; const pageFromLocation = (): PageKey => { const key = new URLSearchParams(window.location.search).get('page'); if (key === 'headers' || key === 'releases' || key === 'imports') return 'sources'; if (key === 'scrap') return 'product'; if (key === 'basis') return 'overall'; return key && key in pageNames ? key as PageKey : 'overall'; }; type TopResultRef = { kind: 'TOP'; resultId: string; releaseId: string }; function encodeContext(value: { query: QueryParams; resultRef?: TopResultRef }): string { const bytes = new TextEncoder().encode(JSON.stringify(value)); let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); } const navGroups = [ { label: '质量查询', items: [ ['overall', '总体汇总', AppstoreOutlined], ['department', '产业部汇总', ApartmentOutlined], ['group', '产业部-业务分组', DeploymentUnitOutlined], ['product', '产品汇总', DatabaseOutlined], ] as const, }, { label: '分析工作台', items: [ ['analysis', '智能分析', RobotOutlined], ] as const, }, { label: '数据中心', items: [ ['sources', '数据接入', DatabaseOutlined], ] as const, }, { label: '规则与管理', items: [ ['rules', '计算规则', SettingOutlined], ['mappings', '对应关系', ToolOutlined], ['masterData', '基础数据', DatabaseOutlined], ['tasks', '任务与监控', LineChartOutlined], ['access', '权限与审计', KeyOutlined], ] as const, }, ]; function shownDepartment(value: string): string { return value === '质量管理部' ? '质量中心' : value; } type QualityWorkspaceProps = { appearance: (typeof workspaceThemes)[number]; onAppearanceChange: (themeId: WorkspaceThemeId) => void; }; export default function QualityWorkspace({ appearance, onAppearanceChange }: QualityWorkspaceProps) { const { message } = App.useApp(); const [page, setPage] = useState(pageFromLocation); const [user, setUser] = useState(null); const [sessionLoading, setSessionLoading] = useState(true); const [sessionError, setSessionError] = useState(''); const [accountTab, setAccountTab] = useState(null); const workspaceNavigation = useRef(null); useEffect(() => { const syncFromLocation = () => { const url = new URL(window.location.href); const currentPage = url.searchParams.get('page') || ''; if (['headers', 'releases', 'scrap', 'basis', 'imports'].includes(currentPage)) { if (currentPage === 'imports') url.searchParams.set('showImportHistory', '1'); url.searchParams.set('page', currentPage === 'basis' ? 'overall' : currentPage === 'scrap' ? 'product' : 'sources'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } if (workspaceNavigation.current) workspaceNavigation.current.syncLocation(); else setPage(pageFromLocation()); }; syncFromLocation(); window.addEventListener('popstate', syncFromLocation); return () => window.removeEventListener('popstate', syncFromLocation); }, []); useEffect(() => { let alive = true; (async () => { try { await api.refreshCsrf(); const current = await api.me(); if (alive) setUser(current); } catch (error) { if (error instanceof ApiError && error.status === 401) { if (alive) setUser(null); } else if (alive) { setSessionError(error instanceof Error ? error.message : '无法连接服务'); } } finally { if (alive) setSessionLoading(false); } })(); return () => { alive = false; }; }, []); const navigate = (next: PageKey, query?: QueryParams, resultRef?: TopResultRef) => { if (workspaceNavigation.current) { workspaceNavigation.current.navigate(next, query, resultRef); return; } const url = new URL(window.location.href); if (next === 'imports') { next = 'sources'; url.searchParams.set('showImportHistory', '1'); } else url.searchParams.delete('showImportHistory'); url.searchParams.set('page', next); if (next !== 'analysis' || query || resultRef) { url.searchParams.delete('sessionId'); url.searchParams.delete('turnId'); } if (query) url.searchParams.set('context', encodeContext({ query, ...(resultRef ? { resultRef } : {}) })); else url.searchParams.delete('context'); window.history.pushState({}, '', `${url.pathname}${url.search}${url.hash}`); setPage(next); }; const handleUnauthorized = useCallback((error: unknown) => { if (error instanceof ApiError && error.status === 401) { setUser(null); void api.refreshCsrf().catch(() => undefined); return true; } return false; }, []); const logout = async () => { try { await api.logout(); setAccountTab(null); setUser(null); } catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); } }; if (sessionLoading) return
} /> 正在连接质量数据分析平台…
; if (sessionError) return
服务暂不可用

{sessionError}

; if (!user) return ; return (
质量分析/{pageNames[page]}
({ key: theme.id, label: {theme.name}{theme.id === appearance.id && }, })), onClick: ({ key }) => onAppearanceChange(key as WorkspaceThemeId), }} > {user.departments.length > 0 && {user.departments.map(shownDepartment).join('、')}} , label: '个人资料' }, { key: 'password', icon: , label: '修改密码' }, { type: 'divider' }, { key: 'logout', icon: , label: '退出登录' }, ], onClick: ({ key }) => { if (key === 'logout') void logout(); else setAccountTab(key as AccountTab); } }}>
质量数据分析平台 {...readableSelectPopup} aria-label="页面导航" value={page} onChange={value => navigate(value)} options={[ ...navGroups.map(group => ({ label: group.label, options: group.items.map(([value, label]) => ({ value, label })) })), ]} />
setAccountTab(null)} onUserChange={setUser} onUnauthorized={handleUnauthorized} onLogout={logout} />
); } function LoginPage({ onSuccess }: { onSuccess: (user: AuthUser) => void }) { const [busy, setBusy] = useState(false); const [loginError, setLoginError] = useState(''); const [form] = Form.useForm<{ username: string; password: string }>(); const submit = async (values: { username: string; password: string }) => { setBusy(true); setLoginError(''); try { const result = await api.login(values.username, values.password); onSuccess(result.user); } catch (error) { setLoginError(error instanceof Error ? error.message : '登录失败,请检查账号后重试'); } finally { setBusy(false); } }; return (

登录工作台

setLoginError('')} requiredMark={false} name="quality-center-login"> {loginError && }
); }