import React, { useMemo, useEffect, Suspense } from "react";
import { App, Layout } from "antd";
import { useSelector } from "react-redux";
import { Route, Routes, useNavigate, Navigate } from "react-router-dom";
import { Content } from "antd/es/layout/layout";
import { hasToken, getTokenInfo } from "@dage/pc-components";
import store from "@/store";
import { LayoutMenu, LayoutHeader } from "./components";
import { RootState } from "@/store";
import LogoImage from "@/assets/images/logo.png";
import { DEFAULT_ADMIN_MENU, DEFAULT_MENU, DageRouteItem } from "@/router";
import { MemoSpinLoding } from "@/components";
import "./index.scss";

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

export default function CustomLayout() {
  const navigate = useNavigate();
  const baseStore = useSelector<RootState, RootState["base"]>(
    (state) => state.base
  );
  const menuList = useMemo<DageRouteItem[]>(() => {
    return baseStore.userInfo?.user.isAdmin
      ? [...DEFAULT_MENU, ...DEFAULT_ADMIN_MENU]
      : [...DEFAULT_MENU];
  }, [baseStore.userInfo]);

  useEffect(() => {
    if (!hasToken()) {
      navigate("/login", {
        replace: true,
      });
    } else {
      store.dispatch({ type: "setUserInfo", payload: getTokenInfo() });
    }
  }, [navigate]);

  return (
    <App>
      <Layout hasSider className="layout">
        {/* 菜单 */}
        <Layout.Sider
          width={220}
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            bottom: 0,
            background: "#b6a384",
          }}
        >
          <div className="logo">
            <img draggable="false" alt="logo" src={LogoImage} />
          </div>

          <LayoutMenu
            className="layout-menu"
            theme="dark"
            inlineIndent={20}
            menuData={menuList}
          />
        </Layout.Sider>

        <Layout style={{ marginLeft: 220 }}>
          {/* 头部 */}
          <LayoutHeader menuData={menuList} />

          {/* 主体 */}
          <Content
            style={{
              margin: "15px",
              overflow: "initial",
              position: "relative",
              background: "#ffffff",
              padding: 20,
              borderRadius: 4,
            }}
          >
            <Suspense fallback={<MemoSpinLoding />}>
              {menuList.length && (
                <Routes>
                  <Route
                    path="/"
                    element={
                      <Navigate to={menuList[0].redirect || menuList[0].path} />
                    }
                  />
                  {renderRoutes(menuList).map((menu) =>
                    menu.redirect ? (
                      <Route
                        key={menu.path}
                        path={menu.path}
                        element={<Navigate replace to={menu.redirect} />}
                      />
                    ) : (
                      <Route
                        key={menu.path}
                        path={menu.path}
                        Component={menu.Component}
                      />
                    )
                  )}
                  <Route path="*" Component={NotFound} />
                </Routes>
              )}
            </Suspense>
          </Content>
        </Layout>
      </Layout>
    </App>
  );
}

function renderRoutes(routes: DageRouteItem[]) {
  function deep(v: DageRouteItem[]) {
    const stack: DageRouteItem[] = [];
    v.forEach((item) => {
      const { children = [], ...rest } = item;

      stack.push(rest);

      if (!!children.length) {
        stack.push(...deep(children));
      }
    });
    return stack;
  }

  return deep(routes);
}
