import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap, initRouterTree } from '@/router/router.config'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import 'simple-lightbox/dist/simpleLightbox.min.css' // progress bar style
import store from '@/store/index'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import notification from 'ant-design-vue/es/notification'

const whiteList = ['/user/login']
const loginUrl = '/user/login'
Vue.use(Router)
const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach((to, from, next) => {
  store.commit('resetLoading')
  NProgress.start()
  if (to.matched && to.matched.length > 0) {
    store.commit('changeBreadcrumb', to.matched)
  }

  let token = Vue.ls.get(ACCESS_TOKEN) || sessionStorage.getItem(ACCESS_TOKEN)
  if (token != undefined && token != null && token.length > 0) {
    if (to.path === loginUrl) {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.addRouters.length === 0) {
        store.dispatch('GetInfo').then(res => {
          let menuList = res.data.menuList
          if (menuList.length > 0) {
            store.dispatch('GenerateRoutes', initRouterTree(menuList))
              .then(() => {
                router.addRoutes(store.getters.addRouters)
                const redirect = decodeURIComponent(from.query.redirect || to.path)
                if (to.path === redirect) {
                  // hack方法 确保addRoutes已完成
                  next({ ...to, replace: true })
                } else {
                  // 跳转到目的路由
                  next({ path: redirect })
                }
              })
          } else {
            notification.error({ message: '错误', description: '当前登录用户没有任何权限，请联系管理员增加权限' })
            store.dispatch('Logout').then(() => {
              next({ path: loginUrl, query: { redirect: to.fullPath } })
            })
            NProgress.done()
          }
        }).catch((e) => {
          console.error(e)
          notification.error({ message: '错误', description: '请求用户信息失败，请重试' })
          store.dispatch('Logout').then(() => {
            next({ path: loginUrl, query: { redirect: to.fullPath } })
          })
          NProgress.done()
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // if (to.fullPath != '/') {
      //   next({path: loginUrl, query: {redirect: to.fullPath}})
      // } else {
      // 在没有tonken时（一般是退出登录时）直接进首页，不再进入历史路由页面
      next({ path: loginUrl })
      // }
      NProgress.done()
    }
  }
}
)

router.afterEach(() => {
  NProgress.done()
})

export default router