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

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

export const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/WorkbenchPage',
    children: [
      {
        path: 'WorkbenchPage',
        name: 'WorkbenchPage',
        component: () => import('@/views/WorkbenchPage/index.vue'),
        meta: { title: '工作台' },
      },
      {
        path: 'BusinessManage',
        name: 'BusinessManage',
        redirect: '/BusinessManage/EnterpriseManage',
        meta: { title: '企业管理' },
        children: [
          {
            path: 'EnterpriseManage',
            name: 'EnterpriseManage',
            component: () => import('@/views/BusinessManage/index.vue'),
            meta: { title: '企业列表', hide: true },
          },
          {
            path: 'DataManage',
            name: 'DataManage',
            component: () => import('@/views/BusinessManage/DataManage.vue'),
            meta: { title: '资料管理', hide: true },
          },
        ],
      },
      {
        path: 'CustomerManage',
        name: 'CustomerManage',
        component: () => import('@/views/CustomerManage/index.vue'),
        meta: { title: 'C端管理' },
      },
      {
        path: 'MessageCenter',
        name: 'MessageCenter',
        component: () => import('@/views/MessageCenter/index.vue'),
        meta: { title: '消息中心' },
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue'),
    meta: { title: '登录' },
  },
]

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

// 白名单
const wihteList = ['/login']

// 全局前置导航守卫
router.beforeEach((to) => {
  // 开启进度条
  NProgress.start()
  // 如果没有 token ，并且不在白名单中，则从定向到登陆
  if (!useUserStore().token && !wihteList.includes(to.path)) return '/login'
})

// 全局后置导航守卫
router.afterEach((to) => {
  document.title = `${to.meta.title || ''}-卡叔电梯`
  // 关闭进度条
  NProgress.done()
})

export default router
