import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '../router'
const service = axios.create({
  baseURL: global_config.BASE_URL,
  timeout: 500000,
  headers: {
  }
})

// 请求拦截器
service.interceptors.request.use(config => {
  config.headers['X-Token'] = store.getters.getToken;
  config.headers['Authorization'] = 'Bearer ' + store.getters.getToken
  return config
},
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(response => {
  const res = response.data;
  if (res.code === 0) {
    return response.data;
  } else {
    Message.closeAll();
    Message({
      message: res.message,
      type: 'error',
      duration: 3 * 1000
    })
    if(res.code==401){
      store.commit('CLEAR')
      router.push('/');
    }
  }
  return Promise.reject(res.Message)
},
  error => {
    Message.closeAll();
    Message({
      message: '请求超时，请检查网络后重试！',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
