import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      redirect: '/booking',
      component: () => import('../views/Layout'),
      children: [
        {
          path: '/dashboard',
          name: 'Dashboard',
          component: () => import('../views/Dashboard')
        },
        {
          path: '/booking',
          name: 'Booking',
          component: () => import('../views/Booking')
        },
        {
          path: '/booking/detail',
          name: 'Booking Detail',
          component: () => import('../views/Booking/src/components/BookingDetail'),
          meta: {
            activeMenu: '/booking'
          }
        },
        {
          path: '/tracking',
          name: 'Tracking',
          component: () => import('../views/Tracking')
        },
        {
          path: '/tracking/detail',
          name: 'Tracking Detail',
          component: () => import('../views/Tracking/src/components/TrackingDetail'),
          meta: {
            activeMenu: '/tracking'
          }
        },
        {
          path: '/public-tracking',
          name: 'Public Tracking',
          component: () => import('../views/Tracking/src/components/PublicTracking'),
          meta: {
            activeMenu: '/tracking'
          }
        },
        {
          path: '/public-tracking/detail',
          name: 'Public Tracking Detail',
          component: () =>
            import(
              '../views/Tracking/src/components/PublicTracking/src/components/PublicTrackingDetail.vue'
            ),
          meta: {
            activeMenu: '/tracking'
          }
        },
        {
          path: '/login',
          name: 'Login',
          component: () => import('../views/Login'),
          meta: {
            activeMenu: '/tracking'
          }
        },
        {
          path: '/Operationlog',
          name: 'Operationlog',
          component: () => import('../views/OperationLog')
        }
      ]
    }
  ]
})

// * 路由拦截 beforeEach
router.beforeEach(async (to, from, next) => {
  // 未登录白名单
  const whiteList = ['/login', '/public-tracking', '/public-tracking/detail']
  // 判断是否登录
  if (!whiteList.includes(to.path) && !localStorage.getItem('token')) {
    if (whiteList.includes(from.path)) {
      ElMessage.warning('Please log in to use this feature.')
      next(false)
      return
    } else {
      next('/public-tracking')
    }
  }
  next()
})

export default router
