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

'use strict';

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

var _toArray = require('@babel/runtime/helpers/toArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isFunction = require('lodash/isFunction');
var isNumber = require('lodash/isNumber');
var _common_js_upload_utils = require('./utils.js');
var _common_js_upload_xhr = require('./xhr.js');
var _common_js_log_log = require('../log/log.js');
require('@babel/runtime/helpers/toConsumableArray');
require('@babel/runtime/helpers/typeof');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toArray__default = /*#__PURE__*/_interopDefaultLegacy(_toArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);
var isNumber__default = /*#__PURE__*/_interopDefaultLegacy(isNumber);

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__default["default"](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 handleBeforeUpload(file, params) {
  var sizeLimit = params.sizeLimit,
    beforeUpload = params.beforeUpload;
  var sizePromise = new Promise(function (resolve) {
    var result = null;
    if (sizeLimit) {
      var sizeLimitObj = isNumber__default["default"](sizeLimit) ? {
        size: sizeLimit,
        unit: "KB"
      } : sizeLimit;
      var limit = _common_js_upload_utils.isOverSizeLimit(file.size, sizeLimitObj.size, sizeLimitObj.unit);
      if (limit) {
        result = sizeLimitObj;
      }
    }
    resolve(result);
  });
  var promiseList = [sizePromise, void 0];
  if (isFunction__default["default"](beforeUpload)) {
    var r = beforeUpload(file);
    var p = r instanceof Promise ? r : new Promise(function (resolve) {
      return resolve(r);
    });
    promiseList[1] = p;
  }
  return new Promise(function (resolve) {
    Promise.all(promiseList).then(function (r) {
      resolve(r);
    });
  });
}
function handleError(options) {
  var event = options.event,
    files = options.files,
    response = options.response,
    XMLHttpRequest = options.XMLHttpRequest,
    formatResponse = options.formatResponse;
  files.forEach(function (file) {
    file.status = "fail";
  });
  var res = response;
  if (isFunction__default["default"](formatResponse)) {
    res = formatResponse(response, {
      file: files[0],
      currentFiles: files
    });
  }
  return {
    response: res,
    event: event,
    files: files,
    XMLHttpRequest: XMLHttpRequest
  };
}
function handleSuccess(params) {
  var event = params.event,
    files = params.files,
    response = params.response,
    XMLHttpRequest = params.XMLHttpRequest;
  if ((files === null || files === void 0 ? void 0 : files.length) <= 0) {
    _common_js_log_log["default"].error("Upload", "Empty File in Success Callback");
  }
  files.forEach(function (file) {
    var _file$response;
    file.percent = 100;
    file.status = "success";
    (_file$response = file.response) === null || _file$response === void 0 ? true : delete _file$response.error;
  });
  var res = response;
  files[0].url = res.url || files[0].url;
  return {
    response: res,
    event: event,
    files: files,
    XMLHttpRequest: XMLHttpRequest
  };
}
function handleRequestMethodResponse(res) {
  if (!res) {
    _common_js_log_log["default"].error("Upload", "`requestMethodResponse` is required.");
    return false;
  }
  if (!res.status) {
    _common_js_log_log["default"].error("Upload", "`requestMethodResponse.status` is missing, which value only can be `success` or `fail`");
    return false;
  }
  if (!["success", "fail"].includes(res.status)) {
    _common_js_log_log["default"].error("Upload", "`requestMethodResponse.status` must be `success` or `fail`, examples `{ status: 'success', response: { url: '' } }`");
    return false;
  }
  if (res.status === "success" && (!res.response || !res.response.url && !res.response.files)) {
    _common_js_log_log["default"].warn("Upload", "`requestMethodResponse.response.url` or `requestMethodResponse.response.files` is required if `status` is `success`");
  }
  return true;
}
function uploadOneRequest(params) {
  var action = params.action,
    toUploadFiles = params.toUploadFiles,
    requestMethod = params.requestMethod;
  return new Promise(function (resolve) {
    if (!action && !requestMethod) {
      _common_js_log_log["default"].error("Upload", "one of action and requestMethod must be exist.");
      resolve({});
      return;
    }
    if (!toUploadFiles || !toUploadFiles.length) {
      _common_js_log_log["default"].warn("Upload", "No files need to be uploaded");
      resolve({});
      return;
    }
    toUploadFiles.forEach(function (file) {
      file.status = "progress";
    });
    if (requestMethod) {
      requestMethod(params.multiple ? toUploadFiles : toUploadFiles[0]).then(function (res) {
        if (!handleRequestMethodResponse(res)) {
          resolve({});
          return;
        }
        var _res$response = res.response,
          response = _res$response === void 0 ? {} : _res$response;
        if (res.status === "fail") {
          response.error = res.error || response.error;
        }
        var resultFiles = [];
        if (response.url && !response.files || res.status === "fail") {
          toUploadFiles.forEach(function (file) {
            file.status = res.status;
            file.response = response;
            file.url = response.url;
          });
          resultFiles = toUploadFiles;
        } else if (response.files) {
          resultFiles = response.files.map(function (file) {
            var fileInfo = toUploadFiles.find(function (toFile) {
              return file.name && toFile.name === file.name || file.raw && toFile.raw === file.raw;
            });
            return _objectSpread(_objectSpread(_objectSpread({}, fileInfo), file), {}, {
              status: res.status,
              response: response
            });
          });
        }
        var result = {
          response: response,
          file: resultFiles[0],
          files: resultFiles
        };
        if (res.status === "success") {
          var _params$onResponseSuc;
          (_params$onResponseSuc = params.onResponseSuccess) === null || _params$onResponseSuc === void 0 ? void 0 : _params$onResponseSuc.call(params, result);
        } else if (res.status === "fail") {
          var _params$onResponseErr;
          (_params$onResponseErr = params.onResponseError) === null || _params$onResponseErr === void 0 ? void 0 : _params$onResponseErr.call(params, result);
        }
        resolve({
          status: res.status,
          data: result
        });
      });
    } else {
      var _params$setXhrObject;
      var xhrReq = _common_js_upload_xhr["default"]({
        action: params.action,
        files: params.toUploadFiles,
        useMockProgress: params.useMockProgress,
        mockProgressDuration: params.mockProgressDuration,
        onError: function onError(p) {
          var _params$onResponseErr2;
          var r = handleError(_objectSpread(_objectSpread({}, p), {}, {
            formatResponse: params.formatResponse
          }));
          (_params$onResponseErr2 = params.onResponseError) === null || _params$onResponseErr2 === void 0 ? void 0 : _params$onResponseErr2.call(params, r);
          resolve({
            status: "fail",
            data: r
          });
        },
        onProgress: params.onResponseProgress,
        onSuccess: function onSuccess(p) {
          var formatResponse = params.formatResponse;
          var res = p.response;
          if (isFunction__default["default"](formatResponse)) {
            res = formatResponse(p.response, {
              file: p.file,
              currentFiles: p.files
            });
          }
          if (res.error) {
            var _params$onResponseErr3;
            var r = handleError(_objectSpread(_objectSpread({}, p), {}, {
              response: res
            }));
            (_params$onResponseErr3 = params.onResponseError) === null || _params$onResponseErr3 === void 0 ? void 0 : _params$onResponseErr3.call(params, r);
            resolve({
              status: "fail",
              data: r
            });
          } else {
            var _params$onResponseSuc2;
            p.file.response = res;
            p.files[0].response = res;
            var _r = handleSuccess(_objectSpread(_objectSpread({}, p), {}, {
              response: res
            }));
            (_params$onResponseSuc2 = params.onResponseSuccess) === null || _params$onResponseSuc2 === void 0 ? void 0 : _params$onResponseSuc2.call(params, _r);
            resolve({
              status: "success",
              data: _r
            });
          }
        },
        formatRequest: params.formatRequest,
        data: params.data,
        name: params.name,
        headers: params.headers,
        withCredentials: params.withCredentials,
        method: params.method
      });
      (_params$setXhrObject = params.setXhrObject) === null || _params$setXhrObject === void 0 ? void 0 : _params$setXhrObject.call(params, {
        files: params.toUploadFiles,
        xhrReq: xhrReq
      });
    }
  });
}
function upload(params) {
  var uploadAllFilesInOneRequest = params.uploadAllFilesInOneRequest,
    toUploadFiles = params.toUploadFiles,
    uploadedFiles = params.uploadedFiles,
    isBatchUpload = params.isBatchUpload;
  var thisUploadFiles = toUploadFiles.filter(function (t) {
    return !t.response || t.response && !t.response.error;
  });
  return new Promise(function (resolve) {
    if (uploadAllFilesInOneRequest || !params.multiple) {
      uploadOneRequest(params).then(function (r) {
        if (r.status === "success") {
          r.data.files = isBatchUpload || !params.multiple ? r.data.files : uploadedFiles.concat(r.data.files);
        }
        var failedFiles = r.status === "fail" ? r.data.files : [];
        resolve(_objectSpread(_objectSpread({}, r), {}, {
          failedFiles: failedFiles
        }));
      });
      return;
    }
    var list = thisUploadFiles.map(function (file) {
      return uploadOneRequest(_objectSpread(_objectSpread({}, params), {}, {
        toUploadFiles: [file]
      }));
    });
    Promise.all(list).then(function (arr) {
      var files = [];
      var failedFiles = [];
      arr.forEach(function (one) {
        if (one.status === "success") {
          files.push(one.data.files[0]);
        } else if (one.status === "fail") {
          failedFiles.push(one.data.files[0]);
        }
      });
      var tFiles = params.autoUpload ? uploadedFiles.concat(files) : uploadedFiles;
      var newFiles = isBatchUpload || !params.multiple ? files : tFiles;
      resolve({
        status: files.length ? "success" : "fail",
        data: {
          files: newFiles
        },
        failedFiles: failedFiles,
        list: arr
      });
    });
  });
}
function formatToUploadFile(files, format) {
  var status = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : void 0;
  var percent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  return files.map(function (fileRaw) {
    var file = fileRaw;
    if (isFunction__default["default"](format)) {
      file = format(fileRaw);
    }
    var uploadFile = _objectSpread({
      raw: fileRaw,
      lastModified: fileRaw.lastModified,
      name: fileRaw.name,
      size: fileRaw.size,
      type: fileRaw.type,
      percent: percent,
      status: status
    }, file);
    return uploadFile;
  });
}
function validateFile(params) {
  var files = params.files,
    uploadValue = params.uploadValue,
    max = params.max,
    allowUploadDuplicateFile = params.allowUploadDuplicateFile;
  return new Promise(function (resolve) {
    var tmpFiles = files.filter(function (file) {
      var sameNameFile = uploadValue.find(function (t) {
        return t.name === file.name;
      });
      return allowUploadDuplicateFile || !sameNameFile;
    });
    var hasSameNameFile = false;
    if (tmpFiles.length < files.length) {
      hasSameNameFile = true;
    }
    if (!tmpFiles.length) {
      var tFiles = formatToUploadFile(files, params.format, params.autoUpload ? "progress" : "waiting");
      resolve({
        hasSameNameFile: hasSameNameFile,
        file: tFiles === null || tFiles === void 0 ? void 0 : tFiles[0],
        files: tFiles,
        validateResult: {
          type: "FILTER_FILE_SAME_NAME"
        }
      });
      return;
    }
    var lengthOverLimit = false;
    if (max && tmpFiles.length && !params.isBatchUpload) {
      tmpFiles = tmpFiles.slice(0, max - uploadValue.length);
      if (tmpFiles.length !== files.length) {
        lengthOverLimit = true;
      }
    }
    var formattedFiles = formatToUploadFile(tmpFiles, params.format, params.autoUpload ? "progress" : "waiting");
    var allFileValidatePromise;
    if (params.beforeAllFilesUpload) {
      var _params$beforeAllFile;
      var r = (_params$beforeAllFile = params.beforeAllFilesUpload) === null || _params$beforeAllFile === void 0 ? void 0 : _params$beforeAllFile.call(params, formattedFiles);
      allFileValidatePromise = r instanceof Promise ? r : new Promise(function (resolve2) {
        return resolve2(r);
      });
    }
    var promiseList = formattedFiles.map(function (file) {
      return new Promise(function (resolve2) {
        handleBeforeUpload(file, {
          beforeUpload: params.beforeUpload,
          sizeLimit: params.sizeLimit
        }).then(function (_ref) {
          var _ref2 = _slicedToArray__default["default"](_ref, 2),
            sizeResult = _ref2[0],
            customResult = _ref2[1];
          if (sizeResult) {
            resolve2({
              file: file,
              validateResult: {
                type: "FILE_OVER_SIZE_LIMIT",
                extra: sizeResult
              }
            });
          } else if (customResult === false) {
            resolve2({
              file: file,
              validateResult: {
                type: "CUSTOM_BEFORE_UPLOAD"
              }
            });
          }
          resolve2({
            file: file
          });
        });
      });
    });
    Promise.all([allFileValidatePromise].concat(promiseList)).then(function (results) {
      var _results = _toArray__default["default"](results),
        allFilesResult = _results[0],
        others = _results.slice(1);
      if (allFilesResult === false) {
        resolve({
          lengthOverLimit: lengthOverLimit,
          hasSameNameFile: hasSameNameFile,
          validateResult: {
            type: "BEFORE_ALL_FILES_UPLOAD"
          },
          files: formattedFiles
        });
      } else {
        resolve({
          lengthOverLimit: lengthOverLimit,
          hasSameNameFile: hasSameNameFile,
          fileValidateList: others,
          files: formattedFiles
        });
      }
    });
  });
}
function getFilesAndErrors(fileValidateList, getError) {
  var sizeLimitErrors = [];
  var beforeUploadErrorFiles = [];
  var toFiles = [];
  fileValidateList.forEach(function (oneFile) {
    var _oneFile$validateResu, _oneFile$validateResu2;
    if (((_oneFile$validateResu = oneFile.validateResult) === null || _oneFile$validateResu === void 0 ? void 0 : _oneFile$validateResu.type) === "CUSTOM_BEFORE_UPLOAD") {
      beforeUploadErrorFiles.push(oneFile.file);
      return;
    }
    if (((_oneFile$validateResu2 = oneFile.validateResult) === null || _oneFile$validateResu2 === void 0 ? void 0 : _oneFile$validateResu2.type) === "FILE_OVER_SIZE_LIMIT") {
      if (!oneFile.file.response) {
        oneFile.file.response = {};
      }
      oneFile.file.response.error = oneFile.file.response.error || getError(oneFile.validateResult.extra);
      sizeLimitErrors.push(oneFile);
      return;
    }
    toFiles.push(oneFile.file);
  });
  return {
    sizeLimitErrors: sizeLimitErrors,
    beforeUploadErrorFiles: beforeUploadErrorFiles,
    toFiles: toFiles
  };
}
function getTriggerTextField(p) {
  if (p.isBatchUpload && p.status) return "reupload";
  if (p.status === "fail") return "reupload";
  if (p.status === "progress") return "uploading";
  if (p.status === "success" || !p.autoUpload && p.status === "waiting") {
    return p.multiple ? "continueUpload" : "reupload";
  }
  return "fileInput";
}
function getDisplayFiles(params) {
  var multiple = params.multiple,
    uploadValue = params.uploadValue,
    toUploadFiles = params.toUploadFiles,
    autoUpload = params.autoUpload;
  var waitingUploadFiles = autoUpload ? toUploadFiles : toUploadFiles.filter(function (file) {
    return file.status !== "success";
  });
  if (multiple && !params.isBatchUpload) {
    if (!autoUpload) return uploadValue;
    return (waitingUploadFiles.length ? uploadValue.concat(waitingUploadFiles) : uploadValue) || [];
  }
  return (waitingUploadFiles.length ? waitingUploadFiles : uploadValue) || [];
}

exports.formatToUploadFile = formatToUploadFile;
exports.getDisplayFiles = getDisplayFiles;
exports.getFilesAndErrors = getFilesAndErrors;
exports.getTriggerTextField = getTriggerTextField;
exports.handleBeforeUpload = handleBeforeUpload;
exports.handleError = handleError;
exports.handleRequestMethodResponse = handleRequestMethodResponse;
exports.handleSuccess = handleSuccess;
exports.upload = upload;
exports.uploadOneRequest = uploadOneRequest;
exports.validateFile = validateFile;
//# sourceMappingURL=main.js.map
