import { DageRouteItem } from "@/router";

export const getParentMenuItem = (
  menuItems: DageRouteItem[],
  path: string
): null | DageRouteItem => {
  for (const menuItem of menuItems) {
    if (path.startsWith(menuItem.path || "")) {
      return menuItem;
    }
    if (menuItem.children) {
      const parentMenuItem = getParentMenuItem(menuItem.children, path);
      if (parentMenuItem) {
        return parentMenuItem;
      }
    }
  }
  return null;
};

export const findRouteByPath = (
  routes: DageRouteItem[],
  path: string
): DageRouteItem | null => {
  const temp = path.split("/");

  for (const route of routes) {
    if (route.path.replace(/\/:[^/]+/g, "") === path) {
      return route;
    }
    if (
      // 首层没必要向下遍历
      temp.length !== 2 &&
      route.path.indexOf(temp[1]) > -1 &&
      route.children
    ) {
      const subRoute = findRouteByPath(route.children, path);
      if (subRoute) {
        return subRoute;
      }
    }
  }
  return null;
};
