import { createRouter, createWebHistory } from "vue-router";
//@ts-ignore
import { handleVerifyToken } from "@/utils/verifyToken.ts";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "school",
      component: () => import("@/views/school.vue"),
      meta: { showRouter: true },
    },
    {
      path: "/user",
      name: "user",
      component: () => import("@/views/user.vue"),
      meta: { showRouter: true },
    },
    {
      path: "/energy",
      name: "energy",
      component: () => import("@/views/energy.vue"),
      meta: { showRouter: true },
    },
    {
      path: "/more",
      name: "more",
      component: () => import("@/views/more.vue"),
      meta: { showRouter: false },
    },
    {
      path: "/teacher",
      name: "teacher",
      component: () => import("@/views/teacher.vue"),
      meta: { showRouter: false },
    },
    {
      path: "/student",
      name: "student",
      component: () => import("@/views/student.vue"),
      meta: { showRouter: false },
    },
    {
      path: "/404",
      name: "404",
      component: () => import("@/views/404.vue"),
      meta: { showRouter: false },
    },
  ],
});

// 白名单
const whiteList = ["/", "/404"];

// 路由全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 判断是否为白名单页面
  if (whiteList.includes(to.path)) {
    // 白名单页面直接放行
    next();
  } else {
    const token = sessionStorage.getItem("WANZAI-TOKEN");
    // console.log(token);
    if (token) {
      let flag = await handleVerifyToken(token);
      if (flag) {
        next();
      } else {
        next("/404");
      }
    } else {
      next("/404");
    }
  }
});

export default router;
