/* eslint-disable @typescript-eslint/no-var-requires */
import * as React from "react";
import { useSelector } from "react-redux";
import { Link, useLocation } from "react-router-dom";
import { RouterApi } from "router/types";
import { Layout, Menu } from "antd";
import { UserOutlined } from "@ant-design/icons";
import Router from "router/index";
import { RootState } from "store/store";

const projectConfig = require("configure/projectConfig.json");

const { Sider } = Layout;
const { SubMenu } = Menu;

function SlideMenu() {
  const location = useLocation();
  const user = useSelector((state: RootState) => state.user);
  const authList = user.auth;
  const [slideMenu, setSlideMenu] = React.useState<RouterApi.RouterItem[]>([]);
  const [selectedKeys, setSelectedKeys] = React.useState<string[]>([]);
  const [collapsed, setCollapsedState] = React.useState(false);

  const renderSlideSubMenu = (
    slideMenu: Array<RouterApi.RouterItem>,
    parentPath = ""
  ) =>
    slideMenu.map((item: RouterApi.RouterItem) => {
      const { auth = "", children, path, title, Icon } = item;
      if (
        children &&
        (authList.some((authItem: string) => authItem.startsWith(auth)) ||
          projectConfig.noAuth)
      ) {
        return (
          <SubMenu
            key={`${parentPath}${path}`}
            title={title}
            icon={Icon ? <Icon /> : <UserOutlined />}
          >
            {renderSlideSubMenu(children, `${parentPath}${path}`)}
          </SubMenu>
        );
      }
      if ((authList.includes(auth) || projectConfig.noAuth) && !item.hidden) {
        return (
          <Menu.Item key={`${parentPath}${path}`} icon={Icon ? <Icon /> : null}>
            <Link to={`${parentPath}${path}`}>{title}</Link>
          </Menu.Item>
        );
      }
      return null;
    });

  const getSlideMenuPath = (
    slideMenu: Array<RouterApi.RouterItem>,
    parentPath: string
  ): any =>
    slideMenu.map((item) => {
      const { path, children } = item;
      if (children) {
        return getSlideMenuPath(children, `${parentPath}${path}`);
      }
      return `${parentPath}${path}`;
    });

  const onCollapse = (collapsed: any) => {
    setCollapsedState(collapsed);
  };

  React.useEffect(() => {
    const pathList = location.pathname.split("/").slice(1);
    setSelectedKeys([`/${pathList.join("/")}`]);
  }, [location.pathname]);

  React.useEffect(() => {
    setSlideMenu(Router);
  }, []);

  return slideMenu.length > 0 ? (
    <Sider collapsible collapsed={collapsed} onCollapse={onCollapse}>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKeys}
        style={{ height: "100%", borderRight: 0, overflow: "auto" }}
      >
        {renderSlideSubMenu(slideMenu)}
      </Menu>
    </Sider>
  ) : null;
}
export default SlideMenu;
