import Vue from 'vue'
import Cookies from 'js-cookie'
import router from './router'
import store from './store'
import request from '@/utils/request'
import {getToken, setToken, cookGetToken} from '@/utils/auth'
const stopPath = ['/login', '/noAccess', '/']
import { wxAuth } from "@/utils/wx-auth-two.js";
router.beforeEach((to, from, next) => {
  if (Vue.$httpRequestList.length > 0) { //强行中断时才向下执行
    Vue.$httpRequestList.forEach(item => {
      item('interrupt'); //给个标志，中断请求
    })
  }
  //首页按返回到登录 或 初始化时--直接退出
  if(from.path == '/home' && ( to.path == '/login'  || to.path == '/init' || to.path == '/') || from.path == '/noAccess'){
    wx.closeWindow();//关闭当前网页窗口
    return false
  }
  if(stopPath.indexOf(to.path) !== -1){
    next()
  }else{
    if (cookGetToken()){//Cook中A-Token
      setToken(cookGetToken())
      detailAxiox()//员工详细信息
      Cookies.remove('Admin-Token')
      thens(to, from, next)
    } else if (getToken()) {//local中A-Token
      thens(to, from, next)
    } else {
      if (!window.$routes_map[to.name].need_login) { // 在免登录白名单，直接进入
        if(to.name=='init'&&localStorage.getItem('init')){
          next('/login')
        }else{
          if (typeof(window.$routes_map[to.name]) != 'undefined') {
            window.document.title = window.$routes_map[to.name].label
          }
          next()
        }
      } else {
        window.location.href = process.env.BASE_API//直接重新授权
      }
    }
  }
})

function thens(to, from, next){
  if(to.name !== 'home'){
    window.document.title = window.$routes_map[to.name].label
  }
  if (to.path == '/login' || to.name == 'init') { // 在免登录白名单，直接进入
    next({ name: 'home'})
  }
  // 初始一些数据
  init(to);
  wxAuth(false,next,to)
}

function init(to) {
  store.dispatch('get_user_info', getToken()).then((res) => { //获取用户信息
    if (router.history.current.name == 'login' && to.name != 'home') {
      router.push({
        name: 'home'
      })
      return false
    }
    if (store.getters.user_info.try_user == 1) { //判断是否试用账号
      store.dispatch("setBuyPopup",true);
    }else{
       store.dispatch("setBuyPopup",false);
    }
  });
  store.dispatch('get_point_types').then(res => {}); //获取积分类型
  // 数据更新，每两分钟更新一次
  store.dispatch('get_employee_map').then((res) => {}); //获取人员列表
}

function detailAxiox(){
  request('get',process.env.BASE_API+'/api/employee/detail')
  .then(res => {
    if(res.data.code == 1){
      store.commit("SET_USERINFO", res.data.data.user); // 设置员工信息
      window.sessionStorage.setItem('__VCKEEPALIVE__', JSON.stringify(['/']))
      window.sessionStorage.setItem('routers', '/')
      console.log(getToken());
      console.log(JSON.parse(localStorage.getItem('user_info')))
      console.log(store.getters.user_info)
    }
  })
}
