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: '/BusinessManage',
    children: [
      // {
      //   path: 'WorkbenchPage',
      //   name: 'WorkbenchPage',
      //   component: () => import('@/views/WorkbenchPage/index.vue'),
      //   meta: { title: '工作台' },
      // },
      {
        path: 'BusinessManage',
        name: 'BusinessManage',
        // redirect: '/BusinessManage/StoreManage',
        meta: { title: '门店管理' },
        component: () => import('@/views/BusinessManage/index.vue'),
        children: [
          // {
          //   path: 'StoreManage',
          //   name: 'StoreManage',
          //   component: () => import('@/views/BusinessManage/index.vue'),
          //   meta: { title: '门店列表' },
          // },
          // {
          //   path: 'DataManage',
          //   name: 'DataManage',
          //   component: () => import('@/views/BusinessManage/DataManage.vue'),
          //   meta: { title: '分类管理' },
          // },
        ],
      },
      {
        path: 'EnterpriseManage',
        name: 'EnterpriseManage',
        component: () => import('@/views/EnterpriseManage/index.vue'),
        meta: { title: '企业管理' },
      },
      {
        path: 'CustomerManage',
        name: 'CustomerManage',
        component: () => import('@/views/CustomerManage/index.vue'),
        meta: { title: 'C端管理', needAdmin: true },
      },
      {
        path: 'StoreReview',
        name: 'StoreReview',
        component: () => import('@/views/StoreReview/index.vue'),
        meta: { title: '门店审核', needAdmin: true },
      },
      {
        path: 'EnterpriseAudit',
        name: 'EnterpriseAudit',
        component: () => import('@/views/EnterpriseAudit/index.vue'),
        meta: { title: '企业审核', needAdmin: true },
      },
    ],
  },
  {
    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'
  if (to.meta.needAdmin && !(useUserStore().userInfo?.jurisdictions?.findIndex(item => item.code === 'superadmin') !== -1)) {
    return false
  }
})

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

export default router
