Login_20250812110243.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 = (value: any, e: any) => {
  49. console.log(e,"rrrrrrr", value)
  50. return
  51. e.preventDefault();
  52. if (!validateForm()) {
  53. return;
  54. }
  55. setLoading(true);
  56. try {
  57. const params = {
  58. }
  59. // 发送登录请求
  60. fetch('https://user.landwu.com/api/user/login', {
  61. method: 'POST',
  62. headers: {
  63. 'Content-Type': 'application/json',
  64. },
  65. body: JSON.stringify({
  66. username,
  67. password,
  68. code
  69. }),
  70. }).then(response => response.json()).then(res => {
  71. const { key = "" } = this.state;
  72. values["key"] = key;
  73. login
  74. .login(values)
  75. .then((res) => {
  76. // this.props.isLogin && this.props.isLogin( {access_token:'access_token--11'});
  77. const { msg = "", token = "", code } = res;
  78. if (!code) {
  79. this.setState(() => {
  80. return {
  81. loading: false,
  82. };
  83. });
  84. return false;
  85. }
  86. console.log(res, "--res", code);
  87. if (code == -1) {
  88. console.log("code", code)
  89. this.verify();
  90. message.error(msg);
  91. this.setState(() => {
  92. return {
  93. loading: false,
  94. };
  95. });
  96. return false;
  97. }
  98. message.success(msg);
  99. // console.log(res, "res",token);
  100. // localStorage.setItem("access_token", toCode(token));
  101. localStorage.setItem("access_token", token);
  102. // Cookies.set("access_token", toCode(token));
  103. this.setState(
  104. () => {
  105. return {
  106. loading: true,
  107. };
  108. },
  109. () => {
  110. // this.props.isLogin && this.props.isLogin({ admin: "data.admin" });
  111. // this.props.isLogin && this.props.isLogin({ access_token: token });
  112. console.log(this.props.history.location.pathname, 'historytoCode', toCode(1), fromCode('<(('))
  113. localStorage.removeItem('lw_config_page')
  114. localStorage.removeItem('lw_config_limit')
  115. localStorage.removeItem('lw_menu_config')
  116. localStorage.setItem('nav_index_1', 0)
  117. localStorage.removeItem('nav_index_2')
  118. localStorage.removeItem('nav_index_3')
  119. localStorage.removeItem('is_offline');//是否门店
  120. Loading.init()
  121. setTimeout(() => {
  122. let parms = {}
  123. if (getIsoffline() == 1) {
  124. parms['is_shipping'] = getIsoffline()
  125. }
  126. user
  127. .user_getProfile(parms)
  128. .then((res) => {
  129. Loading.remove()
  130. console.log(res, '获取用户信息')
  131. const { data = {} } = res;
  132. const { userinfo = {} } = data;
  133. this.getUserInfoLog(userinfo, token)
  134. if (userinfo.is_offline) {
  135. localStorage.setItem('is_offline', toCode(userinfo.is_offline))
  136. }
  137. localStorage.setItem("user_info", JSON.stringify(userinfo));
  138. if (!getQuery('is_link') && getQuery('code')) {
  139. this.pdd_pddServiceAuth(() => {
  140. location.reload(true);
  141. })
  142. } else {
  143. Loading.init()
  144. rule.rule_getRuleAuth().then(res => {
  145. Loading.remove()
  146. const { data } = res
  147. let data_menu = data;
  148. console.log(data_menu, '-data_menudata_menudata_menu')
  149. if (data_menu.length && !getQuery('is_link')) {
  150. const _indexUrl = data_menu[0]
  151. const { push } = this.props.history
  152. console.log(_indexUrl, '_indexUrl')
  153. // push('')
  154. push(_indexUrl.url)
  155. // console.log(_indexUrl,'_indexUrl_indexUrl',this.props.history)
  156. }
  157. localStorage.setItem('lw_menu_config', JSON.stringify(data_menu))
  158. window.location.reload(true);
  159. this.props.isLogin &&
  160. this.props.isLogin({
  161. admin: userinfo.username,
  162. access_token: token,
  163. });
  164. }).catch(() => {
  165. Loading.remove()
  166. })
  167. // this.props.history.push('/index')
  168. // console.log(res,'res')
  169. // location.reload(true);
  170. }
  171. return false;
  172. })
  173. .catch((e) => {
  174. Loading.remove()
  175. // location.reload(true);
  176. this.setState(() => {
  177. return {
  178. loading: false,
  179. };
  180. });
  181. });
  182. }, 200);
  183. }
  184. );
  185. })
  186. .catch((e) => {
  187. console.log("catch")
  188. this.setState(() => {
  189. return {
  190. loading: false,
  191. };
  192. });
  193. });
  194. })
  195. } catch (error) {
  196. console.error('登录请求失败:', error);
  197. Message.error('网络错误,请稍后重试');
  198. }
  199. // 模拟登录请求
  200. // setTimeout(() => {
  201. // // 这里添加实际的登录逻辑
  202. // if (username && password) {
  203. // // 模拟登录成功
  204. // localStorage.setItem('isLoggedIn', 'true');
  205. // setIsLoggedIn(true);
  206. // // 跳转到首页
  207. // navigate('/');
  208. // Message.success('登录成功');
  209. // } else {
  210. // Message.error('登录失败,请检查用户名和密码');
  211. // }
  212. // setLoading(false);
  213. // }, 1000);
  214. };
  215. return (
  216. <div className="bg-gray-50 p-4">
  217. <div className="text-center mb-6">
  218. <h1 className="text-2xl font-bold text-gray-800">登录</h1>
  219. </div>
  220. <Form onSubmit={handleLogin} ref={formRef}>
  221. <Form.Item
  222. label="用户名"
  223. required
  224. help={errors.username}
  225. validateState={errors.username ? 'error' : undefined}
  226. >
  227. <Input
  228. placeholder="请输入用户名"
  229. value={username}
  230. onChange={(value) => {
  231. setUsername(value);
  232. if (errors.username) {
  233. setErrors({ ...errors, username: undefined });
  234. }
  235. }}
  236. disabled={loading}
  237. />
  238. </Form.Item>
  239. <Form.Item
  240. label="密码"
  241. required
  242. help={errors.password}
  243. validateState={errors.password ? 'error' : undefined}
  244. >
  245. <Input
  246. htmlType="password"
  247. placeholder="请输入密码"
  248. value={password}
  249. onChange={(value) => {
  250. setPassword(value);
  251. if (errors.password) {
  252. setErrors({ ...errors, password: undefined });
  253. }
  254. }}
  255. disabled={loading}
  256. />
  257. </Form.Item>
  258. <Row>
  259. <Col span={16}>
  260. <Form.Item
  261. label="验证码"
  262. name="code"
  263. required
  264. >
  265. <Input
  266. size="large"
  267. />
  268. </Form.Item>
  269. </Col>
  270. <Col span={8}>
  271. <img
  272. src={validImg}
  273. style={{
  274. width: 82,
  275. height: 30,
  276. marginTop: 28
  277. }}
  278. onClick={evVerify}
  279. />
  280. </Col>
  281. </Row>
  282. <Form.Item>
  283. <Button
  284. type="primary"
  285. htmlType="submit"
  286. loading={loading}
  287. className="w-full"
  288. >
  289. {loading ? '登录中...' : '登录'}
  290. </Button>
  291. </Form.Item>
  292. </Form>
  293. <div className="mt-4 text-center text-sm text-gray-500">
  294. <p>忘记密码?请联系管理员</p>
  295. </div>
  296. </div>
  297. );
  298. }