import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

const httpRequest = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// 请求拦截
httpRequest.interceptors.request.use(
  function(config) {
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function(response) {
    return response.data
  },
  function(error) {
    if (error.response) {
      const { status, message } = error.response.data
      if (status === 400) {
        Message.error(message)
      }
    } else {
      Message.error(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
