import { useState } from "react";
import { Button, Form, Input } from "antd";
import { useNavigate } from "react-router-dom";
import { Base64 } from "@dage/utils";
import { encodeStr, setTokenInfo } from "@dage/pc-components";
import { login } from "@/api";
import { LoginRequest } from "@/types";
import { DEFAULT_ADMIN_MENU, DEFAULT_MENU } from "@/router";
import IconAccount from "./images/icon_ac-min.png";
import IconPassword from "./images/icon_pw-min.png";
import LogoIcon from "./images/logo_black-min.png";
import "./index.scss";

export default function Login() {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleLogin = async (vals: LoginRequest) => {
    setLoading(true);

    const obj = {
      userName: vals.userName,
      passWord: encodeStr(Base64.encode(vals.passWord as string)),
    };

    try {
      const data = await login(obj);
      const list = data.user.isAdmin
        ? [...DEFAULT_MENU, ...DEFAULT_ADMIN_MENU]
        : [...DEFAULT_MENU];

      // 用户信息存到本地
      setTokenInfo(data);
      navigate(list[0].redirect || list[0].path, {
        replace: true,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login">
      <div className="login-img" />

      <div className="login-form">
        <img
          alt="logo"
          className="login-form__logo"
          src={LogoIcon}
          draggable={false}
        />

        <Form className="login-form__input" onFinish={handleLogin}>
          <Form.Item
            name="userName"
            rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input
              prefix={
                <img className="icon-account" src={IconAccount} alt="账号" />
              }
              placeholder="请输入用户名"
              maxLength={15}
              variant="filled"
            />
          </Form.Item>
          <Form.Item
            name="passWord"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input.Password
              prefix={
                <img className="icon-password" src={IconPassword} alt="密码" />
              }
              autoComplete="new-password"
              placeholder="请输入用户密码"
              maxLength={15}
              variant="filled"
            />
          </Form.Item>

          {/* 登录按钮 */}
          <div className="login-form__btn">
            <Button type="primary" htmlType="submit" loading={loading}>
              登 录
            </Button>
          </div>
        </Form>
      </div>
    </div>
  );
}
