import { verifyUrl } from '@/utils/verify';
import type { RouteRecordRaw } from 'vue-router';

/** 给路路径加上级路由的路径 */
export function prefixPathRoutes(routes: RouteRecordRaw[], baseUrl = ''): RouteRecordRaw[] {
  const newRoutes = routes.map((route) => {
    const path = !verifyUrl(route.path) ? mergePath(baseUrl, route.path) : route.path;
    route.path = path || '';
    if (route.children && Array.isArray(route.children) && route.children.length > 0) {
      route.children = prefixPathRoutes(route.children, route.path);
      // if (!route.redirect) {
      //   // 因为没有中间页面所以当有children 时要强制重定向
      //   route.redirect = route.children[0]!.redirect || route.children[0]!.path;
      // }
    }
    return route;
  });

  return newRoutes;
}

/**
 * 递归扩展多级路由为一级路由
 */
export function fatteningRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  return routes.flatMap((route: RouteRecordRaw) => {
    if (route.children) {
      const newRoute = { ...route };
      delete newRoute.children;
      route.children.unshift(newRoute);
      return fatteningRoutes(route.children);
    } else {
      return route;
    }
  });
}

/**
 * 展开路由 多级路由展开成最多二级路由
 */
export function unfoldRoutes(routes: RouteRecordRaw[]): readonly RouteRecordRaw[] {
  const newRoutes = routes.map((route: RouteRecordRaw) => {
    if (route.children) {
      route.children = fatteningRoutes(route.children);
    }
    return route;
  });
  return newRoutes;
}

/**
 * 合并路径 (路径2为斜杠开头就直接返回路径2,否则就返回组合路径)
 */
function mergePath(u1: string, u2: string): string {
  if (u2) {
    // 路径2为斜杠开头就直接返回路径2,否则就返回组合路径
    const url = u2.startsWith('/') ? u2 : u1 + (u1 === '/' ? '' : '/') + u2;
    // 如果有双斜杠就替换为一个斜杠
    return url.replace(/\/\//g, '/');
  } else {
    // 路径2不存在就直接返回路径1
    return u1;
  }
}
