import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { CaretUpOutlined, CaretDownOutlined } from "@ant-design/icons";
import styles from "./index.module.scss";
import SpinLoding from "@/components/SpinLoding";
import { Route, Switch, useLocation } from "react-router-dom";
import AuthRoute from "@/components/AuthRoute";
import classNames from "classnames";
import history from "@/utils/history";
import { Button, Form, Input, Modal, Popconfirm } from "antd";
import { Base64 } from "js-base64";
import encodeStr from "@/utils/pass";
import { passWordEditAPI } from "@/store/action/layout";
import { getTokenInfo, removeTokenInfo } from "@/utils/storage";
import { useDispatch, useSelector } from "react-redux";
import inco1 from "@/assets/img/inco1.png";
import inco3 from "@/assets/img/inco3.png";

import logonImg from "@/assets/img/logo-white.png";
import { MessageFu } from "@/utils/message";
import { RouterType } from "@/types";
import { RootState } from "@/store";

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

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

  const listTemp = useMemo(() => {
    const arr: RouterType = [
      {
        id: 100,
        name: "分享管理",
        path: "/",
        Com: React.lazy(() => import("../A2Share")),
        inco: inco1,
        done: true,
      },
    ];
    return arr;
  }, []);

  // 从仓库中获取页面权限数据
  const authPageArr = useSelector(
    (state: RootState) => state.A0Layout.authPageArr
  );

  useEffect(() => {
    // 如果是超级管理员
    const userInfo = getTokenInfo().user;
    if (userInfo.isAdmin === 1) {
      listTemp.push({
        id: 300,
        name: "用户管理",
        path: "/user",
        Com: React.lazy(() => import("../A3User")),
        inco: inco3,
        done: true,
      });
    }
  }, [listTemp]);

  // 权限的数据和页面判断
  useEffect(() => {
    if (authPageArr && authPageArr.length) {
      authPageArr.forEach((v) => {
        if (v.authority) {
          listTemp.forEach((v2) => {
            if (v.id === v2.id) v2.done = true;
          });
        }
      });
      const newList = listTemp.filter((v) => v.done);
      setList(newList);
    }
  }, [authPageArr, listTemp]);

  const [list, setList] = useState(listTemp);

  // 进页面看看第一个页面有权限的是哪一个
  useEffect(() => {
    const userInfo = getTokenInfo().user;
    if (userInfo.isAdmin !== 1) {
      if (list[0] && list[0].id !== 100) history.replace(list[0].path);
    }
  }, [list]);

  // 进页面获取所有下拉信息和权限信息
  useEffect(() => {
    // dispatch(getDictListAPI());
    // dispatch(getPermissionsAPI());
  }, [dispatch]);

  // 点击跳转
  const pathCutFu = useCallback((path: string) => {
    history.push(path);
  }, []);

  // 当前路径选中的左侧菜单
  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 [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");
  };

  return (
    <div className={styles.Layout}>
      <div className="top">
        <div className="iconBox">
          <img src={logonImg} alt="" />
        </div>
        <div className="layoutRightTop">
          {/* 用户相关 */}
          <div className="user">
            {userInfo.realName}
            <div className="userInco userInco1">
              <CaretUpOutlined />
            </div>
            <div className="userInco userInco2">
              <CaretDownOutlined />
            </div>
            <div className="userSet">
              <span onClick={() => setOpen(true)}>修改密码</span>
              <Popconfirm
                placement="bottom"
                title="确定退出吗?"
                okText="确定"
                cancelText="取消"
                onConfirm={loginExit}
              >
                退出登录
              </Popconfirm>
            </div>
          </div>
        </div>
      </div>
      <div className="bottom">
        {/* 左边 */}
        <div className="layoutLeft">
          {/* 左边主体 */}
          <div className="layoutLeftMain">
            {list.map((v) => (
              <div
                hidden={!v.done}
                key={v.id}
                onClick={() => pathCutFu(v.path)}
                className={classNames(
                  "mainBoxL2Row",
                  v.path === path ? "active" : ""
                )}
              >
                <div className="txt">{v.name}</div>
              </div>
            ))}
          </div>
        </div>
        {/* 右边 */}
        <div className="layoutRight">
          {/* 右边主体 */}
          <div className="layoutRightMain">
            {/* 二级路由页面 */}
            <div className="mainBoxR">
              <React.Suspense fallback={<SpinLoding />}>
                <Switch>
                  {list.map((v) => (
                    <AuthRoute
                      key={v.id}
                      exact
                      path={v.path}
                      component={v.Com}
                    />
                  ))}

                  <Route path="*" component={NotFound} />
                </Switch>
              </React.Suspense>
            </div>
          </div>
        </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: "不能为空!" },
                { min: 6, max: 15, message: "密码长度为6-15个字符!" },
              ]}
            >
              <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>
    </div>
  );
}

// 使用 React.memo 来优化组件，避免组件的无效更新，类似 类组件里面的PureComponent
const MemoLayout = React.memo(Layout);
export default MemoLayout;
