import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
// 前台页面懒加载
const LotterySelection = () => import('../views/LotterySelection.vue')
const LotteryPremium = () => import('../views/LotteryPremium.vue')
const Home = () => import('../views/ssq/Home.vue')
const DltHome = () => import('../views/dlt/Home.vue')
const LotteryInfo = () => import('../views/LotteryInfo.vue')
const Profile = () => import('../views/Profile.vue')
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
const ResetPassword = () => import('../views/ResetPassword.vue')
const PredictRecords = () => import('../views/PredictRecords.vue')
const DltPredictRecords = () => import('../views/dlt/PredictRecords.vue')
const ExcelImportManagement = () => import('../views/ExcelImportManagement.vue')
const ExchangeRecords = () => import('../views/ExchangeRecords.vue')
const DataAnalysis = () => import('../views/DataAnalysis.vue')
const HelpCenter = () => import('../views/HelpCenter.vue')
const AboutUs = () => import('../views/AboutUs.vue')
const UserAgreement = () => import('../views/UserAgreement.vue')
const UserGuide = () => import('../views/UserGuide.vue')
const MemberAgreement = () => import('../views/MemberAgreement.vue')
const PrivacyPolicy = () => import('../views/PrivacyPolicy.vue')

// 双色球相关页面
const SsqLottery = () => import('../views/ssq/Lottery.vue')
const TrendAnalysis = () => import('../views/ssq/TrendAnalysis.vue')
const SurfaceAnalysis = () => import('../views/ssq/SurfaceAnalysis.vue')
const LineAnalysis = () => import('../views/ssq/LineAnalysis.vue')
const SsqTableAnalysis = () => import('../views/ssq/SsqTableAnalysis.vue')
const HitAnalysis = () => import('../views/ssq/HitAnalysis.vue')
const UsageStats = () => import('../views/ssq/UsageStats.vue')
const PrizeStatistics = () => import('../views/ssq/PrizeStatistics.vue')

// 大乐透相关页面
const DltLottery = () => import('../views/dlt/Lottery.vue')
const DltTableAnalysis = () => import('../views/dlt/DltTableAnalysis.vue')
const DltSurfaceAnalysis = () => import('../views/dlt/SurfaceAnalysis.vue')
const DltLineAnalysis = () => import('../views/dlt/LineAnalysis.vue')
const DltTrendAnalysis = () => import('../views/dlt/TrendAnalysis.vue')
const DltHitAnalysis = () => import('../views/dlt/HitAnalysis.vue')
const DltUsageStats = () => import('../views/dlt/UsageStats.vue')
const DltPrizeStatistics = () => import('../views/dlt/PrizeStatistics.vue')

// 精推版页面
const JtSsqHome = () => import('../views/jt/SsqHome.vue')
const JtDltHome = () => import('../views/jt/DltHome.vue')

// 后台管理相关组件
const AdminLogin = () => import('../views/admin/AdminLogin.vue')
const AdminLayout = () => import('../views/admin/layout/AdminLayout.vue')
const AdminVipCodeManagement = () => import('../views/admin/VipCodeManagement.vue')
const AdminExcelImportManagement = () => import('../views/admin/ExcelImportManagement.vue')
const AdminDltExcelImportManagement = () => import('../views/admin/DltExcelImportManagement.vue')
const AdminPredictionManagement = () => import('../views/admin/PredictionManagement.vue')
const AdminDltPredictionManagement = () => import('../views/admin/DltPredictionManagement.vue')
const AdminPrizeStatistics = () => import('../views/admin/PrizeStatistics.vue')
const AdminDltPrizeStatistics = () => import('../views/admin/DltPrizeStatistics.vue')
const AdminUsageStats = () => import('../views/ssq/UsageStats.vue')
const AdminDltUsageStats = () => import('../views/dlt/UsageStats.vue')

const routes = [
  // 前台用户路由
  {
    path: '/',
    name: 'LotterySelection',
    component: LotterySelection
  },
  {
    path: '/lottery-premium',
    name: 'LotteryPremium',
    component: LotteryPremium
  },
  {
    path: '/shuangseqiu',
    name: 'Shuangseqiu',
    component: Home
  },
  {
    path: '/daletou',
    name: 'DaLeTou',
    component: DltHome
  },
  {
    path: '/jt/shuangseqiu',
    name: 'JtShuangseqiu',
    component: JtSsqHome
  },
  {
    path: '/jt/daletou',
    name: 'JtDaLeTou',
    component: JtDltHome
  },
  {
    path: '/lottery-info',
    name: 'LotteryInfo',
    component: LotteryInfo
  },
  {
    path: '/lottery-info/ssq',
    name: 'SsqLottery',
    component: SsqLottery
  },
  {
    path: '/lottery-info/dlt',
    name: 'DltLottery',
    component: DltLottery
  },
  {
    path: '/dlt-table-analysis',
    name: 'DltTableAnalysis',
    component: DltTableAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/dlt-surface-analysis',
    name: 'DltSurfaceAnalysis',
    component: DltSurfaceAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/dlt-line-analysis',
    name: 'DltLineAnalysis',
    component: DltLineAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/dlt-trend-analysis',
    name: 'DltTrendAnalysis',
    component: DltTrendAnalysis,
    meta: { requiresAuth: true }
  },
  {
    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: '/dlt/predict-records',
    name: 'DltPredictRecords',
    component: DltPredictRecords,
    meta: { requiresAuth: true }
  },

  {
    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: '/hit-analysis',
    name: 'HitAnalysis',
    component: HitAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/daletou/hit-analysis',
    name: 'DltHitAnalysis',
    component: DltHitAnalysis,
    meta: { requiresAuth: true }
  },
  {
    path: '/usage-stats',
    name: 'UsageStats',
    component: UsageStats,
    meta: { requiresAuth: true }
  },
  {
    path: '/daletou/usage-stats',
    name: 'DltUsageStats',
    component: DltUsageStats,
    meta: { requiresAuth: true }
  },
  {
    path: '/prize-statistics',
    name: 'PrizeStatistics',
    component: PrizeStatistics,
    meta: { requiresAuth: true }
  },
  {
    path: '/daletou/prize-statistics',
    name: 'DltPrizeStatistics',
    component: DltPrizeStatistics,
    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: '/user-guide',
    name: 'UserGuide',
    component: UserGuide,
    meta: { requiresAuth: true }
  },
  {
    path: '/member-agreement',
    name: 'MemberAgreement',
    component: MemberAgreement,
    meta: { requiresAuth: false }
  },
  {
    path: '/privacy-policy',
    name: 'PrivacyPolicy',
    component: PrivacyPolicy,
    meta: { requiresAuth: false }
  },
  {
    path: '/table-analysis',
    name: 'SsqTableAnalysis',
    component: SsqTableAnalysis
  },


  // 后台管理路由 - 完全隔离
  {
    path: '/cpzsadmin/login',
    name: 'AdminLogin',
    component: AdminLogin,
    meta: { 
      title: '后台登录',
      requiresAuth: false,
      isAdmin: true
    }
  },
  {
    path: '/cpzsadmin',
    component: AdminLayout,
    meta: { 
      requiresAuth: true,
      isAdmin: true
    },
    children: [
      {
        path: '',
        redirect: '/cpzsadmin/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',
        meta: { 
          title: '数据导入',
          requiresAuth: true,
          isAdmin: true
        },
        children: [
          {
            path: '',
            name: 'AdminExcelImportManagement',
            component: AdminExcelImportManagement,
            meta: { 
              title: '数据导入',
              requiresAuth: true,
              isAdmin: true
            }
          },
          {
            path: 'ssq',
            name: 'AdminExcelImportSSQ',
            component: AdminExcelImportManagement,
            meta: { 
              title: '双色球数据导入',
              requiresAuth: true,
              isAdmin: true
            }
          },
          {
            path: 'dlt',
            name: 'AdminExcelImportDLT',
            component: AdminDltExcelImportManagement,
            meta: { 
              title: '大乐透数据导入',
              requiresAuth: true,
              isAdmin: true
            }
          }
        ]
      },
      {
        path: 'prediction',
        meta: { 
          title: '推测管理',
          requiresAuth: true,
          isAdmin: true
        },
        children: [
          {
            path: 'ssq',
            name: 'AdminPredictionSSQ',
            component: AdminPredictionManagement,
            meta: { 
              title: '双色球推测管理',
              requiresAuth: true,
              isAdmin: true
            }
          },
          {
            path: 'dlt',
            name: 'AdminPredictionDLT',
            component: AdminDltPredictionManagement,
            meta: { 
              title: '大乐透推测管理',
              requiresAuth: true,
              isAdmin: true
            }
          }
        ]
      },
      {
        path: 'prize-statistics',
        meta: { 
          title: '奖金统计',
          requiresAuth: true,
          isAdmin: true
        },
        children: [
          {
            path: 'ssq',
            name: 'AdminPrizeStatisticsSSQ',
            component: AdminPrizeStatistics,
            meta: { 
              title: '双色球奖金统计',
              requiresAuth: true,
              isAdmin: true
            }
          },
          {
            path: 'dlt',
            name: 'AdminPrizeStatisticsDLT',
            component: AdminDltPrizeStatistics,
            meta: { 
              title: '大乐透奖金统计',
              requiresAuth: true,
              isAdmin: true
            }
          }
        ]
      },
      {
        path: 'usage-stats',
        meta: { 
          title: '使用统计',
          requiresAuth: true,
          isAdmin: true
        },
        children: [
          {
            path: 'ssq',
            name: 'AdminUsageStatsSSQ',
            component: AdminUsageStats,
            meta: { 
              title: '双色球使用统计',
              requiresAuth: true,
              isAdmin: true
            }
          },
          {
            path: 'dlt',
            name: 'AdminUsageStatsDLT',
            component: AdminDltUsageStats,
            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
        }
      },
      {
        path: 'announcement',
        name: 'AdminAnnouncementManagement',
        component: () => import('../views/admin/AnnouncementManagement.vue'),
        meta: { 
          title: '公告管理',
          requiresAuth: true,
          isAdmin: true
        }
      }
    ]
  },

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

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的位置（比如浏览器后退），使用保存的位置
    if (savedPosition) {
      return savedPosition
    } else {
      // 否则滚动到页面顶部
      return { top: 0, behavior: 'smooth' }
    }
  }
})

// 路由守卫 - 权限控制
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('/cpzsadmin/login')
        return
      }

      // 检查是否是管理员或VIP用户
      const adminInfo = JSON.parse(sessionStorage.getItem('adminInfo') || '{}')
      if (adminInfo.userRole === 'user') {
        ElMessage.error('您没有权限访问后台管理系统')
        next('/cpzsadmin/login')
        return
      }
      
      next()
    }).catch(error => {
      console.error('加载用户状态出错:', error)
      next('/cpzsadmin/login')
    })
  } else if (to.meta.requiresAuth) {
    // 前台需要登录的页面权限检查
    import('../store/user.js').then(({ userStore }) => {
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录后再访问该页面')
        next('/login')
      } else {
        next()
      }
    }).catch(() => {
      next('/login')
    })
  } else {
    next()
  }
})

export default router 