import Vue from 'vue'
import ElementUI, {
  MessageBox
} from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
import App from './App.vue'
import router from './router'
import store from './vuex/store'

// 引入icon
import './assets/icon/iconfont.css'
import './assets/style/custom.scss'

// 引入加载
import {
  showLoading,
  hideLoading
} from './utils/loading';

import 'element-ui/lib/theme-chalk/base.css';
import ElCollapseTransition from 'element-ui/lib/transitions/collapse-transition';

Vue.component(ElCollapseTransition.name, ElCollapseTransition)

import axios from 'axios';
Vue.prototype.$axios = axios;

Vue.prototype.$baseApiUrl = process.env.VUE_APP_API;
Vue.prototype.$baseImgUrl = process.env.VUE_APP_IMGAPI;
// 引入utils的方法
import * as utils from './utils/utils'
Vue.prototype.$utils = utils;
// 防重复点击(指令实现)
Vue.directive('throttle', {
  inserted(el, binding) {
    el.addEventListener('click', () => {
      el.style.pointerEvents = 'none';
      if (!el.disabled) {
        setTimeout(() => {
          el.style.pointerEvents = 'auto';
        }, binding.value || 3000);
      }
    });
  }
});
//响应拦截器
axios.interceptors.response.use(response => {
  if (response.data.code === 401) {
    hideLoading();
    localStorage.clear();
    MessageBox.alert("登录超时请重新登录！", "提示", {
      confirmButtonText: "确定",
      showClose: false,
      callback: () => {
        router.push("/login");
        window.location.reload();
      }
    }).then(r => this.load(false));
  }
  return response;
}, function (error) {
  hideLoading();
  router.push("/login");
  return Promise.reject(error)
});

// 路由拦截器
router.beforeEach((to, from, next) => {
  // if(to.name){
  //   document.title = to.name
  // }

  if (JSON.parse(localStorage.getItem("userdata")) == null) {
    window.localStorage.clear();
  }

  if (to.matched.length != 0) {
    if (to.meta.requireAuth) { // 判断该路由是否需要登录权限

      if (Boolean(localStorage.getItem("userInfo"))) { // 通过vuex state获取当前的user是否存在
        next();
      } else {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath
          } // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
      }
    } else {

      if (Boolean(localStorage.getItem("userInfo"))) { // 判断是否登录
        if (document.URL.indexOf("?") > 0) {
          localStorage.clear()
          next();
        } else {
          if (to.path != "/" && to.path != "/login") { //判断是否要跳到登录界面
            next();
          } else {
            /**
             * 防刷新，如果登录，修改路由跳转到登录页面，修改路由为登录后的首页
             */
            next({
              path: '/home/index'
            })
          }
        }

      } else {
        next();
      }
    }
  } else {
    next({
      path: '/login',
      query: {
        redirect: to.fullPath
      } // 将跳转的路由path作为参数，登录成功后跳转到该路由
    })
  }
})

Vue.config.productionTip = false
new Vue({
  render: h => h(App),
  store,
  router
}).$mount('#app')
