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

function computeFullPath(menuPath, parentPath) {
  if (!menuPath) return parentPath || '';
  if (menuPath.startsWith('/')) {
    return menuPath.replace(/\/+/g, '/');
  }
  const base = (parentPath || '').replace(/\/$/, '');
  return `${base}/${menuPath}`.replace(/\/+/g, '/');
}

/** 将子路由的绝对路径转为相对父布局的路径，供 Vue Router 嵌套使用 */
function toRelativeChildPath(parentAbs, childAbs) {
  const base = (parentAbs || '').replace(/\/$/, '');
  const target = (childAbs || '').replace(/\/$/, '');
  if (!target) return '';
  if (target === base) return '';
  const prefix = `${base}/`;
  if (target.startsWith(prefix)) {
    return target.slice(prefix.length);
  }
  // 兜底：取最后一段（菜单 path 配置异常时）
  const parts = target.split('/').filter(Boolean);
  return parts.length ? parts[parts.length - 1] : '';
}

function hasPageComponent(menu) {
  return menu.type === 4 || (menu.component_path && String(menu.component_path).trim() !== '');
}

function resolvePageComponent(menu) {
  if (menu.type === 4) {
    return () => import('@/views/onepage/index.vue');
  }
  if (menu.component_path && String(menu.component_path).trim() !== '') {
    return createComponentLoader(menu.component_path);
  }
  return () => import('@/views/404/404.vue');
}

/**
 * 菜单子节点 -> 嵌套路由（path 相对 layoutAbsPath）
 */
function convertNestedMenuChildren(children, layoutAbsPath) {
  if (!children || children.length === 0) return [];
  return children.map((child) => nestedMenuToRoute(child, layoutAbsPath));
}

function nestedMenuToRoute(menu, layoutAbsPath) {
  const childAbs = computeFullPath(menu.path, layoutAbsPath);
  const relPath = toRelativeChildPath(layoutAbsPath, childAbs);
  const hasChildren = menu.children && menu.children.length > 0;
  const ownPage = hasPageComponent(menu);

  const meta = {
    title: menu.title,
    icon: menu.icon,
    id: menu.id,
    componentPath: menu.component_path,
  };

  // 既有自己的页面又有子菜单：套一层 EmptyLayout，避免父页面组件里没有 <router-view> 导致子路由无法渲染
  if (hasChildren && ownPage) {
    return {
      path: relPath,
      name: `menu_${menu.id}`,
      meta,
      component: () => import('@/views/layouts/EmptyLayout.vue'),
      children: [
        {
          path: '',
          name: `menu_${menu.id}_index`,
          meta: { ...meta },
          component: resolvePageComponent(menu),
        },
        ...convertNestedMenuChildren(menu.children, childAbs),
      ],
    };
  }

  // 纯目录 + 子节点
  if (hasChildren && !ownPage) {
    const route = {
      path: relPath,
      name: `menu_${menu.id}`,
      meta,
      component: () => import('@/views/layouts/EmptyLayout.vue'),
      children: convertNestedMenuChildren(menu.children, childAbs),
    };
    const firstChild = menu.children[0];
    if (firstChild && firstChild.path) {
      const firstAbs = computeFullPath(firstChild.path, childAbs);
      const firstRel = toRelativeChildPath(childAbs, firstAbs);
      if (firstRel) {
        route.redirect = firstRel;
      }
    }
    return route;
  }

  // 叶子页面
  return {
    path: relPath,
    name: `menu_${menu.id}`,
    meta,
    component: resolvePageComponent(menu),
  };
}

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

  return menus
    // 平台端：只转换 isPlatform !== 0 的菜单（默认视为平台可见）
    .filter((menu) => menu.isPlatform === undefined || Number(menu.isPlatform) !== 0)
    .map((menu) => {
    const fullPath = menu.path
      ? menu.path.startsWith('/')
        ? menu.path.replace(/\/+/g, '/')
        : `${(parentPath || '').replace(/\/$/, '')}/${menu.path}`.replace(/\/+/g, '/')
      : '';

    const hasChildren = menu.children && menu.children.length > 0;
    const ownPage = hasPageComponent(menu);

    const meta = {
      title: menu.title,
      icon: menu.icon,
      id: menu.id,
      componentPath: menu.component_path,
    };

    // 顶层：有页面 + 有子菜单 -> EmptyLayout + 默认子路由 + 相对 path 子路由
    if (hasChildren && ownPage) {
      return {
        path: fullPath || menu.path || '',
        name: `menu_${menu.id}`,
        meta,
        component: () => import('@/views/layouts/EmptyLayout.vue'),
        children: [
          {
            path: '',
            name: `menu_${menu.id}_index`,
            meta: { ...meta },
            component: resolvePageComponent(menu),
          },
          ...convertNestedMenuChildren(menu.children, fullPath),
        ],
      };
    }

    const route = {
      path: fullPath || menu.path || '',
      name: `menu_${menu.id}`,
      meta,
    };

    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 (hasChildren) {
      route.component = () => import('@/views/layouts/EmptyLayout.vue');
      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;
      }
    } else {
      route.component = () => import('@/views/404/404.vue');
    }

    return route;
  });
}
