import axios from 'axios'

// 远程请求, 返回 promise
// 参数 api 与 axios 基本一致
// 增加了一个 urlData 字段, 用来设置 url path 变量值
function request(params = {}) {
  const { urlData, data: rawData, url: rawURL, headers = {}, ...config } = params;
  const url = replaceApiParams(rawURL, urlData)
  // const data = (rawData instanceof FormData) ? rawData : JSON.stringify(rawData)
  const token = localStorage.getItem('x-token') || ''
  const contenType = (rawData instanceof FormData) ? 'multipart/form-data' : 'application/json'
  
  return new Promise((resolve, reject) => {
    axios({
      ...config,
      url,
      data: rawData,
      headers: {
        'Content-Type': contenType,
        ...headers,
        'Authorization': `Bearer ${token}`,
      }
    }).then(({ data: res }) => {

      // 服务端返回包含 code, message, data 字段
      const { code, data } = res

      // 业务处理正确则返回 1000
      if (code === 1000) {
        resolve(data)
      } else {
        reject(res)
      }

    }).catch((error) => {
      // 异常情况
      if (error.response) {
        reject({ message: error.response.statusText })
      } else {
        reject({ message: error.message })
      }
    })
  })
}

function replaceApiParams (url, params) {
  if (typeof params !== 'object') return url

  return url.split('/').map((it) => {
    if (it.indexOf(':') === 0) {
      const theKey = it.substr(1)
      return Object.prototype.hasOwnProperty.call(params, theKey)
        ? params[theKey]
        : it
    }

    return it
  }).join('/')
}

export default request
