const defaultRequestParams = {
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 15000,
  withCredentials: true,
  async: true,
  params: undefined,
  method: 'GET',
}

export default function requestAjax(url, config) {
  return new Promise((resolve, reject) => {
    const params = Object.assign({}, defaultRequestParams, config)

    const xhr = new XMLHttpRequest()
    xhr.timeout = params.timeout
    if (params.withCredentials) xhr.withCredentials = true
    xhr.open(params.method, url, params.async)
    if (typeof params.headers === 'object' && params.headers !== null) {
      Object.keys(params.headers).forEach(key => {
        xhr.setRequestHeader(key, params.headers[key])
      })
    }
    xhr.onerror = event => reject(event)
    xhr.onabort = event => reject(event)
    xhr.ontimeout = event => reject(event)

    xhr.onload = e => {
      if (e.currentTarget.status === 200) {
        try {
          const res = JSON.parse(xhr.responseText)
          if (res.success || +res.code === 200) resolve(res)
          reject(
            new Error(res.msg || res.info || res.message || '请求出错, 请重试'),
          )
        } catch (error) {
          reject(error)
        }
      } else {
        reject(e)
      }
    }
    xhr.send(params.params || null)
  })
}
