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

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

  return menus.map(menu => {
    // 拼接完整的路由路径（处理相对路径）
    const fullPath = menu.path ? 
      (menu.path.startsWith('/') ? menu.path : `${parentPath}/${menu.path}`) 
      : '';

    const route = {
      path: fullPath || 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, fullPath);
      
      // 目录节点添加重定向，防止点击父菜单页面空白
      const firstChild = menu.children[0];
      if (firstChild && firstChild.path) {
        // 计算第一个子路由的完整路径
        const childFullPath = firstChild.path.startsWith('/') ? 
          firstChild.path : 
          `${fullPath}/${firstChild.path}`;
        route.redirect = childFullPath;
      }
    }

    return route;
  });
}
