import { createRouter, createWebHistory } from 'vue-router';
import { getToken } from "@/utils/auth";

const whiteList = ["/login"];

const routes = [
  {
    path: "/",
    name: "Index",
    component: () => import("@/views/Line2/index.vue"),
  },
  {
    path: "/lms",
    name: "Lms",
    component: () => import("@/views/Line1/index.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login.vue"),
  },
  {
    path: "/package-station",
    name: "PackageStation",
    component: () => import("@/views/package-station/index.vue"),
  },
  // 一号线
  {
    path: "/line1",
    name: "Line1",
    children: [
      {
        path: "L1-data",
        name: "Line1L1Data",
        component: () => import("@/views/Line1/L1-data-list/index.vue"),
      },
      {
        path: "alarm-records",
        name: "Line1AlarmRecords",
        component: () => import("@/views/Line1/alarm-records/index.vue"),
      },
    ],
  },
  // 二号线
  {
    path: "/line2",
    name: "Line2",
    children: [
      {
        path: "L1-data",
        name: "Line2L1Data",
        component: () => import("@/views/Line2/L1-data-list/index.vue"),
      },
      {
        path: "L4-data",
        name: "Line2L4Data",
        component: () => import("@/views/Line2/L4-data-list/index.vue"),
      },
    ],
  },
];

const router = createRouter({
	history: createWebHistory(),
	routes
});

router.beforeEach(async (to, from, next) => {
  const token = getToken();
  // 已登录，访问 login → 跳首页
  if (token && to.path === "/login") {
    return next("/lms");
  }
	
  // 白名单放行
	if (whiteList.includes(to.path)) {
    return next();
	}

  // 未登录，访问受保护路由
  if (!token) {
    return next({
      path: "/login",
      query: { redirect: to.fullPath },
    });
  }

  // 已登录，正常访问
  next();
});


export default router;
