import Cookies from 'js-cookie'
import router from './router'
import store from './store'
import Vue from 'vue'
import {
  Message
} from 'element-ui'
import {
  cookGetToken,
  localSetToken,
  getToken,
  removeToken
} from '@/utils/auth'
import {
  wxAuth
} from '@/utils/wx-auth-two.js';

function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('admin') >= 0) return true
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
// 免登名单
const whiteList = ['/invite_new_company', '/create_company', '/login', '/loginTransfer', '/noAccess', '/loginbytoken',
  '/reg', '/forgetPwd', '/resetPwd', '/android', '/demo', '/swiperShow', '/autoLogin'
]
const stopPath = ['/login', '/noAccess']
router.beforeEach((to, from, next) => {
  if (Vue.$httpRequestList.length > 0) { //强行中断时才向下执行
    Vue.$httpRequestList.forEach(item => {
      item('interrupt'); //给个标志，中断请求
    })
  }
  if (stopPath.indexOf(to.path) !== -1) {
    next()
  } else {
    if (cookGetToken()) {
      if (getToken() !== cookGetToken()) {
        store.commit('SET_DELETE_USER', {})
        store.commit('SET_TOKEN', cookGetToken())
        localStorage.setItem('Admin-Token', cookGetToken())
        init(to, next)
      } else {
        init(to, next)
      }
    } else if (getToken()) {
      if (!store.state.user.token) store.commit("SET_TOKEN", getToken());
      init(to, next)
    } else {
      if (whiteList.indexOf(to.path) !== -1 || window.location.href.indexOf('loginbytoken/') !== -1) { // 在免登录白名单，直接进入
        next()
      } else {
        // window.location.href = process.env.BASE_API //直接重新授权
      }
    }
  }
})

function init(to, next) {
  if (to.path === '/login') {
    next({
      path: '/'
    })
  } else {
    if (!store.getters.user_info.id) { // 判断当前用户是否已拉取完user_info信息
      store.dispatch('GetUserInfo').then(res => { // 拉取user_info
        // 设置title
        document.title = ''
        const mo_list = []
        res.data['mo_list'] = []
        for (const i in mo_list) {
          res.data['mo_list'].push(mo_list[i].code)
        }
        const roles = ['admin']
        store.dispatch('GenerateRoutes', {
          roles
        }).then(() => {
          // 增加动态权限列表,在这里发送一个请求，得到路由
          const addRouters = []
          for (const item in store.getters.addRouters) {
            const obj = []
            for (const ritem in store.getters.addRouters[item].children) {
              if (res.data.mo_list.indexOf(store.getters.addRouters[item].children[ritem].name) >= 0 || store
                .getters.addRouters[item].children[ritem].hidden === true || store.getters.addRouters[item]
                .children[ritem].common === true) {
                obj.push(store.getters.addRouters[item].children[ritem])
              }
              obj.push(store.getters.addRouters[item].children[ritem])
            }
            if (obj.length > 0) {
              const _R = store.getters.addRouters[item]
              _R['children'] = obj
              addRouters.push(_R)
            }
          }
          router.addRoutes(addRouters) // 动态添加可访问路由表
          next({...to,replace: true}) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        })
      }).catch((err) => {
        if (getToken()) {
          next('/login')
        }
      })
    } else {
      // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
      if (hasPermission(store.getters.roles, to.meta.roles)) {
        wxAuth('', next);
      } else {
        next({
          path: '/401',
          replace: true,
          query: {
            noGoBack: true
          }
        })
      }
    }
  }
}

router.afterEach((to, from) => {
  // console.log("当前页面" + to.name)
})
