import { Button, Form, Input, message } from 'antd';
import { login } from '../../api/user';
import './index.scss';
import { UserOutlined, KeyOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { setUser } from '../../store/slice/user';
import { useNavigate, useSearchParams } from 'react-router-dom';

const onLogin = async (user, { dispatch, navigate }, to = '/') => {
  let {
    data: { code, msg, data },
  } = await login(user);

  if (code == 0) {
    message.success(msg);

    //! 存token
    localStorage.setItem('token', data.token);
    //! redux存储用户信息
    dispatch(setUser(data.user));
    //! 跳转页面：如果有查询参数r 就 到r的地址，否则 去主页
    navigate(to);
    return;
  }

  message.error(msg);
};

function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const to = searchParams.get('r') ? searchParams.get('r') : undefined;

  function onFinish(values) {
    onLogin(values, { dispatch, navigate }, to);
  }

  return (
    <div className="login_container">
      <div className="login">
        <h3>登入系统</h3>
        <Form
          name="basic"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 500,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="账号："
            name="username"
            rules={[
              {
                required: true,
                message: '请输入账号...',
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="账号..." allowClear />
          </Form.Item>

          <Form.Item
            label="密码："
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码...',
              },
            ]}
          >
            <Input.Password
              prefix={<KeyOutlined />}
              placeholder="密码..."
              allowClear
            />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 4,
              span: 18,
            }}
          >
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 4,
              span: 18,
            }}
          >
            <Button type="link" block>
              注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Login;
