import axios from 'axios'
import qs from 'qs'
import { Notify } from 'vant'

const httpRequest = axios.create({
  baseURL: 'https://project-api.ezijing.com',
  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)
    }
    if (config.headers['Content-Type'] === 'multipart/form-data') {
      const form = new window.FormData()
      for (const key in config.data) {
        form.append(key, config.data[key])
      }
      config.data = form
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function(response) {
    const { data } = response
    if (parseInt(data.code)) {
      Notify(data.msg)
      return Promise.reject(data)
    }
    return data
  },
  function(error) {
    if (error.response) {
      const { message } = error.response.data
      Notify(message || error.response.data)
      return Promise.reject(error.response)
    } else {
      Notify(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
