import axios from 'axios'
import router from '@/router'
import store from '@/store'
import { Message,Loading } from 'element-ui'

//弹窗状态开关
let messageData = null;

// 弹层数据
let loadingInstance = {};
let options = {
  text:"",
  spinner:"",
  background: 'rgba(0, 0, 0, 0.1)'
};
let loadingCount = 0;

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '',
  timeout: Number(process.env.VUE_APP_TIMEOUT) || 15000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 弹层相关
    loadingInstance = Loading.service(options)
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    // 弹层相关
    loadingCount ++;
    return config
  },
  error => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0){
      loadingInstance.close();
    }
    Promise.reject(error)
  })

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0) {
      loadingInstance.close();
    }
    return response.data
  },
  error => {
    // 弹层相关
    loadingCount --;
    if(loadingCount===0){
      loadingInstance.close();
    }
    if (error.response && error.response.status === 401) {
      store.dispatch('logout')
      if (router.currentRoute.path !== '/login') {
        router.replace('/login')
      }
    } else {
      const msg = error.response && error.response.data && error.response.data.message
        ? error.response.data.message
        : error.message || '请求失败'
      Message.error(msg)
    }
    return Promise.reject(error)
  }
)

export default service
