Login_20250812113850.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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) => {
  49. console.log(values, "formRef.current")
  50. return
  51. setLoading(true);
  52. try {
  53. const values = formRef.current.getFieldValues();
  54. console.log(values, "values")
  55. const { username, password, code } = values;
  56. const params = {
  57. username,
  58. password,
  59. code,
  60. key: keys
  61. }
  62. // 发送登录请求
  63. fetch('https://user.landwu.com/api/user/login', {
  64. method: 'POST',
  65. headers: {
  66. 'Content-Type': 'application/json',
  67. },
  68. body: JSON.stringify(params),
  69. }).then(response => response.json()).then(res => {
  70. const { msg = "", token = "", code } = res;
  71. if (!code) {
  72. setLoading(false);
  73. return false;
  74. }
  75. if (code == -1) {
  76. evVerify()
  77. Message.error(msg);
  78. setLoading(false);
  79. return false;
  80. }
  81. Message.success(msg);
  82. localStorage.setItem("access_token", token);
  83. localStorage.setItem('isLoggedIn', 'true');
  84. setIsLoggedIn(true);
  85. // 跳转到首页
  86. navigate('/');
  87. // Cookies.set("access_token", toCode(token));
  88. }).catch((e) => {
  89. console.log("catch")
  90. setLoading(false);
  91. });
  92. } catch (error) {
  93. console.error('登录请求失败:', error);
  94. Message.error('网络错误,请稍后重试');
  95. } finally {
  96. setLoading(false);
  97. }
  98. // 模拟登录请求
  99. // setTimeout(() => {
  100. // // 这里添加实际的登录逻辑
  101. // if (username && password) {
  102. // // 模拟登录成功
  103. // localStorage.setItem('isLoggedIn', 'true');
  104. // setIsLoggedIn(true);
  105. // // 跳转到首页
  106. // navigate('/');
  107. // Message.success('登录成功');
  108. // } else {
  109. // Message.error('登录失败,请检查用户名和密码');
  110. // }
  111. // setLoading(false);
  112. // }, 1000);
  113. };
  114. return (
  115. <div className="bg-gray-50 p-4">
  116. <div className="text-center mb-6">
  117. <h1 className="text-2xl font-bold text-gray-800">登录</h1>
  118. </div>
  119. <Form>
  120. <Form.Item
  121. label="用户名"
  122. name="username"
  123. required
  124. help={errors.username}
  125. validateState={errors.username ? 'error' : undefined}
  126. >
  127. <Input
  128. placeholder="请输入用户名"
  129. value={username}
  130. onChange={(value) => {
  131. setUsername(value);
  132. if (errors.username) {
  133. setErrors({ ...errors, username: undefined });
  134. }
  135. }}
  136. disabled={loading}
  137. />
  138. </Form.Item>
  139. <Form.Item
  140. label="密码"
  141. name="password"
  142. required
  143. help={errors.password}
  144. validateState={errors.password ? 'error' : undefined}
  145. >
  146. <Input
  147. htmlType="password"
  148. placeholder="请输入密码"
  149. value={password}
  150. onChange={(value) => {
  151. setPassword(value);
  152. if (errors.password) {
  153. setErrors({ ...errors, password: undefined });
  154. }
  155. }}
  156. disabled={loading}
  157. />
  158. </Form.Item>
  159. <Row>
  160. <Col span={16}>
  161. <Form.Item
  162. label="验证码"
  163. name="code"
  164. required
  165. >
  166. <Input
  167. size="large"
  168. />
  169. </Form.Item>
  170. </Col>
  171. <Col span={8}>
  172. <img
  173. src={validImg}
  174. style={{
  175. width: 82,
  176. height: 30,
  177. marginTop: 28
  178. }}
  179. onClick={evVerify}
  180. />
  181. </Col>
  182. </Row>
  183. <Form.Item>
  184. <Form.Submit
  185. type="primary"
  186. validate
  187. loading={loading}
  188. onClick={handleLogin}
  189. className="w-full"
  190. style={{ marginRight: 8 }}
  191. >
  192. {loading ? '登录中...' : '登录'}
  193. </Form.Submit>
  194. </Form.Item>
  195. </Form>
  196. <div className="mt-4 text-center text-sm text-gray-500">
  197. <p>忘记密码?请联系管理员</p>
  198. </div>
  199. </div>
  200. );
  201. }