import { useState } from 'react';
import { useNavigate, useParams } from "react-router-dom";
import { login } from '@/services/user';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { message, Form, Button, Input } from 'antd';
import md5 from 'md5';
import { useModel } from '@/store';
import Logo from '@/assets/images/logo.png';
import decorateLeft from '@/assets/images/login/装饰左.png';
import decorateRight from '@/assets/images/login/装饰右.png';
import './index.less';

const errStyle = {color: 'red', paddingBottom: '10px'}

const Login = () => {
  const urlParams = useParams();
  const { setUser } = useModel('user');
  const [errMsg, setErrMsg] = useState();

  const navigate = useNavigate();

  const handleSubmit = async (values) => {
    try {
      // 登录
      const res = await login({ ...values, password: md5(values.password) });
      console.log(res);

      const defaultLoginSuccessMessage = '登录成功！';
      message.success(defaultLoginSuccessMessage);
      
      setUser(res.user);      
      if (urlParams.back) {
        navigate(-1);
      } else {
        navigate('/');
      }
      return;      
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="login-container">
      <Form name="login" id="login" onFinish={handleSubmit}>
        <div className="form-left">
          <img src={Logo} />
        </div>
        <div className="form-right">
          <h2>用户登录</h2>
          <div className="sub-title">
            <img src={decorateLeft} alt="" />
            <span>Welcome</span>
            <img src={decorateRight} alt="" />
          </div>
          <div id="msg" style={errStyle}>{errMsg}</div>
          <Form.Item className="input-control" name="userName" required>
            <Input type="text" prefix={<UserOutlined />} className="form-control cust-input" placeholder="用户名" />
          </Form.Item>
          <Form.Item className="input-control" name="password" required>
            <Input type="password" prefix={<LockOutlined />} className="form-control cust-input" placeholder="密码" />
          </Form.Item>
          <Form.Item className="form-group" style={{ marginBottom: '60px' }}>
            <Button type="primary" className="btn-primary" htmlType="submit">登 录</Button>
          </Form.Item>
        </div>
      </Form>
    </div>
  );
};

export default Login;
