'use strict';

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

var vue = require('vue');
require('../../../utils/index.cjs');
require('../../../locale/index.cjs');
require('../../../hooks/index.cjs');
require('../../../vue-components/index.cjs');
require('../../locale-provider/index.cjs');
var useConfigInject = require('../../config-provider/src/hooks/useConfigInject.cjs');
require('../../config-provider/index.cjs');
require('../../form/index.cjs');
var index = require('../style/index.cjs');
var index$2 = require('./UploadList/index.cjs');
var _interface = require('./interface.cjs');
var utils = require('./utils.cjs');
var initDefaultProps = require('../../../utils/vue/initDefaultProps.cjs');
var FormItemContext = require('../../form/src/FormItemContext.cjs');
var disabledContext = require('../../config-provider/src/context/disabledContext.cjs');
var index$1 = require('../../../hooks/use-merged-state/index.cjs');
var log = require('../../../utils/log.cjs');
var useLocaleReceiver = require('../../locale-provider/src/useLocaleReceiver.cjs');
var en_US = require('../../../locale/lang/en_US.cjs');
var _class = require('../../../utils/dom/class.cjs');
var Upload = require('../../../vue-components/vc-upload/src/Upload.cjs');
var props = require('../../../utils/vue/props.cjs');

const LIST_IGNORE = `__LIST_IGNORE_${Date.now()}__`;
var AUpload = /* @__PURE__ */ vue.defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: "AUpload",
  inheritAttrs: false,
  props: initDefaultProps.initDefaultProps(_interface.uploadProps(), {
    type: "select",
    multiple: false,
    action: "",
    data: {},
    accept: "",
    showUploadList: true,
    listType: "text",
    // or picture
    supportServerRender: true
  }),
  setup(props$1, {
    slots,
    attrs,
    expose
  }) {
    const formItemContext = FormItemContext.useInjectFormItemContext();
    const {
      prefixCls,
      direction,
      disabled
    } = useConfigInject.default("upload", props$1);
    const [wrapSSR, hashId] = index.default(prefixCls);
    const disabledContext$1 = disabledContext.useInjectDisabled();
    const mergedDisabled = vue.computed(() => {
      var _a;
      return (_a = disabled.value) != null ? _a : disabledContext$1.value;
    });
    const [mergedFileList, setMergedFileList] = index$1.useMergedState(props$1.defaultFileList || [], {
      value: vue.toRef(props$1, "fileList"),
      postState: (list) => {
        const timestamp = Date.now();
        return (list != null ? list : []).map((file, index) => {
          if (!file.uid && !Object.isFrozen(file))
            file.uid = `__AUTO__${timestamp}_${index}__`;
          return file;
        });
      }
    });
    const dragState = vue.ref("drop");
    const upload = vue.ref(null);
    vue.onMounted(() => {
      log.devWarning(props$1.fileList !== void 0 || attrs.value === void 0, "Upload", "`value` is not a valid prop, do you mean `fileList`?");
      log.devWarning(props$1.transformFile === void 0, "Upload", "`transformFile` is deprecated. Please use `beforeUpload` directly.");
      log.devWarning(props$1.remove === void 0, "Upload", "`remove` props is deprecated. Please use `remove` event.");
    });
    const onInternalChange = (file, changedFileList, event) => {
      var _a, _b;
      let cloneList = [...changedFileList];
      if (props$1.maxCount === 1)
        cloneList = cloneList.slice(-1);
      else if (props$1.maxCount)
        cloneList = cloneList.slice(0, props$1.maxCount);
      setMergedFileList(cloneList);
      const changeInfo = {
        file,
        fileList: cloneList
      };
      if (event)
        changeInfo.event = event;
      (_a = props$1["onUpdate:fileList"]) == null ? void 0 : _a.call(props$1, changeInfo.fileList);
      (_b = props$1.onChange) == null ? void 0 : _b.call(props$1, changeInfo);
      formItemContext.onFieldChange();
    };
    const mergedBeforeUpload = async (file, fileListArgs) => {
      const {
        beforeUpload,
        transformFile
      } = props$1;
      let parsedFile = file;
      if (beforeUpload) {
        const result = await beforeUpload(file, fileListArgs);
        if (result === false)
          return false;
        delete file[LIST_IGNORE];
        if (result === LIST_IGNORE) {
          Object.defineProperty(file, LIST_IGNORE, {
            value: true,
            configurable: true
          });
          return false;
        }
        if (typeof result === "object" && result)
          parsedFile = result;
      }
      if (transformFile)
        parsedFile = await transformFile(parsedFile);
      return parsedFile;
    };
    const onBatchStart = (batchFileInfoList) => {
      const filteredFileInfoList = batchFileInfoList.filter((info) => !info.file[LIST_IGNORE]);
      if (!filteredFileInfoList.length)
        return;
      const objectFileList = filteredFileInfoList.map((info) => utils.file2Obj(info.file));
      let newFileList = [...mergedFileList.value];
      objectFileList.forEach((fileObj) => {
        newFileList = utils.updateFileList(fileObj, newFileList);
      });
      objectFileList.forEach((fileObj, index) => {
        let triggerFileObj = fileObj;
        if (!filteredFileInfoList[index].parsedFile) {
          const {
            originFileObj
          } = fileObj;
          let clone;
          try {
            clone = new File([originFileObj], originFileObj.name, {
              type: originFileObj.type
            });
          } catch (e) {
            clone = new Blob([originFileObj], {
              type: originFileObj.type
            });
            clone.name = originFileObj.name;
            clone.lastModifiedDate = /* @__PURE__ */ new Date();
            clone.lastModified = (/* @__PURE__ */ new Date()).getTime();
          }
          clone.uid = fileObj.uid;
          triggerFileObj = clone;
        } else {
          fileObj.status = "uploading";
        }
        onInternalChange(triggerFileObj, newFileList);
      });
    };
    const onSuccess = (response, file, xhr) => {
      try {
        if (typeof response === "string")
          response = JSON.parse(response);
      } catch (e) {
      }
      if (!utils.getFileItem(file, mergedFileList.value))
        return;
      const targetItem = utils.file2Obj(file);
      targetItem.status = "done";
      targetItem.percent = 100;
      targetItem.response = response;
      targetItem.xhr = xhr;
      const nextFileList = utils.updateFileList(targetItem, mergedFileList.value);
      onInternalChange(targetItem, nextFileList);
    };
    const onProgress = (e, file) => {
      if (!utils.getFileItem(file, mergedFileList.value))
        return;
      const targetItem = utils.file2Obj(file);
      targetItem.status = "uploading";
      targetItem.percent = e.percent;
      const nextFileList = utils.updateFileList(targetItem, mergedFileList.value);
      onInternalChange(targetItem, nextFileList, e);
    };
    const onError = (error, response, file) => {
      if (!utils.getFileItem(file, mergedFileList.value))
        return;
      const targetItem = utils.file2Obj(file);
      targetItem.error = error;
      targetItem.response = response;
      targetItem.status = "error";
      const nextFileList = utils.updateFileList(targetItem, mergedFileList.value);
      onInternalChange(targetItem, nextFileList);
    };
    const handleRemove = (file) => {
      let currentFile;
      const mergedRemove = props$1.onRemove || props$1.remove;
      Promise.resolve(typeof mergedRemove === "function" ? mergedRemove(file) : mergedRemove).then((ret) => {
        var _a, _b;
        if (ret === false)
          return;
        const removedFileList = utils.removeFileItem(file, mergedFileList.value);
        if (removedFileList) {
          currentFile = {
            ...file,
            status: "removed"
          };
          (_a = mergedFileList.value) == null ? void 0 : _a.forEach((item) => {
            const matchKey = currentFile.uid !== void 0 ? "uid" : "name";
            if (item[matchKey] === currentFile[matchKey] && !Object.isFrozen(item))
              item.status = "removed";
          });
          (_b = upload.value) == null ? void 0 : _b.abort(currentFile);
          onInternalChange(currentFile, removedFileList);
        }
      });
    };
    const onFileDrop = (e) => {
      var _a;
      dragState.value = e.type;
      if (e.type === "drop")
        (_a = props$1.onDrop) == null ? void 0 : _a.call(props$1, e);
    };
    expose({
      onBatchStart,
      onSuccess,
      onProgress,
      onError,
      fileList: mergedFileList,
      upload
    });
    const [locale] = useLocaleReceiver.useLocaleReceiver("Upload", en_US.default.Upload, vue.computed(() => props$1.locale));
    const renderUploadList = (button, buttonVisible) => {
      const {
        removeIcon,
        previewIcon,
        downloadIcon,
        previewFile,
        onPreview,
        onDownload,
        isImageUrl,
        progress,
        itemRender,
        iconRender,
        showUploadList
      } = props$1;
      const {
        showDownloadIcon,
        showPreviewIcon,
        showRemoveIcon
      } = typeof showUploadList === "boolean" ? {} : showUploadList;
      return showUploadList ? vue.createVNode(index$2.default, {
        "prefixCls": prefixCls.value,
        "listType": props$1.listType,
        "items": mergedFileList.value,
        "previewFile": previewFile,
        "onPreview": onPreview,
        "onDownload": onDownload,
        "onRemove": handleRemove,
        "showRemoveIcon": !mergedDisabled.value && showRemoveIcon,
        "showPreviewIcon": showPreviewIcon,
        "showDownloadIcon": showDownloadIcon,
        "removeIcon": removeIcon,
        "previewIcon": previewIcon,
        "downloadIcon": downloadIcon,
        "iconRender": iconRender,
        "locale": locale.value,
        "isImageUrl": isImageUrl,
        "progress": progress,
        "itemRender": itemRender,
        "appendActionVisible": buttonVisible,
        "appendAction": button
      }, {
        ...slots
      }) : button == null ? void 0 : button();
    };
    return () => {
      var _a, _b;
      const {
        listType,
        type
      } = props$1;
      const {
        class: className,
        style: styleName,
        ...transAttrs
      } = attrs;
      const rcUploadProps = {
        onBatchStart,
        onError,
        onProgress,
        onSuccess,
        ...transAttrs,
        ...props$1,
        id: (_a = props$1.id) != null ? _a : formItemContext.id.value,
        prefixCls: prefixCls.value,
        beforeUpload: mergedBeforeUpload,
        onChange: void 0,
        disabled: mergedDisabled.value
      };
      delete rcUploadProps.remove;
      if (!slots.default || mergedDisabled.value)
        delete rcUploadProps.id;
      const rtlCls = {
        [`${prefixCls.value}-rtl`]: direction.value === "rtl"
      };
      if (type === "drag") {
        const dragCls = _class.classNames(prefixCls.value, {
          [`${prefixCls.value}-drag`]: true,
          [`${prefixCls.value}-drag-uploading`]: mergedFileList.value.some((file) => file.status === "uploading"),
          [`${prefixCls.value}-drag-hover`]: dragState.value === "dragover",
          [`${prefixCls.value}-disabled`]: mergedDisabled.value,
          [`${prefixCls.value}-rtl`]: direction.value === "rtl"
        }, attrs.class, hashId.value);
        return wrapSSR(vue.createVNode("span", {
          ...attrs,
          "class": _class.classNames(`${prefixCls.value}-wrapper`, rtlCls, className, hashId.value)
        }, [vue.createVNode("div", {
          "class": dragCls,
          "onDrop": onFileDrop,
          "onDragover": onFileDrop,
          "onDragleave": onFileDrop,
          "style": attrs.style
        }, [vue.createVNode(Upload.default, {
          ...rcUploadProps,
          "ref": upload,
          "class": `${prefixCls.value}-btn`
        }, {
          default: () => {
            var _a2;
            return [vue.createVNode("div", {
              "class": `${prefixCls.value}-drag-container`
            }, [(_a2 = slots.default) == null ? void 0 : _a2.call(slots)])];
          },
          ...slots
        })]), renderUploadList()]));
      }
      const uploadButtonCls = _class.classNames(prefixCls.value, {
        [`${prefixCls.value}-select`]: true,
        [`${prefixCls.value}-select-${listType}`]: true,
        [`${prefixCls.value}-disabled`]: mergedDisabled.value,
        [`${prefixCls.value}-rtl`]: direction.value === "rtl"
      });
      const children = props.flattenChildren((_b = slots.default) == null ? void 0 : _b.call(slots));
      const renderUploadButton = (uploadButtonStyle) => vue.createVNode("div", {
        "class": uploadButtonCls,
        "style": uploadButtonStyle
      }, [vue.createVNode(Upload.default, {
        ...rcUploadProps,
        "ref": upload
      }, slots)]);
      if (listType === "picture-card") {
        return wrapSSR(vue.createVNode("span", {
          ...attrs,
          "class": _class.classNames(`${prefixCls.value}-wrapper`, `${prefixCls.value}-picture-card-wrapper`, rtlCls, attrs.class, hashId.value)
        }, [renderUploadList(renderUploadButton, !!(children && children.length))]));
      }
      return wrapSSR(vue.createVNode("span", {
        ...attrs,
        "class": _class.classNames(`${prefixCls.value}-wrapper`, rtlCls, attrs.class, hashId.value)
      }, [renderUploadButton(children && children.length ? void 0 : {
        display: "none"
      }), renderUploadList()]));
    };
  }
});

exports.LIST_IGNORE = LIST_IGNORE;
exports.default = AUpload;
//# sourceMappingURL=Upload.cjs.map
