import { createRouter, createWebHistory } from 'vue-router'
import Sale from '@/views/person/sale.vue'
import Manager from '@/views/maneger/manager.vue'
import SeniorManager from '@/views/senorManger/seniorManager.vue'
import TopOne from '@/views/topOne/topone.vue'
import Login from '@/views/login/login.vue'
import SecondTop from '@/views/secondTop/secondTop.vue'
import { useUserStore } from '@/stores/user.js'

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/sale'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    // meta: { requiresAuth: false }
  },
  {
    path: '/sale',
    name: 'Sale',
    component: Sale,
    // meta: { requiresAuth: true, minLevel: 1 }
  },
  {
    path: '/manager',
    name: 'Manager',
    component: Manager,
    // meta: { requiresAuth: true, minLevel: 2 }
  },
  {
    path: '/senior-manager',
    name: 'SeniorManager',
    component: SeniorManager,
    // meta: { requiresAuth: true, minLevel: 3 }
  },
  {
    path: '/second-top',
    name: 'SecondTop',
    component: SecondTop,
    // meta: { requiresAuth: true, minLevel: 4 }
  },
  {
    path: '/top',
    name: 'Top',
    component: TopOne,
    // meta: { requiresAuth: true, minLevel: 5 }
  }
]

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

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 如果路由不需要认证，直接通过
  if (!to.meta.requiresAuth) {
    next()
    return
  }
  
  // 检查是否已登录
  if (!userStore.isLoggedIn || !userStore.userInfo) {
    next('/login')
    return
  }
  
  // 检查用户等级权限
  const userLevel = userStore.userInfo.user_level
  const requiredLevel = to.meta.minLevel
  
  // 用户等级必须大于等于所需等级（等级高的可以访问等级低的页面）
  if (userLevel >= requiredLevel) {
    next()
  } else {
    // 权限不足，重定向到对应等级的默认页面
    const defaultRoutes = {
      1: '/sale',
      2: '/manager', 
      3: '/senior-manager',
      4: '/second-top',
      5: '/top'
    }
    next(defaultRoutes[userLevel] || '/sale')
  }
})

export default router