import { ArrowRight as ActionArrowRight } from '@/components/common/icons/ActionIcons';
import React, {
useContext,
useEffect,
useRef,
useState,
useCallback,
useMemo,
lazy,
Suspense,
} from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
API,
getLogo,
showError,
showInfo,
showSuccess,
getSystemName,
finishLogin as runLoginFlow,
onDiscordOAuthClicked,
onGitHubOAuthClicked,
onLinuxDOOAuthClicked,
onOIDCClicked,
onWeChatOpenOAuthClicked,
} from '../../helpers';
import Turnstile from 'react-turnstile';
import { Button, Checkbox, Form, Icon, Modal } from '@/components/ui';
import { Text } from '@/components/ui';
import {
IconGithubLogo,
IconMail,
IconUser,
IconLock,
IconKey,
} from '@/components/ui/icons';
import OIDCIcon from '../common/logo/OIDCIcon';
import LinuxDoIcon from '../common/logo/LinuxDoIcon';
import WeChatIcon from '../common/logo/WeChatIcon';
import DiscordIcon from '../common/logo/DiscordIcon';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { useTranslation } from 'react-i18next';
import AuthBackground from '../common/AuthBackground';
import GlassCard from './GlassCard';
import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs';
import AuthDivider from './AuthDivider';
import { Shield, Smartphone, QrCode } from 'lucide-react';
import AgreementModal from './LazyAgreementModal';
import {
isMiniProgramWebView,
withMiniProgramLogins,
} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin'));
// 检测是否在微信内浏览器中
const isWeChatBrowser = () => {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf('micromessenger') !== -1;
};
// 检测是否是移动设备
const isMobileDevice = () => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
};
const RegisterForm = () => {
let navigate = useNavigate();
const { t } = useTranslation();
const [inputs, setInputs] = useState({
username: '',
password: '',
password2: '',
email: '',
verification_code: '',
wechat_verification_code: '',
});
const { username, password, password2 } = inputs;
const [, userDispatch] = useContext(UserContext);
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
const [turnstileToken, setTurnstileToken] = useState('');
const [showWeChatLoginModal, setShowWeChatLoginModal] = useState(false);
const [showEmailRegister, setShowEmailRegister] = useState(false);
const [wechatLoading, setWechatLoading] = useState(false);
const [wechatOpenLoading, setWechatOpenLoading] = useState(false);
const [githubLoading, setGithubLoading] = useState(false);
const [discordLoading, setDiscordLoading] = useState(false);
const [oidcLoading, setOidcLoading] = useState(false);
const [linuxdoLoading, setLinuxdoLoading] = useState(false);
const [emailRegisterLoading, setEmailRegisterLoading] = useState(false);
const [registerLoading, setRegisterLoading] = useState(false);
const [verificationCodeLoading, setVerificationCodeLoading] = useState(false);
const [otherRegisterOptionsLoading, setOtherRegisterOptionsLoading] =
useState(false);
const [wechatCodeSubmitLoading, setWechatCodeSubmitLoading] = useState(false);
const [disableButton, setDisableButton] = useState(false);
const [countdown, setCountdown] = useState(30);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [hasUserAgreement, setHasUserAgreement] = useState(false);
const [hasPrivacyPolicy, setHasPrivacyPolicy] = useState(false);
const [agreementModal, setAgreementModal] = useState({
visible: false,
type: null,
});
const openAgreement = useCallback((e, type) => {
if (e && (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1)) {
return;
}
if (e) e.preventDefault();
setAgreementModal({ visible: true, type });
}, []);
const closeAgreement = useCallback(() => {
setAgreementModal((prev) => ({ ...prev, visible: false }));
}, []);
const [githubButtonText, setGithubButtonText] = useState('使用 GitHub 继续');
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
const [showWeChatOpenTipModal, setShowWeChatOpenTipModal] = useState(false);
const githubTimeoutRef = useRef(null);
// 注册表单 / 微信验证码弹窗的表单实例:用于在原逻辑执行前做前端校验
const registerFormApi = useRef(null);
const wechatFormApi = useRef(null);
// 获取验证码前先校验邮箱必填与格式,通过后走原发送逻辑
const sendVerificationCodeWithValidation = async () => {
try {
await registerFormApi.current?.validate(['email']);
} catch {
return;
}
await sendVerificationCode();
};
const submitWeChatCodeWithValidation = async () => {
try {
await wechatFormApi.current?.validate();
} catch {
return;
}
await onSubmitWeChatVerificationCode();
};
const logo = getLogo();
const systemName = getSystemName();
let affCode = new URLSearchParams(window.location.search).get('aff');
if (affCode) {
localStorage.setItem('aff', affCode);
}
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
// WeyAi 小程序的 web-view 里只留站内能完成的注册方式(见 helpers/miniProgram.js)。
const status = useMemo(() => {
const raw = statusState?.status || {};
return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw;
}, [statusState?.status]);
const statusLoaded = statusState?.status !== undefined;
const [showEmailVerification, setShowEmailVerification] = useState(() => {
return status.email_verification ?? false;
});
useEffect(() => {
setShowEmailVerification(status.email_verification);
if (status.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(status.turnstile_site_key);
}
// 从 status 获取用户协议和隐私政策的启用状态
setHasUserAgreement(status.user_agreement_enabled || false);
setHasPrivacyPolicy(status.privacy_policy_enabled || false);
}, [status]);
useEffect(() => {
let countdownInterval = null;
if (disableButton && countdown > 0) {
countdownInterval = setInterval(() => {
setCountdown(countdown - 1);
}, 1000);
} else if (countdown === 0) {
setDisableButton(false);
setCountdown(30);
}
return () => clearInterval(countdownInterval); // Clean up on unmount
}, [disableButton, countdown]);
useEffect(() => {
return () => {
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
};
}, []);
const finishLogin = (data) =>
runLoginFlow({ data, userDispatch, navigate, t });
const onWeChatLoginClicked = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setWechatLoading(true);
setShowWeChatLoginModal(true);
setWechatLoading(false);
};
// 微信开放平台扫码登录
const handleWeChatOpenClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
// 在移动端且不在微信内时,显示提示弹窗
if (isMobileDevice() && !isWeChatBrowser()) {
setShowWeChatOpenTipModal(true);
return;
}
setWechatOpenLoading(true);
try {
onWeChatOpenOAuthClicked(status.wechat_open_app_id);
} finally {
setTimeout(() => setWechatOpenLoading(false), 3000);
}
};
// 强制继续微信扫码登录(用于移动端用户确认后)
const handleForceWeChatOpenLogin = () => {
setShowWeChatOpenTipModal(false);
setWechatOpenLoading(true);
try {
onWeChatOpenOAuthClicked(status.wechat_open_app_id);
} finally {
setTimeout(() => setWechatOpenLoading(false), 3000);
}
};
const onSubmitWeChatVerificationCode = async () => {
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setWechatCodeSubmitLoading(true);
try {
const res = await API.get(
`/api/oauth/wechat?code=${inputs.wechat_verification_code}`,
);
const { success, message, data } = res.data;
if (success) {
// Close before finishLogin so the user isn't tempted to re-submit a
// consumed wechat code if session verification fails.
setShowWeChatLoginModal(false);
await finishLogin(data);
} else {
showError(message);
}
} catch (error) {
showError(t('登录失败,请重试'));
} finally {
setWechatCodeSubmitLoading(false);
}
};
function handleChange(name, value) {
setInputs((inputs) => ({ ...inputs, [name]: value }));
}
async function handleSubmit(e) {
if (e) {
e.preventDefault();
}
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (password.length < 8) {
showInfo(t('密码长度不得小于 8 位!'));
return;
}
if (password !== password2) {
showInfo(t('两次输入的密码不一致'));
return;
}
if (username && password) {
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setRegisterLoading(true);
try {
// 获取邀请码,优先使用 URL 参数,其次使用 localStorage
const finalAffCode = affCode || localStorage.getItem('aff');
// 创建请求数据,不直接修改 state
const requestData = {
...inputs,
aff_code: finalAffCode,
};
const res = await API.post(
`/api/user/register?turnstile=${turnstileToken}`,
requestData,
);
const { success, message } = res.data;
if (success) {
localStorage.setItem('new_user_gift_pending', inputs.username);
navigate('/login');
showSuccess(t('注册成功!'));
} else {
showError(message);
}
} catch (error) {
showError(t('注册失败,请重试'));
} finally {
setRegisterLoading(false);
}
}
}
const sendVerificationCode = async () => {
if (inputs.email === '') return;
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setVerificationCodeLoading(true);
try {
const res = await API.get(
`/api/verification?email=${encodeURIComponent(inputs.email)}&turnstile=${turnstileToken}`,
);
const { success, message } = res.data;
if (success) {
showSuccess(t('验证码发送成功,请检查你的邮箱!'));
setDisableButton(true); // 发送成功后禁用按钮,开始倒计时
} else {
showError(message);
}
} catch (error) {
showError(t('发送验证码失败,请重试'));
} finally {
setVerificationCodeLoading(false);
}
};
const handleGitHubClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (githubButtonDisabled) {
return;
}
setGithubLoading(true);
setGithubButtonDisabled(true);
setGithubButtonText(t('正在跳转 GitHub...'));
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
githubTimeoutRef.current = setTimeout(() => {
setGithubLoading(false);
setGithubButtonText(t('请求超时,请刷新页面后重新发起 GitHub 登录'));
setGithubButtonDisabled(true);
}, 20000);
try {
onGitHubOAuthClicked(status.github_client_id);
} finally {
setTimeout(() => setGithubLoading(false), 3000);
}
};
const handleDiscordClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setDiscordLoading(true);
try {
onDiscordOAuthClicked(status.discord_client_id);
} finally {
setTimeout(() => setDiscordLoading(false), 3000);
}
};
const handleOIDCClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setOidcLoading(true);
try {
onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id);
} finally {
setTimeout(() => setOidcLoading(false), 3000);
}
};
const handleLinuxDOClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setLinuxdoLoading(true);
try {
onLinuxDOOAuthClicked(status.linuxdo_client_id);
} finally {
setTimeout(() => setLinuxdoLoading(false), 3000);
}
};
const handleEmailRegisterClick = () => {
setEmailRegisterLoading(true);
setShowEmailRegister(true);
setEmailRegisterLoading(false);
};
const handleOtherRegisterOptionsClick = () => {
setOtherRegisterOptionsLoading(true);
setShowEmailRegister(false);
setOtherRegisterOptionsLoading(false);
};
const onTelegramLoginClicked = async (response) => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
const fields = [
'id',
'first_name',
'last_name',
'username',
'photo_url',
'auth_date',
'hash',
'lang',
];
const params = {};
fields.forEach((field) => {
if (response[field]) {
params[field] = response[field];
}
});
try {
const res = await API.get(`/api/oauth/telegram/login`, { params });
const { success, message, data } = res.data;
if (success) {
await finishLogin(data);
} else {
showError(message);
}
} catch (error) {
showError(t('登录失败,请重试'));
}
};
// 第三方注册按钮:与登录页一致的 36px 描边按钮,无位移 / 扫光动效
const OAuthButton = ({
icon,
children,
onClick,
loading,
disabled,
iconColor,
}) => (
);
const renderOAuthOptions = () => {
return (
{t('移动端登录提示')}
{t(
'请长按保存下方二维码,在微信中扫一扫打开。或使用其他设备的微信扫描二维码。',
)}
{isMobileView
? t('使用其他设备微信扫码关注公众号')
: t('微信扫码关注公众号')}
{t('输入「验证码」获取验证码(三分钟内有效)')}
{t('微信扫码登录功能在移动端体验不佳。建议您:')}
{/* 移动端可长按保存提示 */}
{isMobileView && (