import { Content, Footer, Header } from "antd/es/layout/layout";
import "./layout.less";
import { inject, observer } from "mobx-react";
import { Store } from "antd/es/form/interface";
import { useEffect, useState } from "react";
import { Avatar, Breadcrumb, Layout, Menu, MenuProps, theme } from "antd";
import { UserOutlined } from "@ant-design/icons";
import Sider from "antd/es/layout/Sider";
import { items, headItems } from "./layout_config";
import { Dropdown } from "antd/lib";
import { Outlet, useNavigate } from "react-router";

const getLevelKeys = (items1) => {
  const key: Record<string, number> = {};
  const func = (items2: [], level = 1) => {
    items2.forEach((item: any) => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};
const levelKeys = getLevelKeys(items);

const LayOut = (props: Store) => {
  const { usrStore } = props;
  const [collapsed, setCollapsed] = useState(false);
  const nav = useNavigate();
  const [muens, setMenus] = useState([])
  const [uName, setUname] = useState("")

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();
  const headStyle = {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
  };
  const logoStyle = { width: 60, color: "white" };
  const contentstyle = {
    padding: "12px 0px 12px 12px",
    margin: 0,
    minHeight: 280,
    background: colorBgContainer,
    borderRadius: borderRadiusLG,
  };
  const breadItem = [
    { title: "首页" },
    { title: "数据集管理" },
    { title: "数据管理" },
  ];
  const [stateOpenKeys, setStateOpenKeys] = useState(['2', '23']);
  useEffect(() => {
    const uData = window.localStorage.getItem("user") ?? '';
    setUname(JSON.parse(uData).user.user_name)
    usrStore.getMenu().then((res) => {
      const men: any = [];
      res.forEach(ele => {
        items.forEach((v: any) => {
          if (ele.router_path === v.key) {
            if (ele.children?.length > 0) {
              const childs: any = []
              ele.children?.forEach(eles => {
                v.children?.forEach(vs => {
                  if (eles.router_path === vs.key) {
                    childs.push(vs)
                  }
                });
              });
              v.children = childs
            }
            men.push(v)
          }
        })
      });
      setMenus(men)
    })
  }, [usrStore, usrStore.isNeedLogin]);
  const onOpenChange: MenuProps['onOpenChange'] = (openKeys) => {
    const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
    // open
    if (currentOpenKey !== undefined) {
      const repeatIndex = openKeys
        .filter((key) => key !== currentOpenKey)
        .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);

      setStateOpenKeys(
        openKeys
          .filter((_, index) => index !== repeatIndex)
          .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey]),
      );
    } else {
      // close
      setStateOpenKeys(openKeys);
    }
  };

  return (
    <Layout>
      <Header style={headStyle}>
        <div style={logoStyle}>黄甲数据</div>
        <Dropdown menu={{
          items: headItems, selectable: true, onClick: (e) => {
            if (e.key === "loginout") {
              window.localStorage.removeItem("token")
              nav("/login")
              return
            }
            nav(e.key)
          }
        }}>
          <div>
            <span style={{ color: "#fff" }}>欢迎回来 {uName}</span>
            <Avatar icon={<UserOutlined />} />
          </div>
        </Dropdown>
      </Header>
      <Layout>
        <Sider
          width={150}
          style={{ background: colorBgContainer }}
          collapsible
          collapsed={collapsed}
          onCollapse={(value) => setCollapsed(value)}
        >
          <Menu
            mode="inline"
            theme="dark"
            defaultSelectedKeys={["1"]}
            openKeys={stateOpenKeys}
            style={{ height: "100%", borderRight: 0 }}
            onOpenChange={onOpenChange}
            items={muens}
            onClick={(e) => {
              nav(e.key);
            }}
          />
        </Sider>
        <Layout style={{ padding: "0 15px 15px" }}>
          <Breadcrumb items={breadItem} style={{ margin: "10px 0" }} />
          <Content style={contentstyle}>
            <Outlet />
          </Content>
          <Footer style={{ textAlign: "center" }}>
            Ant Design ©{new Date().getFullYear()} Created by Ant UED
          </Footer>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default inject("usrStore")(observer(LayOut));
