import Vue from 'vue'
import Router from 'vue-router'
import { loginRouter } from './routes.js'
import store from '@/store/index'
import { Message } from 'element-ui'
Vue.use(Router)
const originalPush = Router.prototype.push
const router = new Router({
  routes: [loginRouter]
})
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const LOGIN_PAGE_NAME = 'login'
// 跳转之前
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('Token')
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (to.name === LOGIN_PAGE_NAME) {
    next()
  }  else {
    if (token) {
      if (!store.state.permission.permissionList) {
        try {
          let accessRoutes = await store.dispatch('permission/FETCH_PERMISSION')
          await router.addRoutes(accessRoutes)
          let flag = ruleValidate(accessRoutes, to.path)
          if (flag) {
            next({ ...to, replace: true })
          } 
        } catch (err) {
          if (err.code != '0') {
            next({
              name: LOGIN_PAGE_NAME // 跳转到登录页
            })
          }
        }
      } else {
        // store.dispatch('permission/FETCH_AUTHORID')
        next()
      }
    } else {
      next({
        name: LOGIN_PAGE_NAME
      })
    }
  }
})
function ruleValidate(data, path) {
  let flag = false
  function judgeChildren(data, path) {
    data.forEach(e => {
      if (flag) {
        return
      }
      if (e.path === path) {
        flag = true
        return
      } else if (e.children && e.children.length) {
        judgeChildren(e.children, path)
      }
    })
  }
  judgeChildren(data, path)
  return flag
}

export default router
