import axios from 'axios'
import qs from 'qs'

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 (data.msg) {
      if (data.msg === '请先登录') {
        window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      }
    }
    if (parseInt(data.code) === 1) {
      return Message.error(data.msg)
    }
    if (data.code) {
      if (data.code === 4001) {
        window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      }
      return data.message ? Message.error(data.message) : Message.error(data.msg)
    }
    return data
  },
  function(error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      }
      Message.error(message || error.response.data)
      return Promise.reject(error.response)
    } else {
      Message.error(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
