import Layout from "@/components/Layout/index.vue";
import Login from "@/components/Login/login.vue";
import Vue from "vue";
import Router from "vue-router";

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => {
    if (err.name !== "NavigationDuplicated") throw err;
  });
};

Vue.use(Router);

const router = new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      redirect: "/login", // 默认重定向到登录页
    },
    {
      path: "/login",
      name: "Login",
      component: Login,
      meta: { isLoginPage: true }, // 标记为登录页
    },
    {
      path: "/settings",
      component: Layout,
      meta: { isLoginPage: false }, // 非登录页
      children: [
        {
          path: "",
          name: "settings",
          component: () => import("@/views/settings/index.vue"),
        },
      ],
    },
    {
      path: "*",
      redirect: "/login", // 未定义路由跳登录
    },
  ],
});

// 定义合法跳转的标记键名
const LEGAL_JUMP_FLAG = "isFromLoginPage";

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || "默认标题";

  // 1. 访问登录页：清空标记（重置状态）
  if (to.meta.isLoginPage) {
    sessionStorage.removeItem(LEGAL_JUMP_FLAG);
    next();
    return;
  }

  // 2. 访问非登录页：校验是否从登录页合法跳转
  const isFromLogin = sessionStorage.getItem(LEGAL_JUMP_FLAG) === "true";
  if (isFromLogin) {
    // 合法跳转：正常访问
    next();
  } else {
    // 非法访问（直接输入URL）：强制跳登录页
    next("/login");
  }
});

export default router;
