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 draggable="false" alt="logo" src={LogoImage} />
      </div>

      <div className="login-form">
        <div className="login-form__title">秋收起义纪念馆</div>
        <div className="login-form__subTitle">后台管理系统</div>
        <div className="login-form__enTitle">BACKGROUND MANAGEMENT SYSTEM</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 type="primary" htmlType="submit" loading={loading}>
              登 录
            </Button>
          </div>
        </Form>
      </div>

      <p className="login__tips">
        军叫工农革命，旗号镰刀斧头。匡庐一带不停留，要向潇湘直进。地主重重压迫，
        农民个个同仇。秋收时节暮云愁，霹雳一声暴动。
      </p>
    </div>
  );
}
