/**
 * tdesign v0.41.7
 * (c) 2022 tdesign
 * @license MIT
 */

function xhr(_ref) {
  var _ref$method = _ref.method,
      method = _ref$method === void 0 ? "POST" : _ref$method,
      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,
      files = _ref.files,
      _ref$name = _ref.name,
      name = _ref$name === void 0 ? "file" : _ref$name,
      onError = _ref.onError,
      onProgress = _ref.onProgress,
      onSuccess = _ref.onSuccess;
  var innerFiles = files || [];
  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]);
  });
  innerFiles.forEach(function (f) {
    formData.append(name, f && f.raw);
  });
  xhr2.open(method, action, true);
  Object.keys(headers).forEach(function (key) {
    xhr2.setRequestHeader(key, headers[key]);
  });

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

  if (xhr2.upload) {
    xhr2.upload.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,
        files: innerFiles
      });
    };
  }

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

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

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

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

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

  xhr2.send(formData);
  return xhr2;
}

export { xhr as default };
//# sourceMappingURL=xhr.js.map
