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';
import { useSelector } from 'react-redux';
import { authRouterList, routerItem } from '~/router';

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

const { Sider } = Layout;

export function MenuView() {
  // 侧边栏是否折叠状态
  const collapsedActive = useSelector((state: any) => state.Menu.collapsedActive);
  // 菜单路由列表
  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]);
    const id = Number(keys.key);
    const current: routerItem | undefined = GetRouteByID(id, routerList);
    navigate({ pathname: 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(() => {
    // 设置侧边栏数据
    authRouterList().then((value) => {
      // 除了数据看板，其他没有子项的菜单全部过滤掉
      const arr = getItem(value)?.filter((i: any) => i?.key === 100) || [];
      const brr = getItem(value)?.filter((i: any) => i?.children?.length) || [];
      // 设置要展示的菜单列表
      setItems([...arr, ...brr]);
    });
  }, []);

  useEffect(() => {
    // 设置当前选中的项目
    setOpenKeys([getRoutePid(routerList, location.pathname).toString()]);
    // 设置当前选中的项目的subMenu
    setSelectedKeys([getRouteID(routerList, location.pathname).toString()]);
  }, [location.pathname]);
  return (
    <Sider
      style={{ paddingTop: '50px' }}
      collapsible
      width={180}
      trigger={null}
      collapsed={collapsedActive}
    >
      <Menu
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        onClick={onSelect}
        onOpenChange={onOpenChange}
        mode='inline'
        items={items}
        style={{ backgroundColor: ' #F3F6FF ' }}
      />
    </Sider>
  );
}
