import { createRouter, createWebHistory } from 'vue-router'
import { hasValidToken, getUserInfo, logoutUser, getStoredUser } from '../utils/jwt';
import { justLoggedIn } from '../utils/authSessionState';
import EditorsMaps from '@/views/index/EditorsMaps.vue'

const routes = [
  {
    path: '/dashboard',
    redirect: '/backend/dashboard'
  },
  {
    path: '/',
    component: () => import('@/views/index.vue'),
    children: [
      {
        path: '',
        redirect: '/maps'
      },
      {
        path: 'demands',
        name: 'DemandList',
        component: () => import('@/views/index/DemandList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'maps',
        name: 'Maps',
        component: () => import('@/views/index/Maps.vue')
      },
      {
        path: 'weekly',
        name: 'WeeklyRecommend',
        component: () => import('@/views/index/WeeklyRecommend.vue')
      },
      {
        path: 'map/:id',
        name: 'MapDetail',
        component: () => import('@/views/index/MapDetail.vue')
      },
      {
        path: 'author',
        name: 'ActiveAuthor',
        component: () => import('@/views/index/ActiveAuthor.vue')
      },
      {
        path: 'weapon-match',
        name: 'WeaponMatch',
        component: () => import('@/views/index/WeaponMatch.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'competition',
        name: 'Competition',
        component: () => import('@/views/index/Competition.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'competition/add',
        name: 'AddCompetition',
        component: () => import('@/views/index/AddContestant.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'competition/detail',
        name: 'CompetitionDetail',
        component: () => import('@/views/index/CompetitionDetail.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'competition/signup',
        name: 'CompetitionSignUp',
        component: () => import('@/views/index/CompetitionSignUp.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'editors-maps',
        name: 'EditorsMaps',
        component: () => import('@/views/index/EditorsMaps.vue')
      },
      {
        path:'terrain',
        name: 'Terrain',
        component: () => import('@/views/index/TerrainList.vue')
      },
      {
        path: 'PIC2TGA',
        name: 'PIC2TGA',
        component: () => import('@/views/index/PIC2TGA.vue')
      },
      {
        path: 'terrainGenerate',
        name: 'TerrainGenerate',
        component: () => import('@/views/index/TerrainGenerate.vue')
      }
    ]
  },
  {
    path: '/backend',
    component: () => import('@/views/backend.vue'),
    children: [
      {
        path: '',
        redirect: 'dashboard'
      },
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/backend/Login.vue')
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/backend/Dashboard.vue'),
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  linkActiveClass: 'router-link-active',
  linkExactActiveClass: 'router-link-exact-active'
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (!requiresAuth) {
    return next(); // 如果页面不需要认证，直接放行
  }

  // 方案1: 检查SessionStorage中是否已有用户信息 (刷新后最先检查这里)
  if (getStoredUser()) {
    return next();
  }

  // 方案2: 如果刚登录过，直接放行
  if (justLoggedIn.value) {
    justLoggedIn.value = false;
    // 此时token肯定有效，但可能还没来得及请求用户信息
    // 为确保用户信息被存储，可以调用一次，但不阻塞导航
    getUserInfo().catch(err => console.error("Error fetching user info after login:", err));
    return next();
  }

  // 方案3: 检查localStorage中是否有token (刷新后SessionStorage没有用户信息时)
  if (hasValidToken()) {
    try {
      await getUserInfo(); // 尝试获取用户信息，该函数会把用户信息存入SessionStorage
      return next(); // 获取成功，放行
    } catch (error) {
      // 获取失败 (token无效, 网络问题等)
      logoutUser(); // 清除所有凭证
      return next({
        path: '/backend/login',
        query: { redirect: to.fullPath, sessionExpired: 'true' }
      });
    }
  }

  // 方案4: 如果以上条件都不满足，跳转登录页
  return next({
    path: '/backend/login',
    query: { redirect: to.fullPath }
  });
});

export default router 