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

'use strict';

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

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var VueCompositionAPI = require('@vue/composition-api');
var merge = require('lodash/merge');
var _common_js_upload_main = require('../../_common/js/upload/main.js');
var _common_js_upload_utils = require('../../_common/js/upload/utils.js');
var hooks_useVModel = require('../../hooks/useVModel.js');
var configProvider_useConfig = require('../../config-provider/useConfig.js');
require('@babel/runtime/helpers/toArray');
require('lodash/isFunction');
require('lodash/isNumber');
require('../../_common/js/log/log.js');
require('../../_common/js/upload/xhr.js');
require('@babel/runtime/helpers/typeof');
require('lodash/kebabCase');
require('../../config-provider/context.js');
require('lodash/mergeWith');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('../../_chunks/dep-7c884501.js');
require('dayjs');

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

var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge);

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 useUpload(props, context) {
  var inputRef = VueCompositionAPI.ref();
  var _toRefs = VueCompositionAPI.toRefs(props),
    autoUpload = _toRefs.autoUpload,
    isBatchUpload = _toRefs.isBatchUpload,
    multiple = _toRefs.multiple,
    value = _toRefs.value,
    defaultValue = _toRefs.defaultValue,
    files = _toRefs.files,
    defaultFiles = _toRefs.defaultFiles;
  var _useConfig = configProvider_useConfig.useConfig("upload"),
    global = _useConfig.global,
    t = _useConfig.t,
    classPrefix = _useConfig.classPrefix;
  var _useVModel = hooks_useVModel["default"](value, defaultValue.value || defaultFiles.value, props.onChange, "change", "value", [{
      value: files,
      eventName: "change",
      propName: "files"
    }]),
    _useVModel2 = _slicedToArray__default["default"](_useVModel, 2),
    uploadValue = _useVModel2[0],
    setUploadValue = _useVModel2[1];
  var xhrReq = VueCompositionAPI.ref([]);
  var toUploadFiles = VueCompositionAPI.ref([]);
  var sizeOverLimitMessage = VueCompositionAPI.ref("");
  var localeConfig = VueCompositionAPI.computed(function () {
    return merge__default["default"]({}, global.value, props.locale);
  });
  var innerDisabled = VueCompositionAPI.computed(function () {
    return props.disabled;
  });
  var tipsClasses = "".concat(classPrefix.value, "-upload__tips ").concat(classPrefix.value, "-size-s");
  var errorClasses = [tipsClasses].concat("".concat(classPrefix.value, "-upload__tips-error"));
  var placeholderClass = "".concat(classPrefix.value, "-upload__placeholder");
  var triggerUploadText = VueCompositionAPI.computed(function () {
    var _uploadValue$value, _uploadValue$value$;
    var field = _common_js_upload_main.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];
  });
  var uploading = VueCompositionAPI.ref(false);
  var displayFiles = VueCompositionAPI.computed(function () {
    return _common_js_upload_main.getDisplayFiles({
      multiple: props.multiple,
      toUploadFiles: toUploadFiles.value,
      uploadValue: uploadValue.value,
      autoUpload: autoUpload.value,
      isBatchUpload: isBatchUpload.value
    });
  });
  var updateFilesProgress = function updateFilesProgress() {
    if (props.autoUpload) toUploadFiles.value = _toConsumableArray__default["default"](toUploadFiles.value);
  };
  var onResponseError = function onResponseError(p) {
    if (!p || !p.files || !p.files[0]) return;
    var response = p.response,
      event = p.event,
      files2 = p.files;
    if (props.multiple && !props.uploadAllFilesInOneRequest) {
      var _props$onOneFileFail;
      updateFilesProgress();
      var params = {
        e: event,
        file: files2 === null || files2 === void 0 ? void 0 : files2[0],
        currentFiles: files2,
        failedFiles: files2,
        response: 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]
      });
    }
  };
  var onResponseProgress = function onResponseProgress(p) {
    var _props$onProgress;
    updateFilesProgress();
    var params = {
      e: p.event,
      file: p.file,
      currentFiles: p.files,
      percent: p.percent,
      type: p.type,
      XMLHttpRequest: p.XMLHttpRequest
    };
    (_props$onProgress = props.onProgress) === null || _props$onProgress === void 0 ? void 0 : _props$onProgress.call(props, params);
    context.emit("progress", params);
  };
  var onResponseSuccess = function onResponseSuccess(p) {
    if (props.multiple && !props.uploadAllFilesInOneRequest) {
      var _props$onOneFileSucce;
      updateFilesProgress();
      var 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) {
    var limit = sizeLimitObj;
    return limit.message ? t(limit.message, {
      sizeLimit: limit.size
    }) : "".concat(t(localeConfig.value.sizeLimitMessage, {
      sizeLimit: limit.size
    }), " ").concat(limit.unit);
  }
  var handleNotAutoUpload = function handleNotAutoUpload(toFiles) {
    var tmpFiles = props.multiple && !isBatchUpload.value ? uploadValue.value.concat(toFiles) : toFiles;
    if (!tmpFiles.length) return;
    if (["image", "image-flow"].includes(props.theme)) {
      var list = tmpFiles.map(function (file) {
        return new Promise(function (resolve) {
          _common_js_upload_utils.getFileUrlByFileRaw(file.raw).then(function (url) {
            resolve(_objectSpread(_objectSpread({}, file), {}, {
              url: file.url || url
            }));
          });
        });
      });
      Promise.all(list).then(function (files2) {
        setUploadValue(files2, {
          trigger: "add",
          index: uploadValue.value.length,
          file: toFiles[0],
          files: toFiles
        });
      });
    } else {
      setUploadValue(tmpFiles, {
        trigger: "add",
        index: uploadValue.value.length,
        file: toFiles[0],
        files: toFiles
      });
    }
    toUploadFiles.value = [];
  };
  var onFileChange = function onFileChange(files2) {
    var _props$onSelectChange;
    if (innerDisabled.value) return;
    var params = {
      currentSelectedFiles: _common_js_upload_main.formatToUploadFile(_toConsumableArray__default["default"](files2), props.format)
    };
    (_props$onSelectChange = props.onSelectChange) === null || _props$onSelectChange === void 0 ? void 0 : _props$onSelectChange.call(props, _toConsumableArray__default["default"](files2), params);
    context.emit("select-change", _toConsumableArray__default["default"](files2), params);
    _common_js_upload_main.validateFile({
      uploadValue: uploadValue.value,
      files: _toConsumableArray__default["default"](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(function (args) {
      var _args$validateResult;
      if (((_args$validateResult = args.validateResult) === null || _args$validateResult === void 0 ? void 0 : _args$validateResult.type) === "BEFORE_ALL_FILES_UPLOAD") {
        var _props$onValidate;
        var params2 = {
          type: "BEFORE_ALL_FILES_UPLOAD",
          files: args.files
        };
        (_props$onValidate = props.onValidate) === null || _props$onValidate === void 0 ? void 0 : _props$onValidate.call(props, params2);
        context.emit("validate", params2);
        return;
      }
      if (args.lengthOverLimit) {
        var _props$onValidate2;
        var _params = {
          type: "FILES_OVER_LENGTH_LIMIT",
          files: args.files
        };
        (_props$onValidate2 = props.onValidate) === null || _props$onValidate2 === void 0 ? void 0 : _props$onValidate2.call(props, _params);
        context.emit("validate", _params);
        if (!args.files.length) return;
      }
      if (args.hasSameNameFile) {
        var _props$onValidate3;
        var _params2 = {
          type: "FILTER_FILE_SAME_NAME",
          files: args.files
        };
        (_props$onValidate3 = props.onValidate) === null || _props$onValidate3 === void 0 ? void 0 : _props$onValidate3.call(props, _params2);
        context.emit("validate", _params2);
      }
      if (Array.isArray(args.fileValidateList)) {
        var _props$onWaitingUploa;
        var _getFilesAndErrors = _common_js_upload_main.getFilesAndErrors(args.fileValidateList, getSizeLimitError),
          sizeLimitErrors = _getFilesAndErrors.sizeLimitErrors,
          beforeUploadErrorFiles = _getFilesAndErrors.beforeUploadErrorFiles,
          toFiles = _getFilesAndErrors.toFiles;
        var 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$onValidate4;
          sizeOverLimitMessage.value = sizeLimitErrors[0].file.response.error;
          (_props$onValidate4 = props.onValidate) === null || _props$onValidate4 === void 0 ? void 0 : _props$onValidate4.call(props, {
            type: "FILE_OVER_SIZE_LIMIT",
            files: sizeLimitErrors.map(function (t2) {
              return t2.file;
            })
          });
          context.emit("validate", {
            type: "FILE_OVER_SIZE_LIMIT",
            files: sizeLimitErrors.map(function (t2) {
              return t2.file;
            })
          });
        } else {
          sizeOverLimitMessage.value = "";
          if (beforeUploadErrorFiles.length) {
            var _props$onValidate5;
            var _params3 = {
              type: "CUSTOM_BEFORE_UPLOAD",
              files: beforeUploadErrorFiles
            };
            (_props$onValidate5 = props.onValidate) === null || _props$onValidate5 === void 0 ? void 0 : _props$onValidate5.call(props, _params3);
            context.emit("validate", _params3);
          }
        }
        if (autoUpload.value) uploadFiles(tmpWaitingFiles);else handleNotAutoUpload(tmpWaitingFiles);
      }
    });
    inputRef.value.value = null;
  };
  var onNormalFileChange = function 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) {
    var notUploadedFiles = uploadValue.value.filter(function (t2) {
      return t2.status !== "success";
    });
    var files2 = autoUpload.value ? toFiles || toUploadFiles.value : notUploadedFiles;
    if (!files2 || !files2.length) return;
    uploading.value = true;
    xhrReq.value = [];
    _common_js_upload_main.upload({
      action: props.action,
      headers: props.headers,
      method: props.method,
      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,
      mockProgressDuration: props.mockProgressDuration,
      requestMethod: props.requestMethod,
      formatRequest: props.formatRequest,
      formatResponse: props.formatResponse,
      onResponseProgress: onResponseProgress,
      onResponseSuccess: onResponseSuccess,
      onResponseError: onResponseError,
      setXhrObject: function setXhrObject(xhr) {
        var _xhr$files$;
        if ((_xhr$files$ = xhr.files[0]) !== null && _xhr$files$ !== void 0 && _xhr$files$.raw && xhrReq.value.find(function (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(function (_ref) {
      var status = _ref.status,
        data = _ref.data,
        list = _ref.list,
        failedFiles = _ref.failedFiles;
      uploading.value = false;
      if (status === "success") {
        var _props$onSuccess;
        if (props.autoUpload) {
          setUploadValue(_toConsumableArray__default["default"](data.files), {
            trigger: "add",
            file: data.files[0]
          });
        }
        xhrReq.value = [];
        var params = {
          fileList: data.files,
          currentFiles: files2,
          file: files2[0],
          results: list === null || list === void 0 ? void 0 : list.map(function (t2) {
            return t2.data;
          }),
          response: data.response || list.map(function (t2) {
            return t2.data.response;
          }),
          XMLHttpRequest: data.XMLHttpRequest
        };
        (_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;
        var _params4 = {
          e: data.event,
          file: failedFiles[0],
          failedFiles: failedFiles,
          currentFiles: files2,
          response: data.response,
          XMLHttpRequest: data.XMLHttpRequest
        };
        (_props$onFail = props.onFail) === null || _props$onFail === void 0 ? void 0 : _props$onFail.call(props, _params4);
        context.emit("fail", _params4);
      }
      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"
        });
      }
    });
  }
  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);
    var 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(_toConsumableArray__default["default"](uploadValue.value), changePrams);
    } else {
      if (p.index < uploadValue.value.length) {
        uploadValue.value.splice(p.index, 1);
        setUploadValue(_toConsumableArray__default["default"](uploadValue.value), changePrams);
      } else {
        var _props$onWaitingUploa4;
        toUploadFiles.value.splice(p.index - uploadValue.value.length, 1);
        toUploadFiles.value = _toConsumableArray__default["default"](toUploadFiles.value);
        (_props$onWaitingUploa4 = props.onWaitingUploadFilesChange) === null || _props$onWaitingUploa4 === void 0 ? void 0 : _props$onWaitingUploa4.call(props, {
          files: _toConsumableArray__default["default"](toUploadFiles.value),
          trigger: "remove"
        });
        context.emit("waiting-upload-files-change", {
          files: _toConsumableArray__default["default"](toUploadFiles.value),
          trigger: "remove"
        });
      }
    }
    (_props$onRemove = props.onRemove) === null || _props$onRemove === void 0 ? void 0 : _props$onRemove.call(props, p);
    context.emit("remove", p);
  }
  var triggerUpload = function triggerUpload(e) {
    var _e$stopPropagation;
    if (innerDisabled.value || !inputRef.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();
  };
  var innerCancelUpload = function innerCancelUpload() {
    var _props$onCancelUpload;
    (_props$onCancelUpload = props.onCancelUpload) === null || _props$onCancelUpload === void 0 ? void 0 : _props$onCancelUpload.call(props);
    context.emit("cancel-upload");
  };
  var cancelUpload = function 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(function (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(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          status: "waiting"
        });
      });
    } else {
      setUploadValue(uploadValue.value.map(function (item) {
        if (item.status !== "success") return _objectSpread(_objectSpread({}, item), {}, {
          status: "waiting"
        });
        return item;
      }), {
        trigger: "abort"
      });
    }
    if (context2 !== null && context2 !== void 0 && context2.file && !autoUpload.value) onInnerRemove === null || onInnerRemove === void 0 ? void 0 : onInnerRemove({
      file: context2.file,
      e: context2.e,
      index: 0
    });
    innerCancelUpload();
  };
  var onInnerPreview = function 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: t,
    localeConfig: localeConfig,
    classPrefix: classPrefix,
    triggerUploadText: triggerUploadText,
    toUploadFiles: toUploadFiles,
    uploadValue: uploadValue,
    displayFiles: displayFiles,
    sizeOverLimitMessage: sizeOverLimitMessage,
    uploading: uploading,
    tipsClasses: tipsClasses,
    errorClasses: errorClasses,
    placeholderClass: placeholderClass,
    inputRef: inputRef,
    innerDisabled: innerDisabled,
    xhrReq: xhrReq,
    uploadFiles: uploadFiles,
    onFileChange: onFileChange,
    onNormalFileChange: onNormalFileChange,
    onDragFileChange: onDragFileChange,
    onInnerRemove: onInnerRemove,
    triggerUpload: triggerUpload,
    cancelUpload: cancelUpload,
    onInnerPreview: onInnerPreview,
    innerCancelUpload: innerCancelUpload
  };
}

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