import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 路由组件
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Orders from '@/views/Orders.vue'
import OrderDetail from '@/views/OrderDetail.vue'
import OrderCreate from '@/views/OrderCreate.vue'
import Payments from '@/views/Payments.vue'
import PaymentCreate from '@/views/PaymentCreate.vue'
import AdminOrders from '@/views/AdminOrders.vue'
import AdminUsers from '@/views/AdminUsers.vue'
import AdminDashboard from '@/views/AdminDashboard.vue'
import Dashboard from '@/views/Dashboard.vue'
import Welcome from '@/views/Welcome.vue'
import Profile from '@/views/Profile.vue'
import Subscription from '@/views/Subscription.vue'
import MyWorks from '@/views/MyWorks.vue'
import VideoDetail from '@/views/VideoDetail.vue'
import TextToVideo from '@/views/TextToVideo.vue'
import TextToVideoCreate from '@/views/TextToVideoCreate.vue'
import ImageToVideo from '@/views/ImageToVideo.vue'
import ImageToVideoCreate from '@/views/ImageToVideoCreate.vue'
import StoryboardVideo from '@/views/StoryboardVideo.vue'
import StoryboardVideoCreate from '@/views/StoryboardVideoCreate.vue'

const routes = [
  {
    path: '/works',
    name: 'MyWorks',
    component: MyWorks,
    meta: { title: '我的作品', requiresAuth: true }
  },
  {
    path: '/video/:id',
    name: 'VideoDetail',
    component: VideoDetail,
    meta: { title: '视频详情', requiresAuth: true }
  },
  {
    path: '/text-to-video',
    name: 'TextToVideo',
    component: TextToVideo,
    meta: { title: '文生视频', requiresAuth: true }
  },
  {
    path: '/text-to-video/create',
    name: 'TextToVideoCreate',
    component: TextToVideoCreate,
    meta: { title: '文生视频创作', requiresAuth: true }
  },
  {
    path: '/image-to-video',
    name: 'ImageToVideo',
    component: ImageToVideo,
    meta: { title: '图生视频', requiresAuth: true }
  },
  {
    path: '/image-to-video/create',
    name: 'ImageToVideoCreate',
    component: ImageToVideoCreate,
    meta: { title: '图生视频创作', requiresAuth: true }
  },
  {
    path: '/storyboard-video',
    name: 'StoryboardVideo',
    component: StoryboardVideo,
    meta: { title: '分镜视频', requiresAuth: true }
  },
  {
    path: '/storyboard-video/create',
    name: 'StoryboardVideoCreate',
    component: StoryboardVideoCreate,
    meta: { title: '分镜视频创作', requiresAuth: true }
  },
  {
    path: '/',
    redirect: '/welcome' // 重定向到欢迎页面
  },
  {
    path: '/welcome',
    name: 'Welcome',
    component: Welcome,
    meta: { title: '欢迎', guest: true }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { title: '首页', requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { title: '个人主页', requiresAuth: true }
  },
  {
    path: '/subscription',
    name: 'Subscription',
    component: Subscription,
    meta: { title: '会员订阅', requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', guest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { title: '注册', guest: true }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: Orders,
    meta: { title: '订单管理', requiresAuth: true }
  },
  {
    path: '/orders/:id',
    name: 'OrderDetail',
    component: OrderDetail,
    meta: { title: '订单详情', requiresAuth: true }
  },
  {
    path: '/orders/create',
    name: 'OrderCreate',
    component: OrderCreate,
    meta: { title: '创建订单', requiresAuth: true }
  },
  {
    path: '/payments',
    name: 'Payments',
    component: Payments,
    meta: { title: '支付记录', requiresAuth: true }
  },
  {
    path: '/payments/create',
    name: 'PaymentCreate',
    component: PaymentCreate,
    meta: { title: '创建支付', requiresAuth: true }
  },
  {
    path: '/admin/orders',
    name: 'AdminOrders',
    component: AdminOrders,
    meta: { title: '订单管理', requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/users',
    name: 'AdminUsers',
    component: AdminUsers,
    meta: { title: '用户管理', requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/dashboard',
    name: 'AdminDashboard',
    component: AdminDashboard,
    meta: { title: '后台管理', requiresAuth: true, requiresAdmin: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 添加路由缓存配置
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  try {
    const userStore = useUserStore()
    
    // 初始化用户状态
    if (!userStore.initialized) {
      await userStore.init()
    }
    
    // 检查是否需要认证
    if (to.meta.requiresAuth) {
      if (!userStore.isAuthenticated) {
        // 未登录，跳转到登录页
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }
      
      // 检查管理员权限
      if (to.meta.requiresAdmin && !userStore.isAdmin) {
        // 权限不足，跳转到首页
        next('/home')
        return
      }
    }
    
    // 已登录用户访问登录页，重定向到首页
    if (to.meta.guest && userStore.isAuthenticated) {
      next('/home')
      return
    }
    
    // 设置页面标题
    if (to.meta.title) {
      document.title = `${to.meta.title} - AIGC Demo`
    }
    
    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    // 发生错误时，允许访问但显示错误信息
    next()
  }
})

export default router
