import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAppStore } from '@/stores/app'

// 基础路由
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard',
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login.vue'),
    meta: { requiresAuth: false, layout: 'auth' }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/pages/dashboard/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '仪表板',
      icon: 'DashboardOutlined',
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('@/pages/user/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '用户管理',
      icon: 'UserOutlined',
      permissions: ['user:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/merchants',
    name: 'Merchants',
    component: () => import('@/pages/merchant/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '商家管理',
      icon: 'ShopOutlined',
      permissions: ['merchant:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/travel',
    name: 'Travel',
    component: () => import('@/pages/travel/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '旅行管理',
      icon: 'CompassOutlined',
      permissions: ['travel:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/animals',
    name: 'Animals',
    component: () => import('@/pages/animal/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '动物管理',
      icon: 'HeartOutlined',
      permissions: ['animal:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/flowers',
    name: 'Flowers',
    component: () => import('@/pages/flower/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '花卉管理',
      icon: 'EnvironmentOutlined',
      permissions: ['flower:read'],
      layout: 'main'
    }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('@/pages/order/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '订单管理',
      icon: 'ShoppingCartOutlined',
      permissions: ['order:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/promotion',
    name: 'Promotion',
    component: () => import('@/pages/promotion/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '推广管理',
      icon: 'GiftOutlined',
      permissions: ['promotion:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/permission',
    name: 'Permission',
    component: () => import('@/pages/permission/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '权限管理',
      icon: 'LockOutlined',
      permissions: ['system:read'],
      layout: 'main'  // 添加布局信息
    }
  },
  {
    path: '/system',
    name: 'System',
    component: () => import('@/pages/system/index.vue'),
    meta: { 
      requiresAuth: true,
      title: '系统设置',
      icon: 'SettingOutlined',
      permissions: ['system:read'],
      layout: 'main'
    }
  },
  {
    path: '/system/logs',
    name: 'SystemLogs',
    component: () => import('@/pages/system/logs.vue'),
    meta: { 
      requiresAuth: true,
      title: '系统日志',
      icon: 'FileTextOutlined',
      permissions: ['system:read'],
      layout: 'main'
    }
  },
  {
    path: '/no-permission',
    name: 'NoPermission',
    component: () => import('@/pages/NoPermission.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/pages/NotFound.vue'),
    meta: { requiresAuth: false }
  }
]

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

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const { meta } = to
  const appStore = useAppStore()
  
  // 确保应用已初始化
  if (!appStore.state.initialized) {
    await appStore.initialize()
  }
  
  const isAuthenticated = !!appStore.state.user

  // 检查是否需要认证
  if (meta.requiresAuth && !isAuthenticated) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }

  // 如果已认证且访问登录页，重定向到首页
  if (to.name === 'Login' && isAuthenticated) {
    next({ name: 'Dashboard' })
    return
  }

  // 检查权限
  if (meta.requiresAuth && isAuthenticated && meta.permissions) {
    // 检查用户是否拥有访问该路由所需的权限
    const requiredPermissions = Array.isArray(meta.permissions) ? meta.permissions : [meta.permissions]
    
    // 如果用户没有所有必需的权限，则重定向到无权限页面
    if (!appStore.hasAllPermissions(requiredPermissions)) {
      next({ name: 'NoPermission' })
      return
    }
  }

  next()
})

// 错误处理
router.onError((error) => {
  console.error('🚨 路由错误:', error)
})

export default router