import { ResultType, AuthMenuType } from '@/@types'
import router from '@/router/index'

import { getAuth, getUserAllMenu } from '@/utils/auth'
import { LoadingBar } from 'quasar'
LoadingBar.setDefaults({
  color: 'primary',
  size: '3px',
  position: 'bottom'
})

let loadAsyncRouter = false

const whiteList = ['/auth/login']

router.beforeEach((to, from, next) => {
  localStorage.setItem('routerBefore', from.path)
  LoadingBar.start()
  /** 请求头包含授权信息 并且 页面必须授权 直接进入 */
  if (getAuth()) {
    //debugger;
    if (to.path === '/auth/login' || to.path === '/') {
      next({
        path: '/home'
      })
      LoadingBar.stop()
    } else {
      if (!loadAsyncRouter) {
        // 判断当前用户是否获取权限
        loadAsyncRouter = true
        const allAuth = getUserAllMenu()
        if (allAuth != ResultType.EmptyArray) {
          //TODO: 动态生成并追加路由 //router.addRoutes(store.getters.addRouters);
          //   if (to.path === '/404') {
          //     //如果用户直接访问404调回原页面或首页
          //     next(to.redirectedFrom || '/')
          //   } else {
          //检查是否有权限访问
          const authMenu = allAuth.findIndex((x: AuthMenuType) => {
            return x.menuUrl == to.path
          })
          if (authMenu != -1) {
            next({
              ...to,
              replace: true
            })
          } else {
            next('/404')
          }
          LoadingBar.stop()
        } else {
          next('/404')
          LoadingBar.stop()
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/auth/login?redirect=${decodeURIComponent(to.path)}`) // 否则全部重定向到登录页
      LoadingBar.stop()
    }
  }
})

router.afterEach(() => {
  LoadingBar.stop() // 结束Progress
})

router.onError(error => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = error.to
  if (isChunkLoadFailed) {
    router.replace(targetPath)
  }
})
