import { createRouter, createWebHistory } from 'vue-router'
import { sendVisitLog } from '@/utils/useStatistics'
import loginService from '../services/loginService'
import Home from '../pages/Home.vue'
import About from '../pages/About.vue'
import My from '../pages/My.vue'
import Item from '../pages/Item.vue'
import MyCoupon from '../pages/MyCoupon.vue'
import MyOrder from '../pages/MyOrder.vue'
import MyAllowance from '../pages/MyAllowance.vue'
import MyAllowanceForm from '../pages/MyAllowanceForm.vue'
import MyBank from '../pages/MyBank.vue'
import Login from '../pages/Login.vue'

const routes = [
  { path: '/login', name: 'Login', component: Login },
  { path: '/', name: 'Home', component: Home },
  { path: '/about', name: 'About', component: About },
  { path: '/my', name: 'My', component: My, meta: { requiresAuth: true } },
  { path: '/item/:id', name: 'Item', component: Item },
  { path: '/my/coupon', name: 'MyCoupon', component: MyCoupon },
  { path: '/my/order', name: 'MyOrder', component: MyOrder },
  { path: '/my/allowance', name: 'MyAllowance', component: MyAllowance },
  { path: '/my/allowance/form', name: 'MyAllowanceForm', component: MyAllowanceForm },
  { path: '/my/bank', name: 'MyBank', component: MyBank },
]

const router = createRouter({ history: createWebHistory(), routes })
// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (loginService.isLoggedIn()) {
      next()
    } else {
      next({
        name: 'Login',
        query: { redirect: to.fullPath } // 保存原目标路径
      })
    }
  } else {
    next() // 不需要认证的路由直接放行
  }
})
// 路由跳转后发送PV统计
router.afterEach(() => {
  // 检查全局的aplus_queue是否存在
  // if (window.aplus_queue) {
  //   // 使用提供的PV发送事件，按要求传递参数
  //   window.aplus_queue.push({
  //     action: 'aplus.sendPV',
  //     arguments: [{ is_auto: false }] // 按文档要求传递固定格式参数
  //   })
  // }
  console.log('发送PV统计')
  sendVisitLog()
})
export default router