import React, { useEffect, useContext } from "react";
import { Menu, Layout, theme } from "antd";
import { useState } from "react";
import "../container/index.less";
import { useNavigate } from "react-router-dom";

const { Sider } = Layout;

export default function sider (props) {
   const navigate = useNavigate();
   const { token: { colorBgContainer }, } = theme.useToken();
   const { collapsed } = props
   const [menuItems, setMenuItems] = useState([]);
   const [openKeys, setOpenKeys] = useState([])
   const [selectedKeys, setSelectedKeys] = useState([])

   useEffect(() => {
      const siderNav = (nav = []) => {
         return nav.filter(item => item.nav)
            .map(item => {
               return {
                  label: item.label,
                  key: item.path,
                  icon: item.icon,
                  children: item.children && siderNav(item.children),
               };
            })
      };

      setMenuItems(siderNav(props.routerNav))
   }, [props.routerNav])

   useEffect(() => {
      let siderOpenKeys = sessionStorage.getItem('siderOpenKeys')
      if (siderOpenKeys) {
         setOpenKeys(JSON.parse(siderOpenKeys))
      }
      let siderSelectKeys = sessionStorage.getItem('siderSelectKeys')
      if (siderSelectKeys) {
         setSelectedKeys(JSON.parse(siderSelectKeys))
      }
   }, [])

   return (
      <Sider
         collapsed={collapsed}
         style={{
            background: colorBgContainer,
         }}
      >
         <div style={{
            height: '100%', overflow: 'auto', scrollbarWidth: 'thin',
         }}>
            <Menu
               mode="inline"
               items={menuItems}
               selectedKeys={selectedKeys}
               openKeys={openKeys}
               onClick={({ keyPath, key }) => {
                  let url = keyPath.reduce((pre, cur) => {
                     return cur + '/' + pre;
                  }, '');
                  navigate(url);
                  sessionStorage.setItem('siderSelectKeys', JSON.stringify([key]));
                  setSelectedKeys([key]);
               }}
               onOpenChange={(openKeys) => {
                  sessionStorage.setItem('siderOpenKeys', JSON.stringify(openKeys));
                  setOpenKeys(openKeys);
               }}
            />
         </div>

      </Sider>
   );
}
