import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // get token from cookie
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'
import RouterView from '@/views/routerView.vue'
import IframeView from '@/views/iframeView.vue'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法
const whiteList = ['/login'] // no redirect whitelist
const lay = {
  path: '/',
  redirect: '/dashboard',
  component: Layout,
  children: []
}
// 递归找最后一级页面
function getc(obj) {
  if (!obj.children || !obj.children.length) {
    return obj
  } else {
    return getc(obj.children[0])
  }
}
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/getInfo')
          await store.dispatch('user/getRouter')
          if (store.getters.menus.length < 1) {
            global.antRouter = []
            next()
          }
          // 设置路由
          lay.children = []
          for (var route of store.getters.menus) {
            lay.children.push(buildRoute(route))
          }
          lay.redirect = getc(lay).name
          router.addRoutes([lay])
          global.antRouter = lay.children
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next('/login')
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

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

function buildRoute(route) {
  const { url, moduleName, icon, moduleId, code, type, hidden, fullUrl } = route
  var item = {}
  item.path = fullUrl || code
  item.name = fullUrl || code
  item.meta = {
    url,
    title: moduleName,
    icon: icon,
    moduleId
  }
  item.hidden = hidden
  if (route.children && route.children.length) {
    if (type == 2) {
      try {
        item.component = _import(`${fullUrl}`)
      } catch (e) {
        console.log(e)
      }
      const roles = []
      for (var role of route.children) {
        roles.push(role.code)
      }
      item.meta.roles = roles
    } else {
      item.component = RouterView
      item.children = route.children.map(child => buildRoute(child))
    }
  } else {
    if (type == 4) {
      item.component = IframeView
    } else {
      try {
        item.component = _import(`${fullUrl}`)
      } catch (e) {
        console.log(e)
      }
    }
  }
  return item
}
