import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './route'
import useUserStore from '@/store/modules/user'

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

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 如果访问的是登录页面，直接放行
  if (to.path === '/login') {
    next()
    return
  }

  // 检查用户是否已登录
  if (userStore.isLoggedIn) {
    next()
  } else {
    // 将用户重定向到登录页，并保存原目标路径
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }
})

export default router
