import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import LotterySelection from '../views/LotterySelection.vue'
import Home from '../views/Home.vue'
import LotteryInfo from '../views/LotteryInfo.vue'
import Profile from '../views/Profile.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import ResetPassword from '../views/ResetPassword.vue'
import PredictRecords from '../views/PredictRecords.vue'
import VipCodeManagement from '../views/VipCodeManagement.vue'
import ExcelImportManagement from '../views/ExcelImportManagement.vue'
import ExchangeRecords from '../views/ExchangeRecords.vue'
import TrendAnalysis from '../views/TrendAnalysis.vue'
import SurfaceAnalysis from '../views/SurfaceAnalysis.vue'
import LineAnalysis from '../views/LineAnalysis.vue'
import TableAnalysis from '../views/TableAnalysis.vue'
import DataAnalysis from '../views/DataAnalysis.vue'
import HelpCenter from '../views/HelpCenter.vue'
import AboutUs from '../views/AboutUs.vue'
import UserAgreement from '../views/UserAgreement.vue'
import AIAssistant from '../views/AIAssistant.vue'

// 后台管理相关组件
import AdminLogin from '../views/admin/AdminLogin.vue'
import AdminLayout from '../views/admin/layout/AdminLayout.vue'
import AdminVipCodeManagement from '../views/admin/VipCodeManagement.vue'
import AdminExcelImportManagement from '../views/admin/ExcelImportManagement.vue'

const routes = [
  // 前台用户路由
  {
    path: '/',
    name: 'LotterySelection',
    component: LotterySelection
  },
  {
    path: '/shuangseqiu',
    name: 'Shuangseqiu',
    component: Home
  },
  {
    path: '/lottery-info',
    name: 'LotteryInfo',
    component: LotteryInfo
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: ResetPassword
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/predict-records',
    name: 'PredictRecords',
    component: PredictRecords
  },
  {
    path: '/vip-management',
    name: 'VipCodeManagement',
    component: VipCodeManagement
  },
  {
    path: '/excel-import',
    name: 'ExcelImportManagement',
    component: ExcelImportManagement
  },
  {
    path: '/exchange-records',
    name: 'ExchangeRecords',
    component: ExchangeRecords
  },
  {
    path: '/trend-analysis',
    name: 'TrendAnalysis',
    component: TrendAnalysis
  },
  {
    path: '/surface-analysis',
    name: 'SurfaceAnalysis',
    component: SurfaceAnalysis
  },
  {
    path: '/line-analysis',
    name: 'LineAnalysis',
    component: LineAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/data-analysis',
    name: 'DataAnalysis',
    component: DataAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/help-center',
    name: 'HelpCenter',
    component: HelpCenter,
    meta: { requiresAuth: true }
  },
  {
    path: '/about-us',
    name: 'AboutUs',
    component: AboutUs,
    meta: { requiresAuth: true }
  },
  {
    path: '/user-agreement',
    name: 'UserAgreement',
    component: UserAgreement,
    meta: { requiresAuth: true }
  },
  {
    path: '/table-analysis',
    name: 'TableAnalysis',
    component: TableAnalysis
  },
  {
    path: '/ai-assistant',
    name: 'AIAssistant',
    component: AIAssistant
  },

  // 后台管理路由 - 完全隔离
  {
    path: '/admin/login',
    name: 'AdminLogin',
    component: AdminLogin,
    meta: { 
      title: '后台登录',
      requiresAuth: false,
      isAdmin: true
    }
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: { 
      requiresAuth: true,
      isAdmin: true
    },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('../views/admin/Dashboard.vue'),
        meta: { 
          title: '控制面板',
          requiresAuth: true,
          isAdmin: true
        }
      },
      {
        path: 'vip-code',
        name: 'AdminVipCodeManagement',
        component: AdminVipCodeManagement,
        meta: { 
          title: '会员码管理',
          requiresAuth: true,
          isAdmin: true
        }
      },
      {
        path: 'excel-import',
        name: 'AdminExcelImportManagement',
        component: AdminExcelImportManagement,
        meta: { 
          title: '数据导入',
          requiresAuth: true,
          isAdmin: true
        }
      },
      {
        path: 'user-list',
        name: 'AdminUserList',
        component: () => import('../views/admin/UserList.vue'),
        meta: { 
          title: '用户列表',
          requiresAuth: true,
          isAdmin: true
        }
      },
      {
        path: 'operation-history',
        name: 'AdminOperationHistory',
        component: () => import('../views/admin/OperationHistory.vue'),
        meta: { 
          title: '操作历史',
          requiresAuth: true,
          isAdmin: true
        }
      }
    ]
  },

  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

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

// 路由守卫 - 权限控制
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title + ' - 彩票推测系统'
  }

  // 后台管理路由权限检查
  if (to.meta.isAdmin) {
    // 如果是登录页面，直接放行
    if (to.name === 'AdminLogin') {
      next()
      return
    }

    // 从store中导入userStore
    import('../store/user.js').then(({ userStore }) => {
      // 检查是否已登录（使用session存储）
      if (!userStore.isAdminLoggedIn()) {
        ElMessage.error('请先登录后台管理系统')
        next('/admin/login')
        return
      }

      // 检查是否是管理员或VIP用户
      const adminInfo = JSON.parse(sessionStorage.getItem('adminInfo') || '{}')
      if (adminInfo.userRole === 'user') {
        ElMessage.error('您没有权限访问后台管理系统')
        next('/admin/login')
        return
      }
      
      next()
    }).catch(error => {
      console.error('加载用户状态出错:', error)
      next('/admin/login')
    })
  } else {
    next()
  }
})

export default router 