import path from 'path';
import { isExternal } from '@/utils/validate';
import { hasAccess } from '@/utils/hasAccess';

export function convertRouter(asyncRoutes) {
  return asyncRoutes.map(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = resolve => require(['@/vab/layouts'], resolve);
      } else {
        const index = route.component.indexOf('views');
        const path =
          index > 0 ? route.component.slice(index) : `views/${route.component}`;
        route.component = resolve => require([`@/${path}`], resolve);
      }
    }
    if (route.children && route.children.length)
      route.children = convertRouter(route.children);
    if (route.children && route.children.length === 0) delete route.children;
    return route;
  });
}

export function filterRoutes(routes, rolesControl, baseUrl = '/') {
  return routes
    .filter(route => {
      if (rolesControl && route.meta && route.meta.roles)
        return hasAccess(route.meta.roles);
      else return true;
    })
    .map(route => {
      if (route.path !== '*' && !isExternal(route.path))
        route.path = path.resolve(baseUrl, route.path);
      if (route.children)
        route.children = filterRoutes(route.children, rolesControl, route.path);
      return route;
    });
}

export function handleActivePath(route, isTabsBar = false) {
  const { meta, path, fullPath } = route;
  const rawPath = route.matched
    ? route.matched[route.matched.length - 1].path
    : path;
  if (isTabsBar) return meta.dynamicNewTab ? fullPath : rawPath;
  if (meta.activeMenu) return meta.activeMenu;
  return fullPath ? fullPath : rawPath;
}

export function toLoginRoute() {
  return { path: '/login', replace: true };
}

export function getNames(routes) {
  return routes.flatMap(route => {
    const names = [];
    if (route.name) names.push(route.name);
    if (route.children) names.push(...getNames(route.children));
    return names;
  });
}
