"use client";
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { UserPlus } from "lucide-react";
import { apiRegister, apiMe, apiOperations } from "@/lib/api";
import { hasAuthCookieHint } from "@/lib/cookies";
/** 关闭注册时的说明页(提交失败切到关闭态时复用) */
export function RegisterClosedPanel({ notice }: { notice: string }) {
return (
暂不开放注册
{notice || "站点当前已关闭新用户注册,已有账号可直接登录。"}
去登录
);
}
export default function RegisterClient({
verifyEmail: initialVerifyEmail,
registerNotice,
}: {
verifyEmail: boolean;
registerNotice: string;
}) {
const router = useRouter();
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [registerClosed, setRegisterClosed] = useState(false);
const [code, setCode] = useState("");
const [notice, setNotice] = useState(registerNotice);
const [sending, setSending] = useState(false);
const [sentMessage, setSentMessage] = useState("");
// 重发倒计时(秒);>0 期间按钮锁定不可点
const [countdown, setCountdown] = useState(0);
const countdownTimer = useRef | null>(null);
const verifyEmail = initialVerifyEmail;
// 卸载时清理倒计时,避免泄漏
useEffect(() => {
return () => {
if (countdownTimer.current) clearInterval(countdownTimer.current);
};
}, []);
const startCountdown = () => {
if (countdownTimer.current) clearInterval(countdownTimer.current);
setCountdown(60);
countdownTimer.current = setInterval(() => {
setCountdown((c) => {
if (c <= 1) {
if (countdownTimer.current) clearInterval(countdownTimer.current);
countdownTimer.current = null;
return 0;
}
return c - 1;
});
}, 1000);
};
// 已登录用户不必再注册,直接回首页
useEffect(() => {
if (!hasAuthCookieHint()) return;
apiMe()
.then((res) => {
if (res.user) router.replace("/");
})
.catch(() => {});
}, [router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
setLoading(true);
try {
const res = await apiRegister(username, email, password, code);
if (res.user) {
router.push("/");
router.refresh();
} else if (res.id) {
router.push("/login");
} else {
const msg = res.error || "注册失败";
if (msg.includes("关闭注册")) {
// 热关闭:补拉提示文案后切关闭态
try {
const s = await apiOperations<{ register_notice: string }>("/api/site-state");
setNotice(s.register_notice || notice);
} catch {
/* 沿用 SSR 提示 */
}
setRegisterClosed(true);
}
setError(msg);
}
} finally {
setLoading(false);
}
};
if (registerClosed) {
return ;
}
return (
);
}