import { AuthMenuType } from '../@types'
import { ResultType } from '../@types/enumHelper'
import { boot } from 'quasar/wrappers'

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

let loadAsyncRouter = false

const whiteList = ['/auth/login', '/auth/regist', '/auth/forget', '/auth/newpassword', '/404']
export default boot(({ router, store }) => {
  router.beforeEach((to, from, next) => {
    localStorage.setItem('routerBefore', from.path)
    LoadingBar.start()
    /** 请求头包含授权信息 并且 页面必须授权 直接进入 */
    if (getAuth()) {
      //debugger;
      if (to.path === '/auth/login' || to.path === '/') {
        next('/index')
      } else {
        if (!loadAsyncRouter) {
          // 判断当前用户是否获取权限
          loadAsyncRouter = true
          const allAuth = getUserAllMenu();
          next({
            ...to,
            replace: true
          })
          if (process.env.NODE_ENV == 'development') {
            next({
              ...to,
              replace: true
            })
          } else {
            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')
              }
            } else {
              next('/404')
            }
          }
        } else {
          next()
        }
      }
    } else {
      let urlPath = to.matched[0].path
      if (urlPath.indexOf('/:') != -1) urlPath = urlPath.substring(0, urlPath.indexOf('/:'))
      if (whiteList.indexOf(urlPath) !== -1) {
        next()
      } else {
        next(`/auth/login?redirect=${decodeURIComponent(to.path)}`) // 否则全部重定向到登录页
      }
    }
  })

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