import { createRouter, createWebHashHistory } from "vue-router";
import useGuard from "@/utils/route-guard";
import yktRouters from "./ykt";
import hlwRouters from "./hlw";
// vue项目自带路由
let children = [];
children = children.concat(yktRouters);

if (import.meta.env.VITE_NEED_IM === "true") {
  children = children.concat(hlwRouters);
}
let routes = [
  {
    path: "/",
    name: "Home",
    meta: {
      keepAlive: true, //设置页面是否需要使用缓存
    },
    component: () => import("@/views/home/index.vue"),
    children,
  },
];

// 是否需要登录, 如果需要登陆的话, 配置登陆地址
if (import.meta.env.VITE_NEED_LOGIN === "true") {
  routes.push({
    name: "LOGIN",
    path: "/LOGIN",
    component: () => import("../views/login/index"),
    meta: {
      keepAlive: false,
      title: "登录",
      ignoreAuth: true, // 忽略路由守卫
    },
  });
}

const router = createRouter({
  history: createWebHashHistory("/dist/"),
  routes: [...routes],
});
export function getRoutes(includesParentName = false) {
  const flatRoutes = (children, list = []) => {
    if (Array.isArray(children)) {
      children.forEach((i) => {
        if (Array.isArray(i.children)) flatRoutes(i.children, list);
        else {
          list.push(i);
          return;
        }
        if (includesParentName) list.push(i);
      });
    }
    return list;
  };
  return flatRoutes(routes);
}

router.beforeEach(async (to, from) => {
  const res = await useGuard(to, from);
  if (res && res.name) {
    return res;
  }
  if (res === false) return false;
  // return false to cancel navigation
  if (
    (to.fullPath === from.fullPath && from.name) ||
    !getRoutes(true)
      .map((i) => i.name)
      .includes(to.name)
  ) {
    return false;
  }
  return true;
});

export default router;
