menu.ts 2.6 KB
/**
 * 菜单相关工具函数
 */
import { getRouteConfig, transformMenuConfig } from '@/api/route';
import { useMenuStore } from '@/stores';
import { getMicroAppByPath } from '@/qiankun/apps';

/**
 * 获取第一个子应用的第一个菜单的第一个子菜单路径
 * @returns 返回路径,如果没有找到则返回 '/home'
 */
export function getFirstSubAppFirstMenuPath(): string {
  const menuStore = useMenuStore();
  const topMenus = menuStore.topMenus;
  console.log('[菜单工具] 获取默认路径,顶级菜单数量:', topMenus.length);
  
  // 排除首页,找到第一个子应用
  const firstSubApp = topMenus.find(
    (menu) => menu.path !== '/home' && menu.path !== '/',
  );

  if (
    !firstSubApp ||
    !firstSubApp.sidebarMenus ||
    firstSubApp.sidebarMenus.length === 0
  ) {
    console.log('[菜单工具] 未找到有效的子应用菜单,返回默认路径 /home');
    return '/home';
  }

  // 获取第一个菜单项
  const firstMenu = firstSubApp.sidebarMenus[0];

  // 如果第一个菜单有子菜单,返回第一个子菜单的路径
  if (firstMenu.children && firstMenu.children.length > 0) {
    const targetPath = firstMenu.children[0].path;
    console.log('[菜单工具] 默认路径:', targetPath, '是否为微应用路由:', !!getMicroAppByPath(targetPath));
    return targetPath;
  }

  // 如果没有子菜单,返回第一个菜单本身的路径
  const targetPath = firstMenu.path;
  console.log('[菜单工具] 默认路径:', targetPath, '是否为微应用路由:', !!getMicroAppByPath(targetPath));
  return targetPath;
}

/**
 * 加载菜单并获取默认跳转路径
 * @returns 返回默认跳转路径
 */
export async function loadMenusAndGetDefaultPath(): Promise<string> {
  const menuStore = useMenuStore();

  try {
    // 如果菜单已加载,直接获取路径
    if (menuStore.isMenusLoaded) {
      console.log('[菜单工具] 菜单已加载,直接获取默认路径');
      return getFirstSubAppFirstMenuPath();
    }

    console.log('[菜单工具] 开始加载菜单配置...');
    // 加载菜单配置
    const response = await getRouteConfig();
    if (response.code === 200 && response.data) {
      const { topMenus } = transformMenuConfig(response.data);
      menuStore.setTopMenus(topMenus);
      console.log('[菜单工具] 菜单配置加载成功');
      return getFirstSubAppFirstMenuPath();
    }
  } catch (error) {
    console.error('[菜单工具] 加载菜单配置失败:', error);
  }

  // 如果加载失败,返回默认路径
  console.log('[菜单工具] 加载失败,返回默认路径 /home');
  return '/home';
}