import { useState } from "react";
import { Button, Form, Input } from "antd";
import { Base64 } from "js-base64";
import { useNavigate } from "react-router-dom";
import encodeStr from "@/utils/pass";
import { LoginRequest } from "@/types";
import { login } from "@/api";
import { setTokenInfo } from "@dage/web-components";
import IconAccount from "./images/icon_account.png";
import IconPassword from "./images/icon_password.png";
import LogoImage from "../../assets/images/logo.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);

      // 用户信息存到本地
      setTokenInfo(data);
      navigate("/weapon", {
        replace: true,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login">
      <div className="login-logo">
        <img alt="logo" src={LogoImage} />
        <div className="login-logo__txt">
          {"上海工业博物馆后台界面".split("").map((t) => (
            <span key={t}>{t}</span>
          ))}
        </div>
      </div>

      <div className="login-form">
        <div className="login-form__title">登 录</div>

        <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}
              bordered={false}
            />
          </Form.Item>
          <Form.Item
            name="passWord"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input.Password
              prefix={
                <img className="icon-password" src={IconPassword} alt="密码" />
              }
              placeholder="请输入用户密码"
              maxLength={15}
              bordered={false}
            />
          </Form.Item>

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