import { createComponentLoader } from '@/utils/pathResolver';

// 递归转换嵌套菜单为嵌套路由
export function convertMenusToRoutes(menus) {
  if (!menus || menus.length === 0) return [];

  return menus.map(menu => {
    // 基础路由配置
    const route = {
      path: menu.path || '', // 优先使用菜单path，无则为空字符串
      name: `menu_${menu.id}`,
      meta: {
        icon: menu.icon,
        title: menu.title,
        id: menu.id,
        parentId: menu.pid,
        menuPath: menu.path,
        componentPath: menu.component_path
      }
    };

    // 处理组件路径
    if (menu.type === 4) {
      // 单页类型：使用单页组件，根据路由从单页表获取内容
      route.component = () => import('@/views/onepage/index.vue');
      route.meta.menuType = 4; // 标记为单页类型
    } else if (menu.component_path) {
      // 页面类型：直接使用component_path加载组件
      route.component = createComponentLoader(menu.component_path);
    } else if (menu.children && menu.children.length > 0) {
      // 无组件但有子路由的父菜单，添加默认空组件（避免路由报错）
      route.component = () => import('@/views/layouts/EmptyLayout.vue');
      // 为父菜单添加重定向，指向第一个有效子路由
      const firstValidChild = findFirstValidRoute(menu.children);
      if (firstValidChild && firstValidChild.path) {
        route.redirect = firstValidChild.path;
      }
    }

    // 递归处理子菜单为子路由
    if (menu.children && menu.children.length > 0) {
      route.children = convertMenusToRoutes(menu.children);
    }

    return route;
  });
}

// 查找第一个有效的子路由
function findFirstValidRoute(children) {
  if (!children || children.length === 0) return null;
  for (const child of children) {
    if (child.path && (child.component_path || (child.children && child.children.length > 0))) {
      return child;
    }
    if (child.children && child.children.length > 0) {
      const grandChild = findFirstValidRoute(child.children);
      if (grandChild) return grandChild;
    }
  }
  return null;
}
