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';
import './index.scss';
import { CommonAPI } from '~/api';

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

// 消息字段转换菜单key
const menuKeyMap = [
  { key: 230, label: 'pilotMessage' },
  { key: 240, label: 'joinApplyMessage' },
  { key: 430, label: 'orderMessage' },
  { key: 1010, label: 'dynamicMessage' },
  { key: 250, label: 'userStateMessage' },
  { key: 940, label: 'pointsMallMessage' },
];

export function MenuView() {
  // 菜单栏提醒
  const [itemsAlert, setItemsAlert] = useState<{ key: number; number: number }[]>([]);
  // 侧边栏是否折叠状态
  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) || [];
  };
  // 获取当前菜单是否有tag
  const getTag = (id: number) => {
    return itemsAlert?.find((i) => i.key === id)?.number;
  };
  // 获取侧边栏的数量
  const getMessageNumber = async () => {
    const res = await CommonAPI.getMessage();
    if (res && res.code === '200') {
      if (!res.result) return;
      const arr = Object.entries(res.result);
      const list = arr.map((i) => {
        const key = menuKeyMap?.find((k) => k.label === i[0])?.key || 0;
        return { key, number: Number(i[1]) };
      });
      const brr = [...new Set(list.map((i) => Math.floor(i.key / 100) * 100))].map((i) => {
        return {
          key: i,
          number: list
            .filter((n) => Math.floor(n.key / 100) * 100 === i)
            .reduce((a, b) => a + b.number, 0),
        };
      });
      // console.log('红点 --->', brr);
      setItemsAlert([...list, ...brr]);
    }
  };
  // 组件挂载
  useEffect(() => {
    // 设置侧边栏数据
    authRouterList().then(async (value) => {
      // 除了数据看板，其他没有子项的菜单全部过滤掉
      const arr = getItem(value)?.filter((i: any) => i?.key === 100) || [];
      const brr = getItem(value)?.filter((i: any) => i?.children?.length) || [];
      // 设置要展示的菜单列表
      setItems([...arr, ...brr]);
      // 将方法挂载到全局
      (window as any).getMessageNumber = getMessageNumber;
    });
  }, []);

  useEffect(() => {
    // 设置当前选中的项目
    setOpenKeys([getRoutePid(routerList, location.pathname).toString()]);
    // 设置当前选中的项目的subMenu
    setSelectedKeys([getRouteID(routerList, location.pathname).toString()]);
    // 获取展示的红点
    getMessageNumber().then();
  }, [location.pathname]);
  return (
    <Layout.Sider
      className={'sider-view'}
      style={{ paddingTop: '50px' }}
      collapsible
      width={180}
      trigger={null}
      collapsed={collapsedActive}
    >
      <Menu
        className={'menu-view'}
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        onClick={onSelect}
        onOpenChange={onOpenChange}
        mode='inline'
        // items={items}
        style={{ backgroundColor: ' #F3F6FF ' }}
      >
        {items?.map((i: any) =>
          i?.children ? (
            <Menu.ItemGroup key={i.key}>
              {!!getTag(i.key) && <div className={'menu-subTag'}>{getTag(i.key)}</div>}
              <Menu.SubMenu title={i.label} key={i.key} icon={i.icon}>
                {i?.children?.map((n: any) => (
                  <Menu.Item title={n.label} key={n.key} icon={n.icon}>
                    {n.label}
                    {!!getTag(n.key) && <div className={'menu-tag'}>{getTag(n.key)}</div>}
                  </Menu.Item>
                ))}
              </Menu.SubMenu>
            </Menu.ItemGroup>
          ) : (
            <Menu.Item title={i.label} key={i.key} icon={i.icon}>
              {i.label}
              {!!getTag(i.key) && <div className={'menu-tag'}>{getTag(i.key)}</div>}
            </Menu.Item>
          ),
        )}
      </Menu>
    </Layout.Sider>
  );
}
