import { createRouter, createWebHistory, type RouteRecordRaw, createWebHashHistory } from 'vue-router'

// 导入页面组件
import Landscape from '@/views/Landscape.vue'
import Portrait from '@/views/Portrait.vue'
import Login from '@/views/Login.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Login',
    component: Login,
  },
  {
    path: '/landscape',
    name: 'Landscape',
    component: Landscape,
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/portrait',
    name: 'Portrait',
    component: Portrait,
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})

// 检测屏幕方向并重定向到相应页面
const getOrientationRoute = () => {
  const width = window.innerWidth
  const height = window.innerHeight
  // 如果宽度大于高度，显示横屏页面，否则显示竖屏页面
  return width > height ? 'Landscape' : 'Portrait'
}

// 路由守卫 - 权限验证和方向检测
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title as string
  }

  // 检查是否需要登录
  const isAuthenticated = localStorage.getItem('isAuthenticated')

  if (to.name !== 'Login' && !isAuthenticated) {
    // 未登录，重定向到登录页
    next({ name: 'Login' })
  } else if (to.name === 'Login' && isAuthenticated) {
    // 已登录但访问登录页，重定向到对应方向页面
    const routeName = getOrientationRoute()
    next({ name: routeName })
  } else if (to.name === 'Landscape' || to.name === 'Portrait') {
    // 检查当前方向是否正确
    const correctRoute = getOrientationRoute()
    if (to.name !== correctRoute) {
      // 方向不匹配，重定向到正确页面
      next({ name: correctRoute })
    } else {
      next()
    }
  } else {
    next()
  }
})

// 添加全局方向变化监听
if (typeof window !== 'undefined') {
  window.addEventListener('resize', () => {
    const isAuthenticated = localStorage.getItem('isAuthenticated')
    if (isAuthenticated && router.currentRoute.value.name !== 'Login') {
      const correctRoute = getOrientationRoute()
      if (router.currentRoute.value.name !== correctRoute) {
        router.push({ name: correctRoute })
      }
    }
  })
}

export default router
