/*
 * @Author: your name
 * @Date: 2022-02-22 14:22:46
 * @LastEditTime: 2022-03-04 15:52:40
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \lowcode-ui\src\permission.js
 */
import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH } from './store/mutation-types'
import { domTitle, setDocumentTitle } from '../packages/utils/domUtil'
import { asyncRouterMap } from './config/router.config.js'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const toDefaultRoute = ['/user/login', '/user/loginSys', '/cms/content']
const loginRoutePath = '/user/login'
const IS_DEVELOPMENT = process.env.NODE_ENV === 'development'
const whiteList = IS_DEVELOPMENT
  ? ['register', 'login', 'loginSys', 'Analysis', 'TodoList']
  : ['register', 'login', 'loginSys']
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (toDefaultRoute.includes(to.path)) {
      next({ path: INDEX_MAIN_PAGE_PATH })
      NProgress.done()
    } else {
      if (store.getters.addRouters.length === 0) {
          const constRoutes = asyncRouterMap
          store.dispatch('GenerateRoutes', { constRoutes }).then(() => {
            // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表
            router.addRoutes(store.getters.addRouters)
            const redirect = decodeURIComponent(from.query.redirect || to.path)
             if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              // next({ path: redirect })
              next({ path: INDEX_MAIN_PAGE_PATH })
            }
          })
      } else {
        next()
      }
    }
  } else {
    if (!to || !to.name) {
      next({ path: loginRoutePath })
    } else if (whiteList.includes(to.name)) {
      next()
    } else {
      Notification.warning({
        message: '系统通知',
        description: 'token 已过期, 请重新登录！',
        duration: 2,
        onClose: function () {
          store.dispatch('Logout').then(() => {
            next({ path: loginRoutePath, query: { redirect: to.fullPath } })
          })
        }
      })
    }
  }
})

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