import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import _ from 'lodash'

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

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

// 主入口路由
// const mainRoutes = {}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addMenuRoutes(menuList = [], routes = []) {
  // routes = JSON.parse(JSON.stringify(routes))
  // menuList = JSON.parse(JSON.stringify(menuList))
  const tmp = []
  if (routes.length > 0) {
    for (let i = 0; i < routes.length; i++) {
      const index = _.findIndex(menuList, (o) => o.menuCode === routes[i].menuId)
      if (index !== -1) {
        const route = routes[i]
        if (route.children !== undefined) {
          route.children = addMenuRoutes(menuList[index].children, route.children)
        }
        tmp.push(route)
      }
    }
  }
  return tmp
}

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // 检查用户是否曾经登录过
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        await store.dispatch('permission/setCurrentRoute', to)
        await store.dispatch('esvDialog/resetClass', to)
        next()
      } else {
        try {
          // 检查用户 token 是否有效
          await store.dispatch('user/checkToken')

          // get user info
          await store.dispatch('user/getInfo')

          // 获取字典表数据
          await store.dispatch('app/getDictionary')

          // 获取可访问的 菜单页面列表 和 按键列表
          const { data: menuList } = await store.dispatch('user/getMenuList')
          const { data: permissionList } = await store.dispatch('user/getPermissionList')

          // 使用获取的 menuList 与 asyncRoutes 进行对比得到可访问的 access routes map
          let accessRoutes = await store.dispatch('permission/generateRoutes')
          accessRoutes = addMenuRoutes(menuList, accessRoutes)
          await store.dispatch('permission/setRoutes', accessRoutes)
          await store.dispatch('permission/setPermissions', permissionList)

          // 添加全局垫底的404
          accessRoutes.push({ path: '*', redirect: '/404', hidden: true })

          // fnAddDynamicMenuRoutes(menuList)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history system-log
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error.message || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
