import { Menu, MenuProps } from "antd";
import { FC, memo, useCallback, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { DageRouteItem } from "@/router";
import { findRouteByPath } from "../../utils";

export interface LayoutMenuProps extends Omit<MenuProps, "mode" | "items"> {
  /** 菜单内容 */
  menuData: DageRouteItem[];
  /**
   * 最大可展示层级
   * @default 2
   */
  maxShowLevel?: number;
}

export const LayoutMenu: FC<LayoutMenuProps> = memo(
  ({ menuData, maxShowLevel = 2, ...rest }) => {
    const location = useLocation();
    const navigate = useNavigate();
    const defaultOpenKeys = useMemo(() => {
      let currentPath = "";
      const stack: string[] = [];
      const paths = location.pathname.split("/").filter((path) => path !== "");
      for (let i = 0; i < paths.length - 1; i++) {
        currentPath += `/${paths[i]}`;
        const item = findRouteByPath(menuData, currentPath);
        if (item) {
          stack.push(item.path);
        }
      }
      return stack;
    }, [menuData, location]);

    const renderMenuItems = useCallback(
      (list: DageRouteItem[], level = 1): any[] => {
        return list.map((item) => {
          const { title, path, icon, children, hide } = item;

          if (hide) return null;

          if (level <= maxShowLevel - 1 && children) {
            return {
              key: path,
              icon: icon,
              label: title,
              children: renderMenuItems(children, level + 1),
            };
          }

          return {
            key: path,
            icon: icon,
            label: title,
          };
        });
      },
      [maxShowLevel]
    );

    const handleMenu = useCallback(
      (item: any) => {
        navigate(item.key);
      },
      [navigate]
    );

    return (
      <Menu
        mode="inline"
        items={renderMenuItems(menuData)}
        selectedKeys={[location.pathname]}
        defaultOpenKeys={defaultOpenKeys}
        onClick={handleMenu}
        {...rest}
      />
    );
  }
);
