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