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(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 检查URL参数中是否包含token和用户信息（来自其他页面的跳转）
  const urlToken = to.query.token
  const urlUsername = to.query.username
  const urlLevel = to.query.level
  
  // 如果URL中包含token和用户信息，进行自动登录
  if (urlToken && urlUsername && urlLevel) {
    try {
      // 解码用户名（URL编码的中文）
      const decodedUsername = decodeURIComponent(urlUsername)
      
      // 直接设置用户信息到store（跳过API验证，因为token来自可信源）
      userStore.login(urlToken, decodedUsername, parseInt(urlLevel), '', '')
      
      // 根据用户等级跳转到对应页面
      const defaultRoutes = {
        1: '/sale',
        2: '/manager', 
        3: '/senior-manager',
        4: '/second-top',
        5: '/top'
      }
      
      const targetRoute = defaultRoutes[parseInt(urlLevel)] || '/sale'
      
      // 如果当前路由就是目标路由，直接通过；否则重定向
      if (to.path === targetRoute) {
        next()
      } else {
        next(targetRoute)
      }
      return
    } catch (error) {
      console.error('自动登录失败:', error)
      // 如果自动登录失败，继续正常的路由守卫逻辑
    }
  }
  
  // 如果路由不需要认证，直接通过
  if (!to.meta.requiresAuth) {
    next()
    return
  }
  
  // 如果访问登录页面，始终允许访问（允许重新登录）
  if (to.path === '/login') {
    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