import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
const service = axios.create({
  // eslint-disable-next-line no-undef
  baseURL: global_config.BASE_URL,
  timeout: 50000,
  headers: {}
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers['X-Token'] = localStorage.getItem('Token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

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

export default service
