import { useEffect, useState } from 'react';
import type { MenuProps } from 'antd';
import { Layout, Menu } from 'antd';
import { RouteObjectType, routerList } from '~/router/router';
import { useLocation, useNavigate } from 'react-router-dom';
import { GetRouteByID, getRouteID, getRoutePid } from '~/utils/router';

type MenuItem = Required<MenuProps>['items'][number];

const { Sider } = Layout;

export function MenuView() {
  // 菜单路由列表
  const [items, setItems] = useState<MenuItem[]>([]);
  // 当选选中的项目
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  // 当选选中的项目的subMenu
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  // 路由钩子
  const location = useLocation();
  // 路由跳转钩子
  const navigate = useNavigate();
  // 点击侧边栏事件
  const onOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys([keys[keys.length - 1]]);
  };
  // 点击侧边栏事件 onSelect改为onClick
  const onSelect: MenuProps['onClick'] = (keys) => {
    setSelectedKeys([keys.key]);
    // setSelectedKeys(keys.selectedKeys);
    const id = Number(keys.key);
    const current = GetRouteByID(id, routerList);
    // console.log(current?.path);
    if (current) navigate(current?.path);
  };
  // 递归将路由转换为侧边栏数据
  const getItem = (routerList: RouteObjectType[]) => {
    const list: Array<MenuItem> = routerList.map((i) => {
      if (i.children?.length) {
        return {
          label: i.meta?.title,
          key: i.meta?.id,
          icon: i.meta?.icon,
          children: getItem(i.children || []),
        };
      } else {
        if (!i.meta.hidden) {
          return {
            label: i.meta?.title,
            key: i.meta?.id,
            icon: i.meta?.icon,
          };
        }
      }
    }) as MenuItem[];
    return list?.filter((i) => i !== undefined);
  };
  // 组件挂载
  useEffect(() => {
    // 设置侧边栏数据
    setItems(getItem(routerList));
    // 设置当前选中的项目
    setOpenKeys([getRoutePid(routerList, location.pathname).toString()]);
    // 设置当前选中的项目的subMenu
    console.log(
      '当前选中menu-->',
      getRouteID(routerList, location.pathname),
      location.pathname,
      routerList,
    );
    setSelectedKeys([getRouteID(routerList, location.pathname).toString()]);
  }, []);
  return (
    <Sider style={{ paddingTop: '50px' }} collapsible collapsed={false} width={180} trigger={null}>
      <Menu
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        onClick={onSelect}
        onOpenChange={onOpenChange}
        mode='inline'
        items={items}
        style={{ backgroundColor: ' #F3F6FF ' }}
      />
      {/* <div className="sider-collapsed" onClick={() => setCollapsed(!collapsed)}> */}
      {/*  <Button */}
      {/*    className="collapsed-icon" */}
      {/*    type="link" */}
      {/*    icon={collapsed ? <RightOutlined /> : <LeftOutlined />} */}
      {/*  /> */}
      {/* </div> */}
    </Sider>
  );
}
