import axios from 'axios'
import { replaceUrlParams } from './index'

const MultiForm = 'multipart/form-data'

export default function request (config = {}, axiosResult = false) {
  let {
    urlParams = undefined,
    contentType = undefined,
    method = 'get',
    url = '',
    data = undefined,
    headers = {},
    ...axiosConf
  } = config

  url = replaceUrlParams(url, urlParams)

  if (method === 'get' || method === 'GET') {
    // get 请求丢掉 body 参数
    data = undefined
  } else {
    if (!contentType) {
      contentType = MultiForm
      headers = { ...headers, 'Content-Type': MultiForm }
    }
  }

  // data 转换为 formdata, 但是只支持一层结构的 plainobject
  if (data && contentType === MultiForm) {
    if (!(data instanceof window.FormData)) {
      data = Object.keys(data).reduce((fmt, k) => {
        if (Array.isArray(data[k])) {
          data[k].forEach(x =>  fmt.append(k, x))
        } else {
          fmt.append(k, data[k])
        }

        return fmt
      }, new window.FormData)
    }
  }

  const rtn = axios({
    url,
    method,
    data,
    headers,
    ...axiosConf
  })

  // 如果不需要业务封装, 返回 axios 原始结果
  if (axiosResult) return rtn

  // 否则
  return new Promise((resolve, reject) => {
    rtn.then(({ data }) => {
      const { code, message } = data
      
      if (code === 200) {
        resolve(message)
      } else {
        reject(message)
      }
    }).catch((error) => {
      if (error.message) {
        reject(error.message)
      } else {
        reject(`${error.response.status} - ${error.response.statusText}`)
      }
    })
  })
}
