import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import filters from './filters'
import directive from './directive'
import { http } from './ajax/index.js';
import axios from 'axios'

import { showLoading, hideLoading } from './ajax/loading';
import Util from "./tool";

//本地环境开启提示信息
Vue.config.productionTip = false;

//加载全局样式
import '@/assets/css/public/common.min.css'
import '@/assets/css/font/iconfont.css'


//加载过滤器
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]));

//加载自定义指令
Vue.use(directive);

//处理顶部导航TAB
router.afterEach((to, from, next) => {
  if (to.path == "/" || to.path == "/login" || to.path == '/notfound'||to.path == '/bindError') {
    return
  }
  let tabOldArr = sessionStorage.getItem('tabs');
  let tabOldJson;
  let tabNewJson = [];
  if (tabOldArr) {
    tabOldJson = JSON.parse(tabOldArr);
    for (var i = 0; i < tabOldJson.length; i++) {
      tabNewJson.push(JSON.stringify(tabOldJson[i]))
    }
    if (tabNewJson.indexOf(JSON.stringify({
      path: to.path,
      title: to.meta.title,
      query: to.query
    })) == -1) {
      
      tabOldJson.push({
        path: to.path,
        title: to.meta.title,
        query: to.query
      })
    }
  } else {
    tabOldJson = [
      {
        path: to.path,
        title: to.meta.title,
        query: to.query
      }
    ]


  }
  if (tabOldJson) {
    sessionStorage.setItem('tabs', JSON.stringify(tabOldJson));
  }
});


axios.interceptors.request.use((config) => {
  if(config.loading){
    showLoading();
  }
  
  return config;
}, (err) => {
  return Promise.reject(err)

})

axios.interceptors.response.use(res => {
  hideLoading();
  if(res.data.err_code==101){
    //token验证失败
    var path_=window.location.hash
    path_=path_.substr(1)
    console.log(path_)
    window.location.href = '/#/login?referer=' + encodeURI(path_);
  }
  return res.data;
}, error => {
  // Message('网络出现问题,请检查网络');
  hideLoading();
  return Promise.reject(new Error(error))
})

//挂载到VUE原型上封装后的http请求
Vue.prototype.$http = http;

//路由页面回跳处理  
router.beforeEach((to, from, next) => {
  if (to.path == "/login" || to.path == '/notfound' ||to.path == '/bindError') {
    next()
  } else {
    let token = Util.getCookie('token') || '';
    if (!token) {
      sessionStorage.removeItem('userInfox')
      var path_=window.location.hash
      path_=path_.substr(1)
      window.location.href = '/#/login?referer=' + encodeURI(path_);
      history.go(0);
    } else {
      next();
    }
  }
});


new Vue({
  router,
  render: (h) => h(App),
}).$mount("#app");