Login_20250812112930.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // entrypoints/popup/pages/Login.tsx
  2. import React, { useState } from 'react';
  3. import { useNavigate } from 'react-router-dom';
  4. import { Button, Input, Message, Form, Grid } from '@alifd/next';
  5. const { Row, Col } = Grid
  6. export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
  7. const formRef = useRef<any>(null); // 创建 ref 引用
  8. const [username, setUsername] = useState('');
  9. const [password, setPassword] = useState('');
  10. const [loading, setLoading] = useState(false);
  11. const [errors, setErrors] = useState<{ username?: string, password?: string }>({});
  12. const [keys, setKeys] = useState('');
  13. const [validImg, setValidImg] = useState('');
  14. const navigate = useNavigate();
  15. useEffect(() => {
  16. evVerify()
  17. }, [])
  18. const validateForm = () => {
  19. const newErrors: { username?: string, password?: string } = {};
  20. if (!username.trim()) {
  21. newErrors.username = '请输入用户名';
  22. }
  23. if (!password) {
  24. newErrors.password = '请输入密码';
  25. } else if (password.length < 6) {
  26. newErrors.password = '密码长度至少为6位';
  27. }
  28. setErrors(newErrors);
  29. return Object.keys(newErrors).length === 0;
  30. };
  31. const evVerify = () => {
  32. console.log('username')
  33. fetch('https://user.landwu.com/api/user/verify', {
  34. method: 'POST',
  35. headers: {
  36. 'Content-Type': 'application/json',
  37. }
  38. }).then(resjson => {
  39. return resjson.json(); // 正确解析 Response 为 JSON 数据
  40. }).then(res => {
  41. const { data = {} } = res;
  42. const { data: info = {} } = data;
  43. const { key = "", img = "" } = info;
  44. setKeys(key)
  45. setValidImg(img)
  46. })
  47. }
  48. const handleLogin = (values: any, e: React.FormEvent) => {
  49. console.log(values,"fff")
  50. return
  51. e.preventDefault();
  52. if (!validateForm()) {
  53. return;
  54. }
  55. setLoading(true);
  56. try {
  57. const values = formRef.current.getFieldValues();
  58. console.log(values,"values")
  59. const { username, password, code } = values;
  60. const params = {
  61. username,
  62. password,
  63. code,
  64. key: keys
  65. }
  66. // 发送登录请求
  67. fetch('https://user.landwu.com/api/user/login', {
  68. method: 'POST',
  69. headers: {
  70. 'Content-Type': 'application/json',
  71. },
  72. body: JSON.stringify(params),
  73. }).then(response => response.json()).then(res => {
  74. const { msg = "", token = "", code } = res;
  75. if (!code) {
  76. setLoading(false);
  77. return false;
  78. }
  79. if (code == -1) {
  80. evVerify()
  81. Message.error(msg);
  82. setLoading(false);
  83. return false;
  84. }
  85. Message.success(msg);
  86. localStorage.setItem("access_token", token);
  87. localStorage.setItem('isLoggedIn', 'true');
  88. setIsLoggedIn(true);
  89. // 跳转到首页
  90. navigate('/');
  91. // Cookies.set("access_token", toCode(token));
  92. }).catch((e) => {
  93. console.log("catch")
  94. setLoading(false);
  95. });
  96. } catch (error) {
  97. console.error('登录请求失败:', error);
  98. Message.error('网络错误,请稍后重试');
  99. } finally {
  100. setLoading(false);
  101. }
  102. // 模拟登录请求
  103. // setTimeout(() => {
  104. // // 这里添加实际的登录逻辑
  105. // if (username && password) {
  106. // // 模拟登录成功
  107. // localStorage.setItem('isLoggedIn', 'true');
  108. // setIsLoggedIn(true);
  109. // // 跳转到首页
  110. // navigate('/');
  111. // Message.success('登录成功');
  112. // } else {
  113. // Message.error('登录失败,请检查用户名和密码');
  114. // }
  115. // setLoading(false);
  116. // }, 1000);
  117. };
  118. return (
  119. <div className="bg-gray-50 p-4">
  120. <div className="text-center mb-6">
  121. <h1 className="text-2xl font-bold text-gray-800">登录</h1>
  122. </div>
  123. <Form onSubmit={handleLogin} ref={formRef}>
  124. <Form.Item
  125. label="用户名"
  126. name="username"
  127. required
  128. help={errors.username}
  129. validateState={errors.username ? 'error' : undefined}
  130. >
  131. <Input
  132. placeholder="请输入用户名"
  133. value={username}
  134. onChange={(value) => {
  135. setUsername(value);
  136. if (errors.username) {
  137. setErrors({ ...errors, username: undefined });
  138. }
  139. }}
  140. disabled={loading}
  141. />
  142. </Form.Item>
  143. <Form.Item
  144. label="密码"
  145. name="password"
  146. required
  147. help={errors.password}
  148. validateState={errors.password ? 'error' : undefined}
  149. >
  150. <Input
  151. htmlType="password"
  152. placeholder="请输入密码"
  153. value={password}
  154. onChange={(value) => {
  155. setPassword(value);
  156. if (errors.password) {
  157. setErrors({ ...errors, password: undefined });
  158. }
  159. }}
  160. disabled={loading}
  161. />
  162. </Form.Item>
  163. <Row>
  164. <Col span={16}>
  165. <Form.Item
  166. label="验证码"
  167. name="code"
  168. required
  169. >
  170. <Input
  171. size="large"
  172. />
  173. </Form.Item>
  174. </Col>
  175. <Col span={8}>
  176. <img
  177. src={validImg}
  178. style={{
  179. width: 82,
  180. height: 30,
  181. marginTop: 28
  182. }}
  183. onClick={evVerify}
  184. />
  185. </Col>
  186. </Row>
  187. <Form.Item>
  188. <Button
  189. type="primary"
  190. htmlType="submit"
  191. loading={loading}
  192. className="w-full"
  193. >
  194. {loading ? '登录中...' : '登录'}
  195. </Button>
  196. </Form.Item>
  197. </Form>
  198. <div className="mt-4 text-center text-sm text-gray-500">
  199. <p>忘记密码?请联系管理员</p>
  200. </div>
  201. </div>
  202. );
  203. }