import { getTokenInfo, removeTokenInfo } from "@/utils/storage";
import styles from "./index.module.scss";
import classNames from "classnames";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Popconfirm, Button, Modal, Form, Input } from "antd";
import React from "react";
import { Route, Switch, useLocation } from "react-router-dom";
import history from "@/utils/history";
import SpinLoding from "@/components/SpinLoding";
import AuthRoute from "@/components/AuthRoute";
import { Base64 } from "js-base64";
import encodeStr from "@/utils/pass";
import {
  getPowerInfoAPI,
  getSelectAllAPI,
  passWordEditAPI,
} from "@/store/action/login";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import { MessageFu } from "@/utils/message";

const NotFound = React.lazy(() => import("../../components/NotFound"));

function Layout() {
  const dispatch = useDispatch();

  const tabListTemp = useMemo(() => {
    return [
      {
        id: 1,
        done: true,
        Com: React.lazy(() => import("../Home")),
        path: "/",
        name: "首页",
      },
      {
        id: 2,
        done: false,
        Com: React.lazy(() => import("../Object")),
        path: "/object",
        name: "馆藏管理",
      },
      {
        id: 3,
        done: true,
        Com: React.lazy(() => import("../Stores")),
        path: "/stores",
        name: "库房管理",
      },
    ];
  }, []);

  const [tabList, setTabList] = useState(tabListTemp);

  // 进页面获取权限信息
  const getPowerInfoAPIFu = useCallback(async () => {
    const res = await getPowerInfoAPI();
    const tempArr = res.data.filter((v: any) => v.authority);
    // 页面权限信息存到仓库
    dispatch({ type: "login/setAuthPageArr", payload: tempArr });
    // 按钮的权限信息存到仓库
    const buttonArr = [] as any;
    tempArr.forEach((v: any) => {
      v.children.forEach((v2: any) => {
        if (v2.authority) buttonArr.push(v2);
      });
    });
    dispatch({ type: "login/setAuthButtonArr", payload: buttonArr });
  }, [dispatch]);

  // 获取页面权限信息
  const powerInfo = useSelector(
    (state: RootState) => state.loginStore.authPageArr
  );

  useEffect(() => {
    getPowerInfoAPIFu();
  }, [getPowerInfoAPIFu]);

  useEffect(() => {
    const temp = getTokenInfo().user.isAdmin;
    if (temp === 1 && tabListTemp.length <= 3)
      tabListTemp.push({
        id: 4,
        done: true,
        Com: React.lazy(() => import("../System")),
        path: "/system",
        name: "系统管理",
      });

    powerInfo.forEach((v: any) => {
      if (
        v.id === 100 ||
        v.id === 200 ||
        v.id === 300 ||
        v.id === 400 ||
        v.id === 500 ||
        v.id === 600
      ) {
        tabListTemp[1].done = true;
      }
    });

    setTabList(tabListTemp.filter((v) => v.done));
  }, [powerInfo, tabListTemp]);

  const location = useLocation();
  const [path, setPath] = useState("");

  useEffect(() => {
    const arr = location.pathname.split("/");
    let pathTemp = "/";
    if (arr[1]) pathTemp = "/" + arr[1];

    setPath(pathTemp);
  }, [location]);

  const userInfo = useMemo(() => {
    return getTokenInfo().user;
  }, []);

  // 顶部路由跳转
  const pathCutFu = (path: string) => {
    history.push(path);
  };

  // 修改密码相关
  const [open, setOpen] = useState(false);

  // 拿到新密码的输入框的值
  const oldPasswordValue = useRef("");

  const checkPassWord = (rule: any, value: any = "") => {
    if (value !== oldPasswordValue.current)
      return Promise.reject("新密码不一致!");
    else return Promise.resolve(value);
  };

  const onFinish = async (values: any) => {
    // 通过校验之后发送请求
    if (values.oldPassword === values.newPassword)
      return MessageFu.warning("新旧密码不能相同!");
    const obj = {
      oldPassword: encodeStr(Base64.encode(values.oldPassword)),
      newPassword: encodeStr(Base64.encode(values.newPassword)),
    };
    const res: any = await passWordEditAPI(obj);
    if (res.code === 0) {
      MessageFu.success("修改成功!");
      loginExit();
    }
  };

  // 点击退出登录
  const loginExit = () => {
    removeTokenInfo();
    history.push("/login");
  };

  // 进来获取所有的下拉列表信息
  useEffect(() => {
    dispatch(getSelectAllAPI());
  }, [dispatch]);

  return (
    <div className={styles.Layout}>
      <div className="topTitle">
        <div className="main">
          <div className="logo"></div>
          <div className="tabCut">
            {tabList.map((v: any) => (
              <div
                onClick={() => pathCutFu(v.path)}
                className={classNames("row", v.path === path ? "active" : "")}
                key={v.id}
              >
                {v.name}
              </div>
            ))}
          </div>
          <div className="user">
            {userInfo.realName}
            <div className="userSet">
              <span onClick={() => setOpen(true)}>修改密码</span>
              <Popconfirm
                title="确定退出吗?"
                okText="确定"
                cancelText="取消"
                onConfirm={loginExit}
              >
                退出登录
              </Popconfirm>
            </div>
          </div>
        </div>
      </div>
      {/* 二级路由页面 */}
      <div className="pageMain">
        <React.Suspense fallback={<SpinLoding />}>
          <Switch>
            {tabList.map((v: any, i: number) => (
              <AuthRoute
                key={v.id}
                exact={i === 0 ? true : false}
                path={v.path}
                component={v.Com}
              />
            ))}
            <Route path="*" component={NotFound} />
          </Switch>
        </React.Suspense>
      </div>
      {/* 点击修改密码打开的对话框 */}
      <Modal
        destroyOnClose
        open={open}
        title="修改密码"
        onCancel={() => setOpen(false)}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <Form
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: "不能为空!" }]}
          >
            <Input.Password maxLength={15} />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: "不能为空!" }]}
          >
            <Input.Password
              maxLength={15}
              onChange={(e) => (oldPasswordValue.current = e.target.value)}
            />
          </Form.Item>

          <Form.Item
            label="确定新密码"
            name="checkPass"
            rules={[{ validator: checkPassWord }]}
          >
            <Input.Password maxLength={15} />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 14, span: 16 }}>
            <Button onClick={() => setOpen(false)}>取消</Button>
            &emsp;
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

const MemoLayout = React.memo(Layout);

export default MemoLayout;
