import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../store/auth.js'
import Dashboard from '@/views/Dashboard.vue'
import Monitor from '@/views/Monitor.vue'
import Government from '@/views/Government.vue'
import Finance from '@/views/Finance.vue'
import Transport from '@/views/Transport.vue'
import Risk from '@/views/Risk.vue'
import Eco from '@/views/Eco.vue'
import Gov from '@/views/Gov.vue'
import Trade from '@/views/Trade.vue'
import Login from '@/views/Login.vue'
import UserManagement from '@/views/UserManagement.vue'
import CattleManagement from '@/views/CattleManagement.vue'
import MallManagement from '@/views/MallManagement.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/monitor',
    name: 'Monitor',
    component: Monitor,
    meta: { requiresAuth: true }
  },
  {
    path: '/government',
    name: 'Government',
    component: Government,
    meta: { requiresAuth: true }
  },
  {
    path: '/finance',
    name: 'Finance',
    component: Finance,
    meta: { requiresAuth: true }
  },
  {
    path: '/transport',
    name: 'Transport',
    component: Transport,
    meta: { requiresAuth: true }
  },
  {
    path: '/risk',
    name: 'Risk',
    component: Risk,
    meta: { requiresAuth: true }
  },
  {
    path: '/eco',
    name: 'Eco',
    component: Eco,
    meta: { requiresAuth: true }
  },
  {
    path: '/gov',
    name: 'Gov',
    component: Gov,
    meta: { requiresAuth: true }
  },
  {
    path: '/trade',
    name: 'Trade',
    component: Trade,
    meta: { requiresAuth: true }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/cattle',
    name: 'CattleManagement',
    component: CattleManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/mall',
    name: 'MallManagement',
    component: MallManagement,
    meta: { requiresAuth: true }
  }
]

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

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化认证状态
  if (!authStore.isAuthenticated) {
    authStore.initAuth()
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    // 已登录用户访问登录页，跳转到首页
    next('/')
  } else {
    // 正常访问
    next()
  }
})

export default router