/**
 * tdesign v0.32.0
 * (c) 2021 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function xhr(_ref) {
  var action = _ref.action,
      _ref$withCredentials = _ref.withCredentials,
      withCredentials = _ref$withCredentials === void 0 ? false : _ref$withCredentials,
      _ref$headers = _ref.headers,
      headers = _ref$headers === void 0 ? {} : _ref$headers,
      _ref$data = _ref.data,
      data = _ref$data === void 0 ? {} : _ref$data,
      file = _ref.file,
      _ref$name = _ref.name,
      name = _ref$name === void 0 ? "file" : _ref$name,
      onError = _ref.onError,
      onProgress = _ref.onProgress,
      onSuccess = _ref.onSuccess;
  var xhr2 = new XMLHttpRequest();

  if (withCredentials) {
    xhr2.withCredentials = true;
  }

  var formData = new FormData();
  var sendData = typeof data === "function" ? data(file) : data;
  Object.keys(sendData).forEach(function (key) {
    formData.append(key, data[key]);
  });
  formData.append(name, file.raw);
  xhr2.open("post", action, true);
  Object.keys(headers).forEach(function (key) {
    xhr2.setRequestHeader(key, headers[key]);
  });

  xhr2.onerror = function (event) {
    return onError({
      event: event,
      file: file
    });
  };

  xhr2.onprogress = function (event) {
    var percent = 0;

    if (event.total > 0) {
      percent = Math.round(event.loaded / event.total * 100);
    }

    onProgress({
      event: event,
      percent: percent,
      file: file
    });
  };

  xhr2.onload = function (event) {
    var response;
    var isFail = xhr2.status < 200 || xhr2.status >= 300;

    if (isFail) {
      return onError({
        event: event,
        file: file,
        response: response
      });
    }

    var text = xhr2.responseText || xhr2.response;

    try {
      response = JSON.parse(text);
    } catch (e) {
      response = text;
    }

    onSuccess({
      event: event,
      file: file,
      response: response
    });
  };

  xhr2.send(formData);
  return xhr2;
}

exports["default"] = xhr;
//# sourceMappingURL=xhr.js.map
