import { useEffect, useRef, useState } from 'react'; import { Alert, App, Button, Descriptions, Form, Input, Modal, Tabs } from 'antd'; import { api } from './api'; import type { AuthUser } from './types'; import { ROLE_LABELS as roles } from './userRoles'; export type AccountTab = 'profile' | 'password'; type PasswordValues = { currentPassword: string; newPassword: string; confirmation: string }; export default function PersonalAccount({ user, tab, onClose, onUserChange, onUnauthorized, onLogout }: { user: AuthUser; tab: AccountTab | null; onClose: () => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean; onLogout: () => Promise; }) { const { message } = App.useApp(); const [form] = Form.useForm(); const [activeTab, setActiveTab] = useState('profile'); const [busy, setBusy] = useState(false); const savingRef = useRef(false); const [error, setError] = useState(''); const forced = user.forcePasswordChange === true; const open = tab !== null || forced; useEffect(() => { if (open) { setActiveTab(forced ? 'password' : tab || 'profile'); setError(''); form.resetFields(); } }, [open, tab, forced, form]); const save = async (values: PasswordValues) => { if (savingRef.current) return; savingRef.current = true; setBusy(true); setError(''); try { await api.changePassword(values.currentPassword, values.newPassword); form.resetFields(); onUserChange({ ...user, forcePasswordChange: false }); onClose(); message.success('密码已修改,下次登录请使用新密码'); } catch (failure) { if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试'); } finally { savingRef.current = false; setBusy(false); } }; return { if (!busy && !forced) onClose(); }} destroyOnHidden> {forced && } setActiveTab(key as AccountTab)} items={[ { key: 'profile', label: '个人资料', disabled: forced || busy, children: name === '质量管理部' ? '质量中心' : name).join('、') || '未设置' }, { key: 'roles', label: '角色', children: user.roles.map(role => roles[role] || role).join('、') || '未设置' }, ]} /> }, { key: 'password', label: '修改密码', children:
setError('')} disabled={busy}> ({ validator: (_, value: string) => { if (value && new TextEncoder().encode(value).length > 72) return Promise.reject(new Error('新密码过长,请缩短后重试')); if (value && value === getFieldValue('currentPassword')) return Promise.reject(new Error('新密码不能与当前密码相同')); return Promise.resolve(); } }), ]}> ({ validator: (_, value: string) => !value || value === getFieldValue('newPassword') ? Promise.resolve() : Promise.reject(new Error('两次输入的新密码不一致')) }), ]}> {error && }
{forced ? : }
}, ]} />
; }