import { createRouter, createWebHistory } from 'vue-router';
import Home from '../pages/home/index.vue';
import Login from '../pages/login/index.vue';
import User from '../pages/user/index.vue';
import UserManage from '../pages/userManage/index.vue';
import LoginLog from '../pages/loginlog/index.vue';
import DbManage from '../pages/dbmanage/index.vue';
import InputColorbox from '../pages/inputimportantinfo/index.vue';
import StationLog from '../pages/stationlog/index.vue';
import TestLog from '../pages/testlog/index.vue';

const routes = [
  {
    path: '/',
    // 动态重定向到登录页或主页
    redirect: () => {
      const isAuthenticated = localStorage.getItem('token');
      return isAuthenticated ? '/home' : '/login';
    }
  },
  {
    path: '/login',
    name: '登录',
    component: Login
  },
  {
    path: '/home',
    name: '主页',
    component: Home,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/user',
    name: '个人中心',
    component: User,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/usermanage',
    name: '用户管理',
    component: UserManage,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/loginlog',
    name: '用户日志',
    component: LoginLog,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/dbmanage',
    name: '数据库管理',
    component: DbManage,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/inputcolorbox',
    name: '数据导入',
    component: InputColorbox,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/stationlog',
    name: '数据导入',
    component: StationLog,
    meta: { requiresAuth: true } // 需要认证的路由
  },
  {
    path: '/testlog',
    name: '测试数据',
    component: TestLog,
    meta: { requiresAuth: true } // 需要认证的路由
  },
];

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


// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') // 用localStorage存储token
  const username = localStorage.getItem('username') // 获取用户名

  if (to.meta.requiresAuth && !isAuthenticated) {
    // 如果需要认证且没有token，则跳转到登录页面
    next('/login')
  } else if ((to.path == '/usermanage' || to.path == '/scopemanage') && (username != 'Admin' && username != 'MomoWen')) {
    // 如果访问的是用户管理页面但用户名不是Admin，则跳转到主页
    next('/home')
  } else {
    // 其他情况正常放行
    sessionStorage.setItem('currentRoute', to.fullPath)
    next()
  }
})

export default router;
