/**
 * ldesign v0.3.13
 * (c) 2023 ldesign
 * @license MIT
 */

import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _typeof from '@babel/runtime/helpers/typeof';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import isFunction from 'lodash/isFunction';
import log from '../log/log.js';
import { getCurrentDate } from './utils.js';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function xhr(_ref) {
  var _files$;
  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,
    _ref$files = _ref.files,
    files = _ref$files === void 0 ? [] : _ref$files,
    _ref$name = _ref.name,
    name = _ref$name === void 0 ? "file" : _ref$name,
    _ref$useMockProgress = _ref.useMockProgress,
    useMockProgress = _ref$useMockProgress === void 0 ? true : _ref$useMockProgress,
    _ref$mockProgressDura = _ref.mockProgressDuration,
    mockProgressDuration = _ref$mockProgressDura === void 0 ? 300 : _ref$mockProgressDura,
    formatRequest = _ref.formatRequest,
    onError = _ref.onError,
    onProgress = _ref.onProgress,
    onSuccess = _ref.onSuccess;
  var innerFiles = files || [];
  var percent = 0;
  var xhr2 = new XMLHttpRequest();
  if (withCredentials) {
    xhr2.withCredentials = true;
  }
  var timer1;
  var timer2;
  if (useMockProgress && ((_files$ = files[0]) === null || _files$ === void 0 ? void 0 : _files$.status) === "progress") {
    var timer22 = setTimeout(function () {
      timer1 = setInterval(function () {
        if (percent + 10 < 100) {
          percent = Math.max(percent + 10, percent);
          if (files[0] && percent !== files[0].percent) {
            files[0].percent = percent;
            onProgress({
              percent: percent,
              file: file || innerFiles[0],
              files: innerFiles.map(function (file2) {
                return _objectSpread(_objectSpread({}, file2), {}, {
                  percent: percent
                });
              }),
              type: "mock",
              XMLHttpRequest: xhr2
            });
          }
        } else {
          clearInterval(timer1);
        }
      }, mockProgressDuration);
      clearTimeout(timer22);
    }, mockProgressDuration);
  }
  var requestData = {};
  if (data) {
    var extraData = isFunction(data) ? data(innerFiles) : data;
    Object.assign(requestData, extraData);
  }
  innerFiles.forEach(function (file2, index) {
    var fileField = innerFiles.length > 1 ? "".concat(name, "[").concat(index, "]") : name;
    requestData[fileField] = file2.raw;
  });
  if (innerFiles.length === 1) {
    requestData[name] = innerFiles[0].raw;
  }
  requestData.length = innerFiles.length;
  if (formatRequest) {
    requestData = formatRequest(requestData);
  }
  var formData = new FormData();
  Object.keys(requestData).forEach(function (key) {
    formData.append(key, requestData[key]);
  });
  xhr2.open(method, action, true);
  Object.keys(headers).forEach(function (key) {
    xhr2.setRequestHeader(key, headers[key]);
  });
  xhr2.onerror = function (event) {
    onError({
      event: event,
      file: file,
      files: innerFiles,
      XMLHttpRequest: xhr2
    });
    clearInterval(timer1);
    clearTimeout(timer2);
  };
  xhr2.ontimeout = function (event) {
    onError({
      event: event,
      file: file,
      files: innerFiles,
      XMLHttpRequest: xhr2
    });
  };
  if (xhr2.upload) {
    xhr2.upload.onprogress = function (event) {
      var _innerFiles$;
      var realPercent = 0;
      if (event.total > 0) {
        realPercent = Math.round(event.loaded / event.total * 100);
      }
      percent = Math.max(realPercent, percent);
      if (percent !== realPercent && ((_innerFiles$ = innerFiles[0]) === null || _innerFiles$ === void 0 ? void 0 : _innerFiles$.percent) !== percent) {
        var progressFiles = innerFiles.map(function (item) {
          return _objectSpread(_objectSpread({}, item), {}, {
            percent: percent
          });
        });
        onProgress({
          event: event,
          percent: percent,
          file: file || progressFiles[0],
          files: progressFiles,
          type: "real",
          XMLHttpRequest: xhr2
        });
      }
    };
  }
  xhr2.onload = function (event) {
    var response = {};
    response.XMLHttpRequest = xhr2;
    var isFail = xhr2.status < 200 || xhr2.status >= 300;
    if (isFail) {
      return onError({
        event: event,
        file: file,
        files: innerFiles,
        response: response,
        XMLHttpRequest: xhr2
      });
    }
    var text = xhr2.responseText || xhr2.response;
    try {
      response = JSON.parse(text);
    } catch (e) {
      response = text;
      log.error("Upload", "response does not a valid json");
    }
    clearInterval(timer1);
    clearTimeout(timer2);
    innerFiles.forEach(function (file2) {
      var _response;
      file2.percent = 100;
      file2.status = "success";
      file2.uploadTime = ((_response = response) === null || _response === void 0 ? void 0 : _response.uploadTime) || getCurrentDate();
    });
    if (_typeof(response) === "object") {
      response.XMLHttpRequest = xhr2;
    }
    onSuccess({
      event: event,
      file: file || innerFiles[0],
      files: _toConsumableArray(innerFiles),
      XMLHttpRequest: xhr2,
      response: response
    });
  };
  xhr2.send(formData);
  xhr2.upload.requestParams = requestData;
  xhr2.upload.requestHeaders = headers;
  return xhr2;
}

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