import axios from 'axios'

var isProduction = process.env.NODE_ENV === 'production'

// const serverName = isProduction ? 'http://192.168.0.135:8001/' : 'http://192.168.0.135:8001/'
const serverName = isProduction ? 'http://8.135.106.227:8001/' : 'http://8.135.106.227:8001/'

axios.defaults.baseURL = serverName
axios.defaults.headers['X-Requested-with'] = 'XMLHttpRequest'
// axios.defaults.headers['token'] = window.localStorage.getItem('token')

axios.interceptors.request.use(function (config) {
  if (config.method === 'post') {
    config.data = {
      ...config.data,
      rnd: Math.random()
    }
  } else if (config.method === 'get') {
    config.params = {
      rnd: Math.random(),
      ...config.params
    }
  }

  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 配置response拦截器
axios.interceptors.response.use(
  response => {
    let data = response.data
    let code = Number(response.data.code)
    switch (code) {
      case -1:
        break
      case 4500:
        break
      case 5001:
        console.log('50015001500150015001')
        break
      case 5002:
        break
      case 500:
        break
      case 0:
        break
      default:
        alert(data.msg)
        break
    }
    return data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 400:
          console.log('=======前端参数传错了======')
          break
        case 500:
          console.log('========服务器错误=======')
          break
        default:
          console.log('error.response', error.response)
          break
      }
    }
    return Promise.reject(error)
  }
)
export { axios }
