LoginVerificationInputPage.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. const YpImage = getOssUrl('yp.png');
  11. interface LocationState {
  12. loginType?: 'phone' | 'email';
  13. areaCode?: string;
  14. phoneNumber?: string;
  15. email?: string;
  16. }
  17. export const LoginVerificationInputPage = () => {
  18. const location = useLocation();
  19. const navigate = useNavigate();
  20. const state = location.state as LocationState | null;
  21. // 验证码输入框状态(4个)
  22. const [codes, setCodes] = useState<string[]>(['', '', '', '']);
  23. const [_focusedIndex, setFocusedIndex] = useState<number | null>(0);
  24. const [countdown, setCountdown] = useState<number>(60);
  25. const [isCodeValid, setIsCodeValid] = useState<boolean>(false);
  26. const [hasCodeError, setHasCodeError] = useState<boolean>(false);
  27. const [isVerifying, setIsVerifying] = useState<boolean>(false);
  28. const [isLoggingIn, setIsLoggingIn] = useState<boolean>(false);
  29. const codeRefs = [
  30. useRef<HTMLInputElement>(null),
  31. useRef<HTMLInputElement>(null),
  32. useRef<HTMLInputElement>(null),
  33. useRef<HTMLInputElement>(null),
  34. ];
  35. useEffect(() => {
  36. // 记录用户当前所在页面
  37. setStorage(STORAGE_KEYS.CURRENT_PAGE, 'login-verification-input');
  38. const visited = getVisitedRoutes();
  39. const userId = getUserId();
  40. if (userId) {
  41. updateUserUIState(userId, {
  42. current_page: 'login-verification-input',
  43. visited_routes: visited,
  44. }).catch(() => {
  45. // 同步失败不影响前端流程
  46. });
  47. }
  48. }, []);
  49. // 自动聚焦到第一个输入框
  50. // 延迟聚焦,确保视口高度修复机制已初始化完成,防止键盘弹出时界面缩小
  51. useEffect(() => {
  52. // 检查 --vh CSS 变量是否已初始化(视口高度修复机制已就绪)
  53. const checkViewportReady = (): boolean => {
  54. const vhValue = getComputedStyle(document.documentElement).getPropertyValue('--vh');
  55. const isReady = vhValue !== '' && vhValue !== null;
  56. console.log(`[LoginVerificationInputPage] 🔍 检查视口就绪: --vh=${vhValue}, isReady=${isReady}`);
  57. return isReady;
  58. };
  59. // 尝试聚焦的函数
  60. const attemptFocus = (source: string) => {
  61. if (codeRefs[0].current) {
  62. const input = codeRefs[0].current;
  63. const vhValue = getComputedStyle(document.documentElement).getPropertyValue('--vh');
  64. const initialHeight = window.innerHeight;
  65. const currentHeight = window.visualViewport?.height || window.innerHeight;
  66. console.log(`[LoginVerificationInputPage] 🎯 尝试聚焦: source=${source}, --vh=${vhValue}, initialHeight=${initialHeight}px, currentHeight=${currentHeight}px, inputMode=${input.inputMode}`);
  67. input.focus();
  68. // 聚焦后立即检查状态
  69. setTimeout(() => {
  70. const afterFocusVh = getComputedStyle(document.documentElement).getPropertyValue('--vh');
  71. const afterFocusHeight = window.visualViewport?.height || window.innerHeight;
  72. console.log(`[LoginVerificationInputPage] ✅ 聚焦后状态: --vh=${afterFocusVh}, currentHeight=${afterFocusHeight}px, document.activeElement=${document.activeElement?.tagName}`);
  73. }, 100);
  74. } else {
  75. console.log(`[LoginVerificationInputPage] ⚠️ 聚焦失败: codeRefs[0].current 为 null`);
  76. }
  77. };
  78. // 如果视口已就绪,延迟一小段时间后聚焦(确保初始化完成)
  79. if (checkViewportReady()) {
  80. console.log(`[LoginVerificationInputPage] ✅ 视口已就绪,延迟150ms后聚焦`);
  81. // 使用 requestAnimationFrame 确保在下一帧执行,给初始化更多时间
  82. requestAnimationFrame(() => {
  83. setTimeout(() => attemptFocus('ready-delayed'), 150);
  84. });
  85. } else {
  86. console.log(`[LoginVerificationInputPage] ⏳ 视口未就绪,等待初始化...`);
  87. // 如果还未就绪,等待一段时间后重试
  88. let checkCount = 0;
  89. const checkInterval = setInterval(() => {
  90. checkCount++;
  91. if (checkViewportReady()) {
  92. console.log(`[LoginVerificationInputPage] ✅ 视口已就绪(重试${checkCount}次),延迟150ms后聚焦`);
  93. clearInterval(checkInterval);
  94. requestAnimationFrame(() => {
  95. setTimeout(() => attemptFocus('retry-delayed'), 150);
  96. });
  97. }
  98. }, 50);
  99. // 最多等待 500ms,超时后强制聚焦
  100. setTimeout(() => {
  101. clearInterval(checkInterval);
  102. console.log(`[LoginVerificationInputPage] ⏰ 等待超时,强制聚焦`);
  103. attemptFocus('timeout');
  104. }, 500);
  105. }
  106. }, []);
  107. // 倒计时功能
  108. useEffect(() => {
  109. if (countdown > 0) {
  110. const timer = setTimeout(() => {
  111. setCountdown(countdown - 1);
  112. }, 1000);
  113. return () => clearTimeout(timer);
  114. }
  115. }, [countdown]);
  116. const handleBack = () => {
  117. // 返回登录验证码页面,并带上传入的所有数据
  118. navigate('/login-verification-code', {
  119. state: {
  120. loginType: state?.loginType,
  121. areaCode: state?.areaCode,
  122. phoneNumber: state?.phoneNumber,
  123. email: state?.email,
  124. },
  125. });
  126. };
  127. // 处理验证码输入
  128. const handleCodeChange = (index: number, value: string) => {
  129. // 清理输入,只保留数字和字母
  130. const sanitizedValue = value.replace(/[^0-9a-zA-Z]/g, '');
  131. // 如果输入长度大于1,说明是自动填充(从输入法上方点击验证码)
  132. if (sanitizedValue.length > 1) {
  133. const newCodes = [...codes];
  134. // 将验证码分配到4个输入框中
  135. for (let i = 0; i < 4; i++) {
  136. newCodes[i] = sanitizedValue[i] || '';
  137. }
  138. setCodes(newCodes);
  139. setHasCodeError(false);
  140. // 聚焦到最后一个有值的输入框或最后一个输入框
  141. const lastFilledIndex = Math.min(sanitizedValue.length - 1, 3);
  142. codeRefs[lastFilledIndex].current?.focus();
  143. setFocusedIndex(lastFilledIndex);
  144. return;
  145. }
  146. // 单个字符输入(正常输入)
  147. const singleChar = sanitizedValue.slice(0, 1);
  148. const newCodes = [...codes];
  149. newCodes[index] = singleChar;
  150. setCodes(newCodes);
  151. setHasCodeError(false);
  152. // 如果输入了值,自动聚焦到下一个输入框
  153. if (singleChar && index < 3) {
  154. codeRefs[index + 1].current?.focus();
  155. setFocusedIndex(index + 1);
  156. }
  157. };
  158. // 处理删除键
  159. const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
  160. if (e.key === 'Backspace' && !codes[index] && index > 0) {
  161. // 如果当前输入框为空,删除上一个输入框的内容并聚焦
  162. const newCodes = [...codes];
  163. newCodes[index - 1] = '';
  164. setCodes(newCodes);
  165. codeRefs[index - 1].current?.focus();
  166. setFocusedIndex(index - 1);
  167. }
  168. };
  169. // 处理粘贴
  170. const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
  171. e.preventDefault();
  172. const pastedText = e.clipboardData.getData('text').replace(/[^0-9a-zA-Z]/g, '').slice(0, 4);
  173. if (pastedText.length > 0) {
  174. const newCodes = [...codes];
  175. for (let i = 0; i < 4; i++) {
  176. newCodes[i] = pastedText[i] || '';
  177. }
  178. setCodes(newCodes);
  179. setHasCodeError(false);
  180. // 聚焦到最后一个有值的输入框或最后一个输入框
  181. const lastFilledIndex = Math.min(pastedText.length - 1, 3);
  182. codeRefs[lastFilledIndex].current?.focus();
  183. setFocusedIndex(lastFilledIndex);
  184. }
  185. };
  186. // 检查验证码是否完整
  187. const isCodeComplete = codes.every(code => code !== '');
  188. // 处理登录
  189. const handleLogin = useCallback(async () => {
  190. if (isLoggingIn) return;
  191. setIsLoggingIn(true);
  192. try {
  193. let response;
  194. if (state?.loginType === 'email' && state?.email) {
  195. response = await loginWithEmail(state.email);
  196. } else if (state?.phoneNumber) {
  197. response = await loginWithPhone(state.phoneNumber, state?.areaCode);
  198. } else {
  199. message.error('登录信息不完整');
  200. setIsLoggingIn(false);
  201. setIsCodeValid(false);
  202. return;
  203. }
  204. if (response.success && response.data) {
  205. // 保存基本用户信息
  206. const userId = response.data.user_id;
  207. setStorage(STORAGE_KEYS.USER_ID, userId);
  208. if (response.data.username) {
  209. setStorage(STORAGE_KEYS.USER_NAME, response.data.username);
  210. }
  211. // 🔥 保存会话 token(登录接口返回)
  212. if (response.data.token) {
  213. const { setUserToken } = await import('@/utils/storage');
  214. setUserToken(response.data.token);
  215. }
  216. // 获取完整用户信息并同步到 localStorage
  217. try {
  218. const userInfo = await getUserInfo(userId);
  219. if (userInfo.success && userInfo.data) {
  220. // 同步用户名
  221. if (userInfo.data.username) {
  222. setUserName(userInfo.data.username);
  223. }
  224. // 同步机器人名字
  225. if (userInfo.data.bot_name) {
  226. setStorage(STORAGE_KEYS.LUMI_NAME, userInfo.data.bot_name);
  227. }
  228. // 同步用户等级
  229. if (typeof userInfo.data.user_level === 'number') {
  230. setStorage(STORAGE_KEYS.USER_LEVEL, String(userInfo.data.user_level));
  231. }
  232. // 背景图片会在 getUserInfo 中自动同步
  233. }
  234. } catch (error) {
  235. // 获取完整用户信息失败不影响登录流程,静默处理
  236. console.warn('获取完整用户信息失败:', error);
  237. }
  238. message.success('登录成功');
  239. // 跳转到聊天界面
  240. navigate('/chatbot');
  241. } else {
  242. message.error('登录失败,请重试');
  243. setIsCodeValid(false);
  244. }
  245. } catch (error) {
  246. const errorMessage = error instanceof Error ? error.message : '登录失败';
  247. message.error(errorMessage);
  248. setIsCodeValid(false);
  249. } finally {
  250. setIsLoggingIn(false);
  251. }
  252. }, [isLoggingIn, state?.loginType, state?.email, state?.phoneNumber, navigate]);
  253. // 验证验证码(当输入完成时自动验证)
  254. useEffect(() => {
  255. if (isCodeComplete && !isVerifying && !isCodeValid && !isLoggingIn) {
  256. const verify = async () => {
  257. setIsVerifying(true);
  258. try {
  259. const codeString = codes.join('');
  260. const sendType = state?.loginType === 'email' ? 'email' : 'domestic_sms';
  261. const response = await verifyCode({
  262. phone: state?.phoneNumber,
  263. email: state?.email,
  264. code: codeString,
  265. send_type: sendType,
  266. });
  267. if (response.success && response.data.valid) {
  268. setIsCodeValid(true);
  269. setHasCodeError(false);
  270. // 验证成功后自动登录
  271. handleLogin();
  272. } else {
  273. setIsCodeValid(false);
  274. setHasCodeError(true);
  275. // 验证失败,清空输入框
  276. setCodes(['', '', '', '']);
  277. codeRefs[0].current?.focus();
  278. setFocusedIndex(0);
  279. message.error('验证码错误,请重新输入');
  280. }
  281. } catch (error) {
  282. console.error('验证验证码失败:', error);
  283. setIsCodeValid(false);
  284. setHasCodeError(true);
  285. // 验证失败,清空输入框
  286. setCodes(['', '', '', '']);
  287. codeRefs[0].current?.focus();
  288. setFocusedIndex(0);
  289. message.error('验证码验证失败,请重试');
  290. } finally {
  291. setIsVerifying(false);
  292. }
  293. };
  294. // 延迟一下再验证,避免用户还在输入时触发
  295. const timer = setTimeout(() => {
  296. verify();
  297. }, 300);
  298. return () => clearTimeout(timer);
  299. }
  300. }, [isCodeComplete, codes.join(''), state?.phoneNumber, state?.email, state?.loginType, isVerifying, isCodeValid, isLoggingIn, handleLogin]);
  301. // 处理发送验证码按钮点击
  302. const handleSendCode = async () => {
  303. if (countdown > 0) {
  304. return;
  305. }
  306. // 验证输入
  307. if (state?.loginType === 'phone' && !state?.phoneNumber) {
  308. message.error('手机号码不能为空');
  309. return;
  310. }
  311. if (state?.loginType === 'email' && !state?.email) {
  312. message.error('邮箱地址不能为空');
  313. return;
  314. }
  315. try {
  316. // 确定发送类型
  317. const sendType = state?.loginType === 'email' ? 'email' : 'domestic_sms';
  318. // 发送验证码
  319. const response = await sendCode({
  320. area_code: state?.loginType === 'phone' ? state?.areaCode : undefined,
  321. phone: state?.loginType === 'phone' ? state?.phoneNumber : undefined,
  322. email: state?.loginType === 'email' ? state?.email : undefined,
  323. send_type: sendType,
  324. });
  325. if (response.success) {
  326. message.success('验证码已发送');
  327. // 重新开始倒计时
  328. setCountdown(60);
  329. // 清空验证码输入框
  330. setCodes(['', '', '', '']);
  331. codeRefs[0].current?.focus();
  332. setFocusedIndex(0);
  333. setIsCodeValid(false);
  334. setHasCodeError(false);
  335. } else {
  336. message.error('发送验证码失败,请重试');
  337. }
  338. } catch (error) {
  339. const errorMessage = error instanceof Error ? error.message : '发送验证码失败';
  340. message.error(errorMessage);
  341. }
  342. };
  343. return (
  344. <div>
  345. {/* 顶部返回按钮 */}
  346. <button
  347. type="button"
  348. onClick={handleBack}
  349. style={{
  350. position: 'absolute',
  351. left: px2vmin(16),
  352. top: px2vmin(56),
  353. width: px2vmin(48),
  354. height: px2vmin(48),
  355. padding: 0,
  356. border: 'none',
  357. background: 'none',
  358. zIndex: 10,
  359. cursor: 'pointer',
  360. }}
  361. aria-label="Back"
  362. >
  363. <img
  364. src={backButton}
  365. alt="Back"
  366. style={{
  367. width: '100%',
  368. height: '100%',
  369. display: 'block',
  370. pointerEvents: 'none',
  371. }}
  372. />
  373. </button>
  374. {/* 中部 GIF 动画图片 */}
  375. <img
  376. src={getOssUrl('01-Default.gif')}
  377. alt="cheer animation"
  378. style={{
  379. position: 'absolute',
  380. left: '50%',
  381. top: px2vmin(132),
  382. height: px2vmin(184),
  383. transform: 'translateX(-50%)',
  384. }}
  385. />
  386. {/* Yp 图片 - 位于动画形象下方 */}
  387. <div
  388. className="absolute"
  389. style={{
  390. top: `calc(${px2vmin(132)} + ${px2vmin(160)})`,
  391. left: '50%',
  392. transform: 'translateX(-50%)',
  393. width: px2vmin(85),
  394. height: px2vmin(13),
  395. }}
  396. >
  397. <img
  398. src={YpImage}
  399. alt="Yp"
  400. className="w-full h-full object-contain"
  401. style={{ width: '100%', height: '100%' }}
  402. draggable={false}
  403. />
  404. </div>
  405. {/* 验证码发送提示文字 */}
  406. <div
  407. className="absolute"
  408. style={{
  409. top: px2vmin(324),
  410. left: '50%',
  411. transform: 'translateX(-50%)',
  412. width: px2vmin(312),
  413. height: px2vmin(16),
  414. fontSize: px2vmin(12),
  415. color: '#FFFFFF',
  416. textAlign: 'left',
  417. lineHeight: px2vmin(16),
  418. }}
  419. >
  420. {state?.loginType === 'email'
  421. ? `验证码已通过邮箱发送至 ${state?.email || ''}`
  422. : `验证码已通过短信发送至 ${(state?.areaCode || '+86')} ${state?.phoneNumber || ''}`}
  423. </div>
  424. {/* 验证码输入框 */}
  425. <div
  426. className="absolute"
  427. style={{
  428. top: px2vmin(346),
  429. left: '50%',
  430. transform: 'translateX(-50%)',
  431. width: px2vmin(312),
  432. display: 'flex',
  433. gap: px2vmin(20),
  434. justifyContent: 'center',
  435. }}
  436. >
  437. {codes.map((code, index) => {
  438. return (
  439. <div key={index} style={{ width: px2vmin(63), position: 'relative' }}>
  440. <div
  441. className="relative overflow-visible"
  442. style={{
  443. height: px2vmin(56),
  444. background: 'rgba(0,0,0,0.1)',
  445. borderTopLeftRadius: '12PX',
  446. borderBottomLeftRadius: '2PX',
  447. borderTopRightRadius: '12PX',
  448. borderBottomRightRadius: '2PX',
  449. boxShadow:
  450. 'rgba(255, 255, 255, 0.18) 0px 1px 0px 0px, rgba(0, 0, 0, 0.65) 0px 0px 0px 1px inset, rgba(0, 0, 0, 0.25) 0px 4px 8px inset',
  451. }}
  452. >
  453. <input
  454. ref={codeRefs[index]}
  455. type="text"
  456. inputMode="numeric"
  457. maxLength={index === 0 ? 4 : 1}
  458. autoComplete={index === 0 ? 'one-time-code' : 'off'}
  459. 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"
  460. style={{
  461. fontSize: px2vmin(20),
  462. paddingLeft: px2vw(8),
  463. paddingRight: px2vw(8),
  464. }}
  465. value={code}
  466. onChange={(e) => handleCodeChange(index, e.target.value)}
  467. onKeyDown={(e) => handleKeyDown(index, e)}
  468. onPaste={handlePaste}
  469. onFocus={() => setFocusedIndex(index)}
  470. onBlur={() => setFocusedIndex(null)}
  471. disabled={isVerifying || isLoggingIn}
  472. />
  473. </div>
  474. <div
  475. className="w-full transition-opacity duration-300"
  476. style={{
  477. height: '2PX',
  478. background: hasCodeError ? 'rgba(133, 34, 33, 1)' : 'var(--Schemes-Primary, rgba(103, 80, 164, 1))',
  479. }}
  480. ></div>
  481. </div>
  482. );
  483. })}
  484. </div>
  485. {/* 发送验证码按钮 */}
  486. <button
  487. type="button"
  488. onClick={handleSendCode}
  489. disabled={countdown > 0 || isVerifying || isLoggingIn}
  490. style={{
  491. position: 'absolute',
  492. left: '50%',
  493. top: px2vmin(456),
  494. width: px2vmin(279),
  495. transform: 'translateX(-50%)',
  496. border: 'none',
  497. padding: 0,
  498. background: 'none',
  499. cursor: countdown === 0 && !isVerifying && !isLoggingIn ? 'pointer' : 'not-allowed',
  500. }}
  501. >
  502. <div
  503. style={{
  504. position: 'relative',
  505. width: '100%',
  506. height: '100%',
  507. display: 'flex',
  508. alignItems: 'center',
  509. justifyContent: 'center',
  510. }}
  511. >
  512. <img
  513. src={sendCodeWaitNo}
  514. alt="send code"
  515. style={{
  516. width: '100%',
  517. display: 'block',
  518. }}
  519. />
  520. <div
  521. style={{
  522. position: 'absolute',
  523. top: '50%',
  524. left: '50%',
  525. transform: 'translate(-50%, -50%)',
  526. fontSize: px2vmin(16),
  527. fontWeight: 500,
  528. color: countdown > 0 || isVerifying || isLoggingIn
  529. ? 'rgba(245, 243, 240, 0.4)'
  530. : 'rgba(245, 243, 240, 1)',
  531. whiteSpace: 'nowrap',
  532. }}
  533. >
  534. {isVerifying || isLoggingIn
  535. ? '验证中...'
  536. : countdown > 0
  537. ? `Send code again: ${String(Math.floor(countdown / 60)).padStart(2, '0')}:${String(countdown % 60).padStart(2, '0')}`
  538. : 'Send code'}
  539. </div>
  540. </div>
  541. </button>
  542. </div>
  543. );
  544. };