/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

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

var VueCompositionAPI = require('@vue/composition-api');
var merge = require('lodash/merge');
var defineProperty838e4192 = require('../../../chunks/defineProperty-838e4192.js');
var log = require('../../../chunks/log.js');
var utils = require('../../../chunks/utils2.js');
var hooks_useVmodel = require('../../../hooks/use-vmodel.js');
var components_configProvider_useConfig = require('../../config-provider/useConfig.js');
require('../../../chunks/_commonjsHelpers-2e6815bd.js');
require('lodash/kebabCase');
require('../../config-provider/context.js');
require('lodash');
require('../../../chunks/zh_CN.js');

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

var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge);

function ownKeys$1(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$1(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? ownKeys$1(Object(source), true).forEach(function (key) {
      defineProperty838e4192._defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function xhr(_ref) {
  var _files$;
  var {
    method = "POST",
    action,
    withCredentials = false,
    headers = {},
    data = {},
    file,
    files = [],
    name = "file",
    useMockProgress = true,
    formatRequest,
    onError,
    onProgress,
    onSuccess
  } = _ref;
  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(() => {
      timer1 = setInterval(() => {
        if (percent + 10 < 100) {
          percent = Math.max(percent + 10, percent);
          if (files[0] && percent !== files[0].percent) {
            files[0].percent = percent;
            onProgress({
              percent,
              file: file || innerFiles[0],
              files: innerFiles.map(file2 => _objectSpread$1(_objectSpread$1({}, file2), {}, {
                percent
              })),
              type: "mock"
            });
          }
        } else {
          clearInterval(timer1);
        }
      }, 300);
      clearTimeout(timer22);
    }, 300);
  }
  var requestData = {};
  if (data) {
    var extraData = typeof data === "function" ? data(file) : data;
    Object.assign(requestData, extraData);
  }
  innerFiles.forEach((file2, index) => {
    var fileField = innerFiles.length > 1 ? "".concat(name, "[").concat(index, "]") : name;
    requestData[fileField] = file2.raw;
    requestData[name] = file2.raw;
  });
  if (formatRequest) requestData = formatRequest(requestData);
  var formData = new FormData();
  Object.keys(requestData).forEach(key => {
    formData.append(key, requestData[key]);
  });
  xhr2.open(method, action, true);
  Object.keys(headers).forEach(key => {
    xhr2.setRequestHeader(key, headers[key]);
  });
  xhr2.onerror = event => {
    onError({
      event,
      file,
      files: innerFiles
    });
    clearInterval(timer1);
    clearTimeout(timer2);
  };
  if (xhr2.upload) {
    xhr2.upload.onprogress = 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(item => _objectSpread$1(_objectSpread$1({}, item), {}, {
          percent
        }));
        onProgress({
          event,
          percent,
          file: file || progressFiles[0],
          files: progressFiles,
          type: "real"
        });
      }
    };
  }
  xhr2.onload = event => {
    var response = {};
    var isFail = xhr2.status < 200 || xhr2.status >= 300;
    if (isFail) {
      return onError({
        event,
        file,
        files: innerFiles,
        response
      });
    }
    var text = xhr2.responseText || xhr2.response;
    try {
      response = JSON.parse(text);
    } catch (e) {
      response = text;
    }
    clearInterval(timer1);
    clearTimeout(timer2);
    innerFiles.forEach(file2 => {
      var _response;
      file2.percent = 100;
      file2.status = "success";
      file2.uploadTime = ((_response = response) === null || _response === void 0 ? void 0 : _response.uploadTime) || utils.getCurrentDate();
    });
    onSuccess({
      event,
      file: file || innerFiles[0],
      files: [...innerFiles],
      response
    });
  };
  xhr2.send(formData);
  return xhr2;
}

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), true).forEach(function (key) {
      defineProperty838e4192._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 handleBeforeUpload(file, params) {
  var {
    sizeLimit,
    beforeUpload
  } = params;
  var sizePromise = new Promise(resolve => {
    var result = null;
    if (sizeLimit) {
      var sizeLimitObj = typeof sizeLimit === "number" ? {
        size: sizeLimit,
        unit: "KB"
      } : sizeLimit;
      var limit = utils.isOverSizeLimit(file.size, sizeLimitObj.size, sizeLimitObj.unit);
      if (limit) result = sizeLimitObj;
    }
    resolve(result);
  });
  var promiseList = [sizePromise, void 0];
  if (typeof beforeUpload === "function") {
    var r = beforeUpload(file);
    var p = r instanceof Promise ? r : new Promise(resolve => resolve(r));
    promiseList[1] = p;
  }
  return new Promise(resolve => {
    Promise.all(promiseList).then(r2 => {
      resolve(r2);
    });
  });
}
function handleError(options) {
  var {
    event,
    files,
    response,
    formatResponse
  } = options;
  files.forEach(file => {
    file.status = "fail";
  });
  var res = response;
  if (typeof formatResponse === "function") res = formatResponse(response, {
    file: files[0],
    currentFiles: files
  });
  return {
    response: res,
    event,
    files
  };
}
function handleSuccess(params) {
  var {
    event,
    files,
    response
  } = params;
  if ((files === null || files === void 0 ? void 0 : files.length) <= 0) log.log.error("Upload", "Empty File in Success Callback");
  files.forEach(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,
    files
  };
}
function handleRequestMethodResponse(res) {
  if (!res) {
    log.log.error("Upload", "`requestMethodResponse` is required.");
    return false;
  }
  if (!res.status) {
    log.log.error("Upload", "`requestMethodResponse.status` is missing, which value only can be `success` or `fail`");
    return false;
  }
  if (!["success", "fail"].includes(res.status)) {
    log.log.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)) log.log.warn("Upload", "`requestMethodResponse.response.url` is required as `status` is `success`");
  return true;
}
function uploadOneRequest(params) {
  var {
    action,
    toUploadFiles,
    requestMethod
  } = params;
  return new Promise(resolve => {
    if (!action && !requestMethod) {
      log.log.error("Upload", "one of action and requestMethod must be exist.");
      resolve({});
      return;
    }
    if (!toUploadFiles || !toUploadFiles.length) {
      log.log.warn("Upload", "No files need to be uploaded");
      resolve({});
      return;
    }
    toUploadFiles.forEach(file => {
      file.status = "progress";
    });
    if (requestMethod) {
      requestMethod(params.multiple ? toUploadFiles : toUploadFiles[0]).then(res => {
        var _params$onResponseSuc, _params$onResponseErr;
        if (!handleRequestMethodResponse(res)) {
          resolve({});
          return;
        }
        var {
          response
        } = res;
        if (res.status === "fail") {
          response = response || {};
          response.error = res.error || response.error;
        }
        toUploadFiles.forEach(file => {
          file.status = res.status;
          file.response = response;
          file.url = response.url;
        });
        var result = {
          response,
          file: toUploadFiles[0],
          files: toUploadFiles
        };
        if (res.status === "success") (_params$onResponseSuc = params.onResponseSuccess) === null || _params$onResponseSuc === void 0 ? void 0 : _params$onResponseSuc.call(params, result);else if (res.status === "fail") (_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 = xhr({
        action: params.action,
        files: params.toUploadFiles,
        useMockProgress: params.useMockProgress,
        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: p => {
          var {
            formatResponse
          } = params;
          var res = p.response;
          if (typeof formatResponse === "function") {
            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
      });
    }
  });
}
function upload(params) {
  var {
    uploadAllFilesInOneRequest,
    toUploadFiles,
    uploadedFiles,
    isBatchUpload
  } = params;
  var thisUploadFiles = toUploadFiles.filter(t => !t.response || t.response && !t.response.error);
  return new Promise(resolve => {
    if (uploadAllFilesInOneRequest || !params.multiple) {
      uploadOneRequest(params).then(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
        }));
      });
      return;
    }
    var list = thisUploadFiles.map(file => uploadOneRequest(_objectSpread(_objectSpread({}, params), {}, {
      toUploadFiles: [file]
    })));
    Promise.all(list).then(arr => {
      var files = [];
      var failedFiles = [];
      arr.forEach(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,
        list: arr
      });
    });
  });
}
function formatToUploadFile(tmpFiles, format, autoUpload) {
  return tmpFiles.map(fileRaw => {
    var file = fileRaw;
    if (typeof format === "function") file = format(fileRaw);
    var uploadFile = _objectSpread({
      raw: fileRaw,
      lastModified: fileRaw.lastModified,
      name: fileRaw.name,
      size: fileRaw.size,
      type: fileRaw.type,
      percent: 0,
      status: autoUpload ? "progress" : "waiting"
    }, file);
    return uploadFile;
  });
}
function validateFile(params) {
  var {
    files,
    uploadValue,
    max,
    allowUploadDuplicateFile
  } = params;
  return new Promise(resolve => {
    var tmpFiles = files.filter(file => {
      var sameNameFile = uploadValue.find(t => 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);
      resolve({
        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);
    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(resolve2 => resolve2(r));
    }
    var promiseList = formattedFiles.map(file => new Promise(resolve2 => {
      handleBeforeUpload(file, {
        beforeUpload: params.beforeUpload,
        sizeLimit: params.sizeLimit
      }).then(_ref => {
        var [sizeResult, customResult] = _ref;
        if (sizeResult) resolve2({
          file,
          validateResult: {
            type: "FILE_OVER_SIZE_LIMIT",
            extra: sizeResult
          }
        });else if (customResult === false) resolve2({
          file,
          validateResult: {
            type: "CUSTOM_BEFORE_UPLOAD"
          }
        });
        resolve2({
          file
        });
      });
    }));
    Promise.all([allFileValidatePromise].concat(promiseList)).then(results => {
      var [allFilesResult, ...others] = results;
      if (allFilesResult === false) {
        resolve({
          lengthOverLimit,
          hasSameNameFile,
          validateResult: {
            type: "BEFORE_ALL_FILES_UPLOAD"
          },
          files: formattedFiles
        });
      } else {
        resolve({
          lengthOverLimit,
          hasSameNameFile,
          fileValidateList: others,
          files: formattedFiles
        });
      }
    });
  });
}
function getFilesAndErrors(fileValidateList, getError) {
  var sizeLimitErrors = [];
  var toFiles = [];
  fileValidateList.forEach(oneFile => {
    var _oneFile$validateResu, _oneFile$validateResu2;
    if (((_oneFile$validateResu = oneFile.validateResult) === null || _oneFile$validateResu === void 0 ? void 0 : _oneFile$validateResu.type) === "CUSTOM_BEFORE_UPLOAD") 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,
    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,
    uploadValue,
    toUploadFiles,
    autoUpload
  } = params;
  var waitingUploadFiles = autoUpload ? toUploadFiles : toUploadFiles.filter(file => file.status !== "success");
  if (multiple && !params.isBatchUpload) {
    if (!autoUpload) return uploadValue;
    return (waitingUploadFiles.length ? uploadValue.concat(waitingUploadFiles) : uploadValue) || [];
  }
  return (waitingUploadFiles.length ? waitingUploadFiles : uploadValue) || [];
}

function useUpload(props, context) {
  const inputRef = VueCompositionAPI.ref();
  const {
    autoUpload,
    isBatchUpload,
    multiple,
    value,
    defaultValue,
    files,
    defaultFiles
  } = VueCompositionAPI.toRefs(props);
  const {
    global,
    t,
    classPrefix
  } = components_configProvider_useConfig.useConfig("upload");
  const [uploadValue, setUploadValue] = hooks_useVmodel["default"](value, defaultValue.value || defaultFiles.value, props.onChange, "change", "value", [{
    value: files,
    eventName: "change",
    propName: "files"
  }]);
  const xhrReq = VueCompositionAPI.ref([]);
  const toUploadFiles = VueCompositionAPI.ref([]);
  const sizeOverLimitMessage = VueCompositionAPI.ref("");
  const localeConfig = VueCompositionAPI.computed(() => merge__default["default"]({}, global.value, props.locale));
  const innerDisabled = VueCompositionAPI.computed(() => props.disabled);
  const tipsClasses = `${classPrefix.value}-upload__tips ${classPrefix.value}-size-s`;
  const errorClasses = [tipsClasses].concat(`${classPrefix.value}-upload__tips-error`);
  const triggerUploadText = VueCompositionAPI.computed(() => {
    var _uploadValue$value, _uploadValue$value$;
    const field = getTriggerTextField({
      isBatchUpload: isBatchUpload.value,
      multiple: multiple.value,
      status: (_uploadValue$value = uploadValue.value) === null || _uploadValue$value === void 0 ? void 0 : (_uploadValue$value$ = _uploadValue$value[0]) === null || _uploadValue$value$ === void 0 ? void 0 : _uploadValue$value$.status,
      autoUpload: autoUpload.value
    });
    return localeConfig.value.triggerUploadText[field];
  });
  const uploading = VueCompositionAPI.ref(false);
  const displayFiles = VueCompositionAPI.computed(() => getDisplayFiles({
    multiple: props.multiple,
    toUploadFiles: toUploadFiles.value,
    uploadValue: uploadValue.value,
    autoUpload: autoUpload.value,
    isBatchUpload: isBatchUpload.value
  }));
  const updateFilesProgress = () => {
    if (props.autoUpload) toUploadFiles.value = [...toUploadFiles.value];
  };
  const onResponseError = p => {
    if (!p || !p.files || !p.files[0]) return;
    const {
      response,
      event,
      files: files2
    } = p;
    if (props.multiple && !props.uploadAllFilesInOneRequest) {
      var _props$onOneFileFail;
      updateFilesProgress();
      const params = {
        e: event,
        file: files2 === null || files2 === void 0 ? void 0 : files2[0],
        currentFiles: files2,
        failedFiles: files2,
        response
      };
      (_props$onOneFileFail = props.onOneFileFail) === null || _props$onOneFileFail === void 0 ? void 0 : _props$onOneFileFail.call(props, params);
      context.emit("one-file-fail", params);
    }
    if (!props.multiple || props.isBatchUpload) {
      setUploadValue([], {
        trigger: "progress-fail",
        e: p.event,
        file: p.files[0]
      });
    }
  };
  const onResponseProgress = p => {
    var _props$onProgress;
    updateFilesProgress();
    const params = {
      e: p.event,
      file: p.file,
      currentFiles: p.files,
      percent: p.percent,
      type: p.type
    };
    (_props$onProgress = props.onProgress) === null || _props$onProgress === void 0 ? void 0 : _props$onProgress.call(props, params);
    context.emit("progress", params);
  };
  const onResponseSuccess = p => {
    if (props.multiple && !props.uploadAllFilesInOneRequest) {
      var _props$onOneFileSucce;
      updateFilesProgress();
      const params = {
        e: p.event,
        file: p.files[0],
        response: p.response
      };
      (_props$onOneFileSucce = props.onOneFileSuccess) === null || _props$onOneFileSucce === void 0 ? void 0 : _props$onOneFileSucce.call(props, params);
      context.emit("one-file-success", params);
    }
  };
  function getSizeLimitError(sizeLimitObj) {
    const limit = sizeLimitObj;
    return limit.message ? t(limit.message, {
      sizeLimit: limit.size
    }) : `${t(localeConfig.value.sizeLimitMessage, {
      sizeLimit: limit.size
    })} ${limit.unit}`;
  }
  const handleNonAutoUpload = toFiles => {
    var _uploadValue$value$2;
    const tmpFiles = props.multiple && !(isBatchUpload.value && ((_uploadValue$value$2 = uploadValue.value[0]) === null || _uploadValue$value$2 === void 0 ? void 0 : _uploadValue$value$2.status) === "success") ? uploadValue.value.concat(toFiles) : toFiles;
    if (["image", "image-flow"].includes(props.theme)) {
      const list = tmpFiles.map(file => new Promise(resolve => {
        utils.getFileUrlByFileRaw(file.raw).then(url => {
          resolve({
            ...file,
            url
          });
        });
      }));
      Promise.all(list).then(files2 => {
        setUploadValue(files2, {
          trigger: "add",
          index: uploadValue.value.length,
          file: files2[0]
        });
      });
    } else {
      setUploadValue(tmpFiles, {
        trigger: "add",
        index: uploadValue.value.length,
        file: tmpFiles[0]
      });
    }
    toUploadFiles.value = [];
  };
  const onFileChange = files2 => {
    var _props$onSelectChange;
    if (innerDisabled.value) return;
    (_props$onSelectChange = props.onSelectChange) === null || _props$onSelectChange === void 0 ? void 0 : _props$onSelectChange.call(props, [...files2], {
      currentSelectedFiles: toUploadFiles
    });
    context.emit("select-change", [...files2], {
      currentSelectedFiles: toUploadFiles
    });
    validateFile({
      uploadValue: uploadValue.value,
      files: [...files2],
      allowUploadDuplicateFile: props.allowUploadDuplicateFile,
      max: props.max,
      sizeLimit: props.sizeLimit,
      isBatchUpload: isBatchUpload.value,
      autoUpload: autoUpload.value,
      format: props.format,
      beforeUpload: props.beforeUpload,
      beforeAllFilesUpload: props.beforeAllFilesUpload
    }).then(args => {
      var _args$validateResult;
      if (((_args$validateResult = args.validateResult) === null || _args$validateResult === void 0 ? void 0 : _args$validateResult.type) === "BEFORE_ALL_FILES_UPLOAD") return;
      if (args.lengthOverLimit) {
        var _props$onValidate;
        (_props$onValidate = props.onValidate) === null || _props$onValidate === void 0 ? void 0 : _props$onValidate.call(props, {
          type: "FILES_OVER_LENGTH_LIMIT",
          files: args.files
        });
        context.emit("validate", {
          type: "FILES_OVER_LENGTH_LIMIT",
          files: args.files
        });
      }
      if (args.hasSameNameFile) {
        var _props$onValidate2;
        (_props$onValidate2 = props.onValidate) === null || _props$onValidate2 === void 0 ? void 0 : _props$onValidate2.call(props, {
          type: "FILTER_FILE_SAME_NAME",
          files: args.files
        });
        context.emit("validate", {
          type: "FILTER_FILE_SAME_NAME",
          files: args.files
        });
      }
      if (Array.isArray(args.fileValidateList)) {
        var _props$onWaitingUploa;
        const {
          sizeLimitErrors,
          toFiles
        } = getFilesAndErrors(args.fileValidateList, getSizeLimitError);
        const tmpWaitingFiles = autoUpload.value ? toFiles : toUploadFiles.value.concat(toFiles);
        toUploadFiles.value = tmpWaitingFiles;
        (_props$onWaitingUploa = props.onWaitingUploadFilesChange) === null || _props$onWaitingUploa === void 0 ? void 0 : _props$onWaitingUploa.call(props, {
          files: tmpWaitingFiles,
          trigger: "validate"
        });
        context.emit("waiting-upload-files-change", {
          files: tmpWaitingFiles,
          trigger: "validate"
        });
        if (sizeLimitErrors[0]) {
          var _props$onValidate3;
          sizeOverLimitMessage.value = sizeLimitErrors[0].file.response.error;
          (_props$onValidate3 = props.onValidate) === null || _props$onValidate3 === void 0 ? void 0 : _props$onValidate3.call(props, {
            type: "FILE_OVER_SIZE_LIMIT",
            files: sizeLimitErrors.map(t2 => t2.file)
          });
          context.emit("validate", {
            type: "FILE_OVER_SIZE_LIMIT",
            files: sizeLimitErrors.map(t2 => t2.file)
          });
        } else {
          sizeOverLimitMessage.value = "";
        }
        if (autoUpload.value) uploadFiles(tmpWaitingFiles);else handleNonAutoUpload(tmpWaitingFiles);
      }
    });
    inputRef.value.value = null;
  };
  const onNormalFileChange = e => {
    onFileChange === null || onFileChange === void 0 ? void 0 : onFileChange(e.target.files);
  };
  function onDragFileChange(e) {
    onFileChange === null || onFileChange === void 0 ? void 0 : onFileChange(e.dataTransfer.files);
  }
  function uploadFiles(toFiles) {
    const notUploadedFiles = uploadValue.value.filter(t2 => t2.status !== "success");
    const files2 = autoUpload.value ? toFiles || toUploadFiles.value : notUploadedFiles;
    if (!files2 || !files2.length) return;
    uploading.value = true;
    xhrReq.value = [];
    upload({
      action: props.action,
      headers: props.headers,
      name: props.name,
      withCredentials: props.withCredentials,
      uploadedFiles: uploadValue.value,
      toUploadFiles: files2,
      multiple: props.multiple,
      isBatchUpload: isBatchUpload.value,
      autoUpload: props.autoUpload,
      uploadAllFilesInOneRequest: props.uploadAllFilesInOneRequest,
      useMockProgress: props.useMockProgress,
      data: props.data,
      requestMethod: props.requestMethod,
      formatRequest: props.formatRequest,
      formatResponse: props.formatResponse,
      onResponseProgress,
      onResponseSuccess,
      onResponseError,
      setXhrObject: xhr => {
        var _xhr$files$;
        if ((_xhr$files$ = xhr.files[0]) !== null && _xhr$files$ !== void 0 && _xhr$files$.raw && xhrReq.value.find(item => {
          var _item$files$;
          return ((_item$files$ = item.files[0]) === null || _item$files$ === void 0 ? void 0 : _item$files$.raw) === xhr.files[0].raw;
        })) return;
        xhrReq.value = xhrReq.value.concat(xhr);
      }
    }).then(_ref => {
      let {
        status,
        data,
        list,
        failedFiles
      } = _ref;
      uploading.value = false;
      if (status === "success") {
        var _props$onSuccess;
        if (props.autoUpload) {
          setUploadValue([...data.files], {
            trigger: "add",
            file: data.files[0]
          });
        }
        xhrReq.value = [];
        const params = {
          fileList: data.files,
          currentFiles: files2,
          file: files2[0],
          results: list === null || list === void 0 ? void 0 : list.map(t2 => t2.data),
          response: data.response || list.map(t2 => t2.data.response)
        };
        (_props$onSuccess = props.onSuccess) === null || _props$onSuccess === void 0 ? void 0 : _props$onSuccess.call(props, params);
        context.emit("success", params);
      } else if (failedFiles !== null && failedFiles !== void 0 && failedFiles[0]) {
        var _props$onFail;
        const params = {
          e: data.event,
          file: failedFiles[0],
          failedFiles,
          currentFiles: files2,
          response: data.response
        };
        (_props$onFail = props.onFail) === null || _props$onFail === void 0 ? void 0 : _props$onFail.call(props, params);
        context.emit("fail", params);
      }
      if (autoUpload.value) {
        var _props$onWaitingUploa2;
        toUploadFiles.value = failedFiles;
        (_props$onWaitingUploa2 = props.onWaitingUploadFilesChange) === null || _props$onWaitingUploa2 === void 0 ? void 0 : _props$onWaitingUploa2.call(props, {
          files: failedFiles,
          trigger: "uploaded"
        });
      }
    }, p => {
      onResponseError(p);
      uploading.value = false;
    });
  }
  function onInnerRemove(p) {
    var _p$e$stopPropagation, _p$e, _props$onRemove;
    sizeOverLimitMessage.value = "";
    (_p$e$stopPropagation = (_p$e = p.e).stopPropagation) === null || _p$e$stopPropagation === void 0 ? void 0 : _p$e$stopPropagation.call(_p$e);
    const changePrams = {
      e: p.e,
      trigger: "remove",
      index: p.index,
      file: p.file
    };
    if (props.isBatchUpload || !props.multiple) {
      var _props$onWaitingUploa3;
      toUploadFiles.value = [];
      (_props$onWaitingUploa3 = props.onWaitingUploadFilesChange) === null || _props$onWaitingUploa3 === void 0 ? void 0 : _props$onWaitingUploa3.call(props, {
        files: [],
        trigger: "remove"
      });
      context.emit("waiting-upload-files-change", {
        files: [],
        trigger: "remove"
      });
      setUploadValue([], changePrams);
    } else if (!props.autoUpload) {
      uploadValue.value.splice(p.index, 1);
      setUploadValue([...uploadValue.value], changePrams);
    } else {
      if (p.index < uploadValue.value.length) {
        uploadValue.value.splice(p.index, 1);
        setUploadValue([...uploadValue.value], changePrams);
      } else {
        var _props$onWaitingUploa4;
        toUploadFiles.value.splice(p.index - uploadValue.value.length, 1);
        toUploadFiles.value = [...toUploadFiles.value];
        (_props$onWaitingUploa4 = props.onWaitingUploadFilesChange) === null || _props$onWaitingUploa4 === void 0 ? void 0 : _props$onWaitingUploa4.call(props, {
          files: [...toUploadFiles.value],
          trigger: "remove"
        });
        context.emit("waiting-upload-files-change", {
          files: [...toUploadFiles.value],
          trigger: "remove"
        });
      }
    }
    (_props$onRemove = props.onRemove) === null || _props$onRemove === void 0 ? void 0 : _props$onRemove.call(props, p);
    context.emit("remove", p);
  }
  const triggerUpload = e => {
    var _e$stopPropagation;
    if (innerDisabled.value) return;
    e === null || e === void 0 ? void 0 : (_e$stopPropagation = e.stopPropagation) === null || _e$stopPropagation === void 0 ? void 0 : _e$stopPropagation.call(e);
    inputRef.value.click();
  };
  const cancelUpload = context2 => {
    var _context2$e, _context2$e$stopPropa, _xhrReq$value;
    (_context2$e = context2.e) === null || _context2$e === void 0 ? void 0 : (_context2$e$stopPropa = _context2$e.stopPropagation) === null || _context2$e$stopPropa === void 0 ? void 0 : _context2$e$stopPropa.call(_context2$e);
    (_xhrReq$value = xhrReq.value) === null || _xhrReq$value === void 0 ? void 0 : _xhrReq$value.forEach(item => {
      var _item$xhrReq;
      (_item$xhrReq = item.xhrReq) === null || _item$xhrReq === void 0 ? void 0 : _item$xhrReq.abort();
    });
    uploading.value = false;
    if (autoUpload.value) {
      toUploadFiles.value = toUploadFiles.value.map(item => ({
        ...item,
        status: "waiting"
      }));
    } else {
      setUploadValue(uploadValue.value.map(item => {
        if (item.status !== "success") return {
          ...item,
          status: "waiting"
        };
        return item;
      }), {
        trigger: "abort"
      });
    }
    if (context2 !== null && context2 !== void 0 && context2.file) onInnerRemove === null || onInnerRemove === void 0 ? void 0 : onInnerRemove({
      file: context2.file,
      e: context2.e,
      index: 0
    });
  };
  const onInnerPreview = p => {
    var _props$onPreview;
    (_props$onPreview = props.onPreview) === null || _props$onPreview === void 0 ? void 0 : _props$onPreview.call(props, p);
    context.emit("preview", p);
  };
  return {
    t,
    localeConfig,
    classPrefix,
    triggerUploadText,
    toUploadFiles,
    uploadValue,
    displayFiles,
    sizeOverLimitMessage,
    uploading,
    tipsClasses,
    errorClasses,
    inputRef,
    innerDisabled,
    xhrReq,
    uploadFiles,
    onFileChange,
    onNormalFileChange,
    onDragFileChange,
    onInnerRemove,
    triggerUpload,
    cancelUpload,
    onInnerPreview
  };
}

exports["default"] = useUpload;
//# sourceMappingURL=use-upload.js.map
