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

const router = createRouter({
  history: createWebHistory(),
  routes: [{ path: '/:pathMatch(.*)*', redirect: '/' }],
})

router.beforeEach(async (to, from, next) => {
  if (window.location.host === 'dasai.ezijing.com') {
    next()
  } else {
    const whiteList = ['/401']
    const user = useUserStore()
    if (!user.isLogin && !whiteList.includes(to.path)) {
      try {
        await user.getUser()
      } catch (e) {
        console.error(e)
      }
      if (!user.isLogin) {
        next('/401')
        return
      }
    }
    if (to.path === '/' && user.role?.id === 1) {
      next('/student/lab')
      return
    }
    next()
  }
})

export default router
