import React from 'react'; import { sendCode, phoneLogin } from '@/services/auth'; import MpQrLogin from '@/components/MpQrLogin'; import '@/styles/auth.css'; /** * 登录 / 注册墙(AuthGate)· 手机号 + 短信验证码 / 小程序扫码登录 * 用于"测评结果需登录"等场景。手机号即账号,未注册自动注册,无密码;小程序扫码为统一微信登录。 * props: * title — 卡片标题(覆盖默认) * subtitle — 一句话说明 * onAuthed(user) — 登录 / 注册成功回调(已写入 token 与用户信息) */ export default function AuthGate({ title, subtitle, onAuthed }) { const [mode, setMode] = React.useState('phone'); // phone | mp const [phone, setPhone] = React.useState(''); const [code, setCode] = React.useState(''); const [debug, setDebug] = React.useState(''); const [err, setErr] = React.useState(''); const [busy, setBusy] = React.useState(false); const [cd, setCd] = React.useState(0); const send = async () => { if (!/^1\d{10}$/.test(phone)) { setErr('请输入正确的 11 位手机号'); return; } setErr(''); setBusy(true); try { const r = await sendCode(phone.trim()); setDebug(`验证码已发送${r.debugCode ? ',演示验证码:' + r.debugCode : ''}(5 分钟内有效)`); setCd(60); const t = setInterval(() => setCd((v) => { if (v <= 1) { clearInterval(t); return 0; } return v - 1; }), 1000); } catch (ex) { setErr(ex && ex.message ? ex.message : '发送失败,请重试'); } finally { setBusy(false); } }; const submit = async (e) => { e.preventDefault(); setErr(''); if (!/^1\d{10}$/.test(phone)) { setErr('请输入正确的 11 位手机号'); return; } if (!code.trim()) { setErr('请输入验证码'); return; } setBusy(true); try { const user = await phoneLogin(phone.trim(), code.trim()); if (onAuthed) onAuthed(user); } catch (ex) { setErr(ex && ex.message ? ex.message : '登录失败,请重试'); } finally { setBusy(false); } }; const TABS = [['phone', '手机号登录'], ['mp', '小程序扫码']]; return (
{subtitle}
}