import path from "path";
/*
 *获取所有的子集路由
 */
const getChildrenRoutes = (routes) => {
  const result = [];
  routes.forEach((route) => {
    if (route.children && route.children.length > 0) {
      result.push(...route.children);
    }
  });
  return result;
};

/*
 *处理脱离层级的路由
 */
// 过滤路由的一个方法
export const filterRoutes = (routes) => {
  //获取到所有的子集路由
  const childrenRoutes = getChildrenRoutes(routes);
  //根据子集路由进行查重操作
  return routes.filter((route) => {
    //根据route在childrenRoutes中进行查重，把所有重复路由表 剔除
    return !childrenRoutes.find((childrenRoute) => {
      return childrenRoute.path === route.path;
    });
  });
};

function isNull(data) {
  if (!data) return true;
  if (JSON.stringify(data) === "{}") return true;
  if (JSON.stringify(data) === "[]") return true;
  return false;
}

/*
 *根据routes（filterRoutes） 数据， 返回对应的menu规则数据
 */
export function generateMenus(routes, basePath = "", level = 1) {
  const result = [];

  routes.forEach((item) => {
    if (isNull(item.meta) && isNull(item.children)) return;

    if (isNull(item.meta) && !isNull(item.children)) {
      result.push(...generateMenus(item.children, basePath, level)); // 传递 level
      return;
    }

    const routePath = path.resolve(basePath, item.path);

    let route = result.find((r) => r.path === routePath);
    if (!route) {
      route = {
        ...item,
        path: routePath,
        children: [],
        level, // 加入层级字段
      };

      if (route.meta.icon && route.meta.title) {
        result.push(route);
      }
    }

    if (!isNull(item.children)) {
      route.children.push(...generateMenus(item.children, route.path, level + 1)); // 层级 +1
    }
  });

  return result;
}

