import { Router } from "vue-router";
import { loginCheck } from "@/utils/router";

export function createRouterGuards(router: Router) {
  // 前置;
  router.beforeEach(async (to, from, next) => {
    const Loading = window["$loading"];
    Loading && Loading.start();
    const isErrorPage = router
      .getRoutes()
      .findIndex((item) => item.name === to.name);
    if (isErrorPage === -1) {
      next({ name: "ErrorPage404" });
    }

    if (!loginCheck()) {
      if (to.name === "Login") {
        next();
      }
      next({ name: "Login" });
    }

    next();
  });

  router.afterEach((to) => {
    const Loading = window["$loading"];
    document.title = (to?.meta?.title as string) || document.title;
    Loading && Loading.finish();
  });

  // 错误
  router.onError((error) => {
    console.log(error, "路由错误");
  });
}
