import { useState } from "react"; import { useNavigate } from "react-router-dom"; import toast from "react-hot-toast"; import { Button } from "@/shadcn-bridge/heroui/button"; import { Input } from "@/shadcn-bridge/heroui/input"; import { Card, CardBody, CardHeader } from "@/shadcn-bridge/heroui/card"; import { title } from "@/components/primitives"; import { updatePassword } from "@/api"; import DefaultLayout from "@/layouts/default"; import { safeLogout } from "@/utils/logout"; interface PasswordForm { newUsername: string; currentPassword: string; newPassword: string; confirmPassword: string; } export default function ChangePasswordPage() { const [form, setForm] = useState({ newUsername: "", currentPassword: "", newPassword: "", confirmPassword: "", }); const [loading, setLoading] = useState(false); const [errors, setErrors] = useState>({}); const navigate = useNavigate(); const validateForm = (): boolean => { const newErrors: Partial = {}; if (!form.newUsername.trim()) { newErrors.newUsername = "请输入新用户名"; } else if (form.newUsername.length < 3) { newErrors.newUsername = "用户名长度至少3位"; } else if (form.newUsername.length > 20) { newErrors.newUsername = "用户名长度不能超过20位"; } if (!form.currentPassword.trim()) { newErrors.currentPassword = "请输入当前密码"; } if (!form.newPassword.trim()) { newErrors.newPassword = "请输入新密码"; } else if (form.newPassword.length < 6) { newErrors.newPassword = "新密码长度不能少于6位"; } else if (form.newPassword.length > 20) { newErrors.newPassword = "新密码长度不能超过20位"; } if (!form.confirmPassword.trim()) { newErrors.confirmPassword = "请再次输入新密码"; } else if (form.confirmPassword !== form.newPassword) { newErrors.confirmPassword = "两次输入密码不一致"; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleInputChange = (field: keyof PasswordForm, value: string) => { setForm((prev) => ({ ...prev, [field]: value })); if (errors[field]) { setErrors((prev) => ({ ...prev, [field]: undefined })); } }; const handleSubmit = async () => { if (!validateForm()) return; setLoading(true); try { const response = await updatePassword(form); if (response.code === 0) { toast.success(response.msg || "账号密码修改成功"); // 使用 toast 确认对话框的替代方案 setTimeout(() => { toast.success("即将跳转到登陆页面,请重新登录"); setTimeout(() => { logout(); }, 1000); }, 1000); } else { toast.error(response.msg || "账号密码修改失败"); } } catch { toast.error("修改账号密码时发生错误"); } finally { setLoading(false); } }; const logout = () => { safeLogout(); navigate("/"); }; const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !loading) { handleSubmit(); } }; return (

安全提醒

检测到您使用的是默认账号密码,为了您的账户安全,请立即修改

handleInputChange("newUsername", e.target.value) } onKeyDown={handleKeyPress} /> handleInputChange("currentPassword", e.target.value) } onKeyDown={handleKeyPress} /> handleInputChange("newPassword", e.target.value) } onKeyDown={handleKeyPress} /> handleInputChange("confirmPassword", e.target.value) } onKeyDown={handleKeyPress} />
⚠️ 注意:修改账号密码后需要重新登录
); }