import { createComponentLoader } from '@/utils/pathResolver';
import { h, resolveComponent as resolveVueComponent } from 'vue';

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

  return menus.map(menu => {
    const route = {
      path: menu.path || '', 
      name: `menu_${menu.id}`,
      meta: {
        title: menu.title,
        icon: menu.icon,
        id: menu.id,
        componentPath: menu.component_path
      }
    };

    // 1. 处理组件加载
    if (menu.type === 4) {
      // 单页类型
      route.component = () => import('@/views/onepage/index.vue');
    } else if (menu.component_path && menu.component_path.trim() !== '') {
      // 正常页面
      route.component = createComponentLoader(menu.component_path);
    } else if (menu.children && menu.children.length > 0) {
      // 目录节点：必须给组件，否则父级无法渲染子级
      route.component = () => import('@/views/layouts/EmptyLayout.vue');
    } else {
      // 异常：既没路径也没子菜单
      route.component = () => import('@/views/404/404.vue');
    }

    // 2. 递归子路由
    if (menu.children && menu.children.length > 0) {
      route.children = convertMenusToRoutes(menu.children);
      
      // 目录节点添加重定向，防止点击父菜单页面空白
      const firstChild = menu.children[0];
      if (firstChild && firstChild.path) {
        route.redirect = firstChild.path;
      }
    }

    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;
}
