LoginVerificationInputPage.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import { useEffect, useState, useRef, useCallback } from 'react';
  2. import { useLocation, useNavigate } from 'react-router-dom';
  3. import { message } from 'antd';
  4. import { setStorage, STORAGE_KEYS, getUserId, getVisitedRoutes, setUserName } from '@/utils/storage';
  5. import { updateUserUIState, verifyCode, loginWithPhone, loginWithEmail, sendCode, getUserInfo } from '@/utils/api';
  6. import { px2vmin, px2vw } from '@/utils/viewport';
  7. import { getOssUrl } from '@/utils/oss';
  8. const sendCodeWaitNo = getOssUrl('send-code-wait-no.png');
  9. const backButton = getOssUrl('backbutn.png');
  10. interface LocationState {
  11. loginType?: 'phone' | 'email';
  12. areaCode?: string;
  13. phoneNumber?: string;
  14. email?: string;
  15. }
  16. export const LoginVerificationInputPage = () => {
  17. const location = useLocation();
  18. const navigate = useNavigate();
  19. const state = location.state as LocationState | null;
  20. // 验证码输入框状态(4个)
  21. const [codes, setCodes] = useState<string[]>(['', '', '', '']);
  22. const [focusedIndex, setFocusedIndex] = useState<number | null>(0);
  23. const [countdown, setCountdown] = useState<number>(60);
  24. const [isCodeValid, setIsCodeValid] = useState<boolean>(false);
  25. const [isVerifying, setIsVerifying] = useState<boolean>(false);
  26. const [isLoggingIn, setIsLoggingIn] = useState<boolean>(false);
  27. const codeRefs = [
  28. useRef<HTMLInputElement>(null),
  29. useRef<HTMLInputElement>(null),
  30. useRef<HTMLInputElement>(null),
  31. useRef<HTMLInputElement>(null),
  32. ];
  33. useEffect(() => {
  34. // 记录用户当前所在页面
  35. setStorage(STORAGE_KEYS.CURRENT_PAGE, 'login-verification-input');
  36. const visited = getVisitedRoutes();
  37. const userId = getUserId();
  38. if (userId) {
  39. updateUserUIState(userId, {
  40. current_page: 'login-verification-input',
  41. visited_routes: visited,
  42. }).catch(() => {
  43. // 同步失败不影响前端流程
  44. });
  45. }
  46. }, []);
  47. // 自动聚焦到第一个输入框
  48. useEffect(() => {
  49. if (codeRefs[0].current) {
  50. codeRefs[0].current.focus();
  51. }
  52. }, []);
  53. // 倒计时功能
  54. useEffect(() => {
  55. if (countdown > 0) {
  56. const timer = setTimeout(() => {
  57. setCountdown(countdown - 1);
  58. }, 1000);
  59. return () => clearTimeout(timer);
  60. }
  61. }, [countdown]);
  62. const handleBack = () => {
  63. // 返回登录验证码页面,并带上传入的所有数据
  64. navigate('/login-verification-code', {
  65. state: {
  66. loginType: state?.loginType,
  67. areaCode: state?.areaCode,
  68. phoneNumber: state?.phoneNumber,
  69. email: state?.email,
  70. },
  71. });
  72. };
  73. // 处理验证码输入
  74. const handleCodeChange = (index: number, value: string) => {
  75. // 只允许输入单个数字或字母
  76. const sanitizedValue = value.replace(/[^0-9a-zA-Z]/g, '').slice(0, 1);
  77. const newCodes = [...codes];
  78. newCodes[index] = sanitizedValue;
  79. setCodes(newCodes);
  80. // 如果输入了值,自动聚焦到下一个输入框
  81. if (sanitizedValue && index < 3) {
  82. codeRefs[index + 1].current?.focus();
  83. setFocusedIndex(index + 1);
  84. }
  85. };
  86. // 处理删除键
  87. const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
  88. if (e.key === 'Backspace' && !codes[index] && index > 0) {
  89. // 如果当前输入框为空,删除上一个输入框的内容并聚焦
  90. const newCodes = [...codes];
  91. newCodes[index - 1] = '';
  92. setCodes(newCodes);
  93. codeRefs[index - 1].current?.focus();
  94. setFocusedIndex(index - 1);
  95. }
  96. };
  97. // 处理粘贴
  98. const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
  99. e.preventDefault();
  100. const pastedText = e.clipboardData.getData('text').replace(/[^0-9a-zA-Z]/g, '').slice(0, 4);
  101. if (pastedText.length > 0) {
  102. const newCodes = [...codes];
  103. for (let i = 0; i < 4; i++) {
  104. newCodes[i] = pastedText[i] || '';
  105. }
  106. setCodes(newCodes);
  107. // 聚焦到最后一个有值的输入框或最后一个输入框
  108. const lastFilledIndex = Math.min(pastedText.length - 1, 3);
  109. codeRefs[lastFilledIndex].current?.focus();
  110. setFocusedIndex(lastFilledIndex);
  111. }
  112. };
  113. // 检查验证码是否完整
  114. const isCodeComplete = codes.every(code => code !== '');
  115. // 处理登录
  116. const handleLogin = useCallback(async () => {
  117. if (isLoggingIn) return;
  118. setIsLoggingIn(true);
  119. try {
  120. let response;
  121. if (state?.loginType === 'email' && state?.email) {
  122. response = await loginWithEmail(state.email);
  123. } else if (state?.phoneNumber) {
  124. response = await loginWithPhone(state.phoneNumber);
  125. } else {
  126. message.error('登录信息不完整');
  127. setIsLoggingIn(false);
  128. setIsCodeValid(false);
  129. return;
  130. }
  131. if (response.success && response.data) {
  132. // 保存基本用户信息
  133. const userId = response.data.user_id;
  134. setStorage(STORAGE_KEYS.USER_ID, userId);
  135. if (response.data.username) {
  136. setStorage(STORAGE_KEYS.USER_NAME, response.data.username);
  137. }
  138. // 获取完整用户信息并同步到 localStorage
  139. try {
  140. const userInfo = await getUserInfo(userId);
  141. if (userInfo.success && userInfo.data) {
  142. // 同步用户名
  143. if (userInfo.data.username) {
  144. setUserName(userInfo.data.username);
  145. }
  146. // 同步机器人名字
  147. if (userInfo.data.bot_name) {
  148. setStorage(STORAGE_KEYS.LUMI_NAME, userInfo.data.bot_name);
  149. }
  150. // 同步用户等级
  151. if (typeof userInfo.data.user_level === 'number') {
  152. setStorage(STORAGE_KEYS.USER_LEVEL, String(userInfo.data.user_level));
  153. }
  154. // 背景图片会在 getUserInfo 中自动同步
  155. }
  156. } catch (error) {
  157. // 获取完整用户信息失败不影响登录流程,静默处理
  158. console.warn('获取完整用户信息失败:', error);
  159. }
  160. message.success('登录成功');
  161. // 跳转到聊天界面
  162. navigate('/chatbot');
  163. } else {
  164. message.error('登录失败,请重试');
  165. setIsCodeValid(false);
  166. }
  167. } catch (error) {
  168. const errorMessage = error instanceof Error ? error.message : '登录失败';
  169. message.error(errorMessage);
  170. setIsCodeValid(false);
  171. } finally {
  172. setIsLoggingIn(false);
  173. }
  174. }, [isLoggingIn, state?.loginType, state?.email, state?.phoneNumber, navigate]);
  175. // 验证验证码(当输入完成时自动验证)
  176. useEffect(() => {
  177. if (isCodeComplete && !isVerifying && !isCodeValid && !isLoggingIn) {
  178. const verify = async () => {
  179. setIsVerifying(true);
  180. try {
  181. const codeString = codes.join('');
  182. const sendType = state?.loginType === 'email' ? 'email' : 'domestic_sms';
  183. const response = await verifyCode({
  184. phone: state?.phoneNumber,
  185. email: state?.email,
  186. code: codeString,
  187. send_type: sendType,
  188. });
  189. if (response.success && response.data.valid) {
  190. setIsCodeValid(true);
  191. // 验证成功后自动登录
  192. handleLogin();
  193. } else {
  194. setIsCodeValid(false);
  195. // 验证失败,清空输入框
  196. setCodes(['', '', '', '']);
  197. codeRefs[0].current?.focus();
  198. setFocusedIndex(0);
  199. message.error('验证码错误,请重新输入');
  200. }
  201. } catch (error) {
  202. console.error('验证验证码失败:', error);
  203. setIsCodeValid(false);
  204. // 验证失败,清空输入框
  205. setCodes(['', '', '', '']);
  206. codeRefs[0].current?.focus();
  207. setFocusedIndex(0);
  208. message.error('验证码验证失败,请重试');
  209. } finally {
  210. setIsVerifying(false);
  211. }
  212. };
  213. // 延迟一下再验证,避免用户还在输入时触发
  214. const timer = setTimeout(() => {
  215. verify();
  216. }, 300);
  217. return () => clearTimeout(timer);
  218. }
  219. }, [isCodeComplete, codes.join(''), state?.phoneNumber, state?.email, state?.loginType, isVerifying, isCodeValid, isLoggingIn, handleLogin]);
  220. // 处理发送验证码按钮点击
  221. const handleSendCode = async () => {
  222. if (countdown > 0) {
  223. return;
  224. }
  225. // 验证输入
  226. if (state?.loginType === 'phone' && !state?.phoneNumber) {
  227. message.error('手机号码不能为空');
  228. return;
  229. }
  230. if (state?.loginType === 'email' && !state?.email) {
  231. message.error('邮箱地址不能为空');
  232. return;
  233. }
  234. try {
  235. // 确定发送类型
  236. const sendType = state?.loginType === 'email' ? 'email' : 'domestic_sms';
  237. // 发送验证码
  238. const response = await sendCode({
  239. area_code: state?.loginType === 'phone' ? state?.areaCode : undefined,
  240. phone: state?.loginType === 'phone' ? state?.phoneNumber : undefined,
  241. email: state?.loginType === 'email' ? state?.email : undefined,
  242. send_type: sendType,
  243. });
  244. if (response.success) {
  245. message.success('验证码已发送');
  246. // 重新开始倒计时
  247. setCountdown(60);
  248. // 清空验证码输入框
  249. setCodes(['', '', '', '']);
  250. codeRefs[0].current?.focus();
  251. setFocusedIndex(0);
  252. setIsCodeValid(false);
  253. } else {
  254. message.error('发送验证码失败,请重试');
  255. }
  256. } catch (error) {
  257. const errorMessage = error instanceof Error ? error.message : '发送验证码失败';
  258. message.error(errorMessage);
  259. }
  260. };
  261. return (
  262. <div>
  263. {/* 顶部返回按钮 */}
  264. <button
  265. type="button"
  266. onClick={handleBack}
  267. style={{
  268. position: 'absolute',
  269. left: px2vmin(16),
  270. top: px2vmin(56),
  271. width: px2vmin(48),
  272. height: px2vmin(48),
  273. padding: 0,
  274. border: 'none',
  275. background: 'none',
  276. zIndex: 10,
  277. cursor: 'pointer',
  278. }}
  279. aria-label="Back"
  280. >
  281. <img
  282. src={backButton}
  283. alt="Back"
  284. style={{
  285. width: '100%',
  286. height: '100%',
  287. display: 'block',
  288. pointerEvents: 'none',
  289. }}
  290. />
  291. </button>
  292. {/* 中部 GIF 动画图片 */}
  293. <img
  294. src="https://lyrria-pro.oss-cn-beijing.aliyuncs.com/01-Default.gif"
  295. alt="cheer animation"
  296. style={{
  297. position: 'absolute',
  298. left: '50%',
  299. top: px2vmin(132),
  300. height: px2vmin(184),
  301. transform: 'translateX(-50%)',
  302. }}
  303. />
  304. {/* 验证码发送提示文字 */}
  305. <div
  306. className="absolute"
  307. style={{
  308. top: px2vmin(304),
  309. left: '50%',
  310. transform: 'translateX(-50%)',
  311. width: px2vmin(312),
  312. height: px2vmin(16),
  313. fontSize: px2vmin(12),
  314. color: '#FFFFFF',
  315. textAlign: 'left',
  316. lineHeight: px2vmin(16),
  317. }}
  318. >
  319. {state?.loginType === 'email'
  320. ? `验证码已通过邮箱发送至 ${state?.email || ''}`
  321. : `验证码已通过短信发送至 ${state?.phoneNumber || ''}`}
  322. </div>
  323. {/* 验证码输入框 */}
  324. <div
  325. className="absolute"
  326. style={{
  327. top: px2vmin(326),
  328. left: '50%',
  329. transform: 'translateX(-50%)',
  330. width: px2vmin(312),
  331. display: 'flex',
  332. gap: px2vmin(30),
  333. justifyContent: 'center',
  334. }}
  335. >
  336. {codes.map((code, index) => {
  337. const isFocused = focusedIndex === index;
  338. return (
  339. <div key={index} style={{ width: px2vmin(63), position: 'relative' }}>
  340. <div
  341. className="relative overflow-visible"
  342. style={{
  343. height: px2vmin(56),
  344. background: 'linear-gradient(180deg, #26232F 0%, #18151F 100%)',
  345. borderTopLeftRadius: '12PX',
  346. borderBottomLeftRadius: '2PX',
  347. borderTopRightRadius: '12PX',
  348. borderBottomRightRadius: '2PX',
  349. boxShadow:
  350. '0PX 1PX 0PX 0PX rgba(255, 255, 255, 0.18), inset 0PX 0PX 0PX 1PX rgba(0, 0, 0, 0.65), inset 0PX 4PX 8PX rgba(0, 0, 0, 0.55)',
  351. }}
  352. >
  353. <input
  354. ref={codeRefs[index]}
  355. type="text"
  356. inputMode="numeric"
  357. maxLength={1}
  358. className="w-full h-full font-normal leading-normal tracking-[0.5px] text-[rgba(245,243,240,0.7)] bg-transparent border-none outline-none placeholder:text-[rgba(245,243,240,0.45)] text-center"
  359. style={{
  360. fontSize: px2vmin(20),
  361. paddingLeft: px2vw(8),
  362. paddingRight: px2vw(8),
  363. }}
  364. value={code}
  365. onChange={(e) => handleCodeChange(index, e.target.value)}
  366. onKeyDown={(e) => handleKeyDown(index, e)}
  367. onPaste={handlePaste}
  368. onFocus={() => setFocusedIndex(index)}
  369. onBlur={() => setFocusedIndex(null)}
  370. disabled={isVerifying || isLoggingIn}
  371. />
  372. </div>
  373. <div
  374. className="w-full transition-opacity duration-300"
  375. style={{
  376. height: '2PX',
  377. background: isFocused || code
  378. ? 'rgba(133, 34, 33, 1)'
  379. : 'var(--Schemes-Primary, rgba(103, 80, 164, 1))',
  380. }}
  381. ></div>
  382. </div>
  383. );
  384. })}
  385. </div>
  386. {/* 发送验证码按钮 */}
  387. <button
  388. type="button"
  389. onClick={handleSendCode}
  390. disabled={countdown > 0 || isVerifying || isLoggingIn}
  391. style={{
  392. position: 'absolute',
  393. left: '50%',
  394. top: px2vmin(436),
  395. width: px2vmin(279),
  396. transform: 'translateX(-50%)',
  397. border: 'none',
  398. padding: 0,
  399. background: 'none',
  400. cursor: countdown === 0 && !isVerifying && !isLoggingIn ? 'pointer' : 'not-allowed',
  401. }}
  402. >
  403. <div
  404. style={{
  405. position: 'relative',
  406. width: '100%',
  407. height: '100%',
  408. display: 'flex',
  409. alignItems: 'center',
  410. justifyContent: 'center',
  411. }}
  412. >
  413. <img
  414. src={sendCodeWaitNo}
  415. alt="send code"
  416. style={{
  417. width: '100%',
  418. display: 'block',
  419. }}
  420. />
  421. <div
  422. style={{
  423. position: 'absolute',
  424. top: '50%',
  425. left: '50%',
  426. transform: 'translate(-50%, -50%)',
  427. fontSize: px2vmin(16),
  428. fontWeight: 500,
  429. color: countdown > 0 || isVerifying || isLoggingIn
  430. ? 'rgba(245, 243, 240, 0.4)'
  431. : 'rgba(245, 243, 240, 1)',
  432. whiteSpace: 'nowrap',
  433. }}
  434. >
  435. {isVerifying || isLoggingIn
  436. ? '验证中...'
  437. : countdown > 0
  438. ? `Send code again: ${String(Math.floor(countdown / 60)).padStart(2, '0')}:${String(countdown % 60).padStart(2, '0')}`
  439. : 'Send code'}
  440. </div>
  441. </div>
  442. </button>
  443. </div>
  444. );
  445. };