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

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']

router.beforeEach((to, from, next) => {
  localStorage.setItem('routerBefore', from.path)
  LoadingBar.start()
  /** 请求头包含授权信息 并且 页面必须授权 直接进入 */
  if (getAuth()) {
    //debugger;
    if (to.path === '/auth/login' || to.path === '/') {
      next('/index')
      LoadingBar.stop()
    } else {
      if (!loadAsyncRouter) {
        // 判断当前用户是否获取权限
        loadAsyncRouter = true
        const allAuth = getUserAllMenu()
        console.log(allAuth)
        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) => {
              console.log(x.menuUrl,to.path)
              return x.menuUrl == to.path
            })
            console.log(authMenu)
            if (authMenu != -1) {
              next({
                ...to,
                replace: true
              })
            } else {
              next('/404')
            }
            LoadingBar.stop()
          } else {
            next('/404')
            LoadingBar.stop()
          }
        }
      } else {
        next()
      }
    }
  } else {
    let urlPath=to.matched[0].path
    if(urlPath.indexOf('/:')!=-1) urlPath=urlPath.substring(0,urlPath.indexOf('/:'))
    if (whiteList.indexOf(urlPath) !== -1) {
      console.log(whiteList,to.path)
      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)
  }
})
