import router, { constantRouterMap, currentRouterMap } from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  console.log('路径: ', to.path)
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          const rounterMap = []
          const permissionMap = res.data.permissionList
          // 构造父路由
          constantRouterMap.forEach(router => {
            permissionMap.forEach(permission => {
              if (router.name === permission['menuUrl']) {
                rounterMap.push(router)
              }
              // 子节点匹配
              router.children.forEach(children => {
                if (children.name === permission['menuUrl']) {
                  // 如果包含, 防止和上面重复添加, 不包含的时候添加一次
                  if (!rounterMap.includes(router)) {
                    rounterMap.push(router)
                  }
                }
              })
            })
          })

          // 构造子路由
          rounterMap.forEach(router => {
            const childMap = []
            router.children.forEach(child => {
              if (child.hidden) {
                childMap.push(child)
              }
              permissionMap.forEach(permission => {
                if (child.name === permission['menuUrl']) {
                  childMap.push(child)
                }
              })
            })
            router.children = childMap
          })

          rounterMap.concat({ path: '*', redirect: '/404', hidden: true })
          router.addRoutes(rounterMap)

          store.commit('AddRoutes', currentRouterMap.concat(rounterMap))

          next({ ...to, replace: true })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // if (to.path === '/') {
    //   next(`/login?redirect=${to.path}`)
    //   NProgress.done()
    // }
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
