import { createRouter, createWebHashHistory } from "vue-router";
import { Local } from "@/utils/storage.js";
import Login from "../pages/login/index.vue";
import Rule from "../pages/rule/index.vue";
import Index from "../pages/index/index.vue";
import Record from "../pages/record/index.vue";
import Signature from "../pages/signature/index.vue";
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/Login",
    },
    {
      path: "/Login",
      name: "Login",
      meta: {
        title: "宁福您彩，新婚送福",
      },
      component: Login,
    },
    {
      path: "/Rule",
      name: "Rule",
      meta: {
        title: "宁福您彩，新婚送福",
      },
      component: Rule,
    },
    {
      path: "/Index",
      name: "Index",
      meta: {
        title: "宁福您彩，新婚送福",
      },
      component: Index,
    },
    {
      path: "/Record",
      name: "Record",
      meta: {
        title: "宁福您彩，新婚送福",
      },
      component: Record,
    },
    {
      path: "/Signature",
      name: "Signature",
      meta: {
        title: "宁福您彩，新婚送福",
      },
      component: Signature,
    },
  ],
});

// 路由守卫：根据路由变化更新页面标题并校验token
router.beforeEach((to, from, next) => {
  // 设置默认标题
  let title = "宁福您彩，新婚送福";

  // 如果路由有meta.title属性，使用它
  if (to.meta && to.meta.title) {
    title = to.meta.title;
  }

  // 更新页面标题
  document.title = title;

  // 校验token，如果没有token且不是访问登录页，则跳转到登录页
  const token = Local.get("token");
  if (!token && to.path !== "/Login") {
    next("/Login");
  } else if (to.path === "/Login") {
    if (token) {
      next('/Index');
    } else {
      Local.remove("token");
      Local.remove("userInfo");
      next();
    }
  } else if (to.path === '/') {
    next('/Login');
  } else {
    next();
  }
});

export default router;
