import router from "@/router";
import path from "path";
// import { rolesControl } from "@/config/settings";
import { isExternal } from "@/utils/validate";
import { hasRole } from "@/utils/hasRole";
import { checkActionAccess } from "@/access/check";
/**

 * @description all模式渲染后端返回路由
 * @param asyncRoutes
 * @returns {*}
 */
export function convertRouter(asyncRoutes) {
  return asyncRoutes.map((route) => {
    if (route.component) {
      if (route.component === "Layout") {
        const path = "layouts";
        route.component = (resolve) => require([`@/${path}`], resolve);
      } else {
        let path = "views/" + route.component;
        if (
          new RegExp("^/views/.*$").test(route.component) ||
          new RegExp("^views/.*$").test(route.component)
        ) {
          path = route.component;
        } else if (new RegExp("^/.*$").test(route.component)) {
          path = "views" + route.component;
        } else if (new RegExp("^@views/.*$").test(route.component)) {
          path = route.component.slice(1);
        } else if (new RegExp("^@/views/.*$").test(route.component)) {
          path = route.component.slice(2);
        } else {
          path = "views/" + route.component;
        }
        // console.log(route.component, `@/${path}`);
        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;
  });
}

/**

 * @description 根据roles数组拦截路由
 * @param routes
 * @param baseUrl
 * @returns {[]}
 */
export function filterRoutes(routes, baseUrl = "/") {
  /*
  *  隐藏权限过滤路由功能，让没有权限页面跳转至权限提示页面
  *  .filter((route) => {
      if (route.meta && route.meta.access) {
        return checkActionAccess(route.meta.access);
      } else {
        return true;
      }
    })
  * */
  const routesArr = routes.map((route) => {
    if (route.path !== "*" && !isExternal(route.path))
      route.path = path.resolve(baseUrl, route.path);
    route.fullPath = route.path;
    if (route.children && route.children.length) {
      route.children = filterRoutes(route.children, route.fullPath);

      if (route.redirect) {
        const NohiddenC = route.children.filter((itemF) => {
          return !itemF.hidden && checkActionAccess(itemF.meta.access);
        });
        if (NohiddenC.length > 0) {
          route.redirect = NohiddenC[0].path;
        }
      }
    }
    return route;
  });
  return routesArr;
}
/**
 * 根据当前页面firstMenu
 * @returns {string}
 */
export function handleFirstMenu() {
  const firstMenu = router.currentRoute.matched[0].path;
  if (firstMenu === "") return "/";
  return firstMenu;
}

/**
 * 多门店
 * 根据当前页面firstMenu
 * @returns {string}
 */
export function handleHeadMenu() {
  const pathArr = router.currentRoute.matched[1].path.split("/");
  return `/${pathArr[1]}/${pathArr[2]}`;
}
