"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const utils = require("./utils.js");
const index_esm = require("../../../@vant/use/dist/index.esm.js");
const useExpose = require("../composables/use-expose.js");
const index = require("../icon/index.js");
require("../image-preview/index.js");
const UploaderPreviewItem = require("./UploaderPreviewItem.js");
const functionCall = require("../image-preview/function-call.js");
const props = require("../utils/props.js");
const format = require("../utils/format.js");
const basic = require("../utils/basic.js");
const uploaderProps = {
  name: props.makeNumericProp(""),
  accept: props.makeStringProp("image/*"),
  capture: String,
  multiple: Boolean,
  disabled: Boolean,
  readonly: Boolean,
  lazyLoad: Boolean,
  maxCount: props.makeNumericProp(Infinity),
  imageFit: props.makeStringProp("cover"),
  resultType: props.makeStringProp("dataUrl"),
  uploadIcon: props.makeStringProp("photograph"),
  uploadText: String,
  deletable: props.truthProp,
  reupload: Boolean,
  afterRead: Function,
  showUpload: props.truthProp,
  modelValue: props.makeArrayProp(),
  beforeRead: Function,
  beforeDelete: Function,
  previewSize: [Number, String, Array],
  previewImage: props.truthProp,
  previewOptions: Object,
  previewFullImage: props.truthProp,
  maxSize: {
    type: [Number, String, Function],
    default: Infinity
  }
};
var stdin_default = Vue.defineComponent({
  name: utils.name,
  props: uploaderProps,
  emits: ["delete", "oversize", "clickUpload", "closePreview", "clickPreview", "clickReupload", "update:modelValue"],
  setup(props2, {
    emit,
    slots
  }) {
    const inputRef = Vue.ref();
    const urls = [];
    const reuploadIndex = Vue.ref(-1);
    const isReuploading = Vue.ref(false);
    const getDetail = (index2 = props2.modelValue.length) => ({
      name: props2.name,
      index: index2
    });
    const resetInput = () => {
      if (inputRef.value) {
        inputRef.value.value = "";
      }
    };
    const onAfterRead = (items) => {
      resetInput();
      if (utils.isOversize(items, props2.maxSize)) {
        if (Array.isArray(items)) {
          const result = utils.filterFiles(items, props2.maxSize);
          items = result.valid;
          emit("oversize", result.invalid, getDetail());
          if (!items.length) {
            return;
          }
        } else {
          emit("oversize", items, getDetail());
          return;
        }
      }
      items = Vue.reactive(items);
      if (reuploadIndex.value > -1) {
        const arr = [...props2.modelValue];
        arr.splice(reuploadIndex.value, 1, items);
        emit("update:modelValue", arr);
        reuploadIndex.value = -1;
      } else {
        emit("update:modelValue", [...props2.modelValue, ...basic.toArray(items)]);
      }
      if (props2.afterRead) {
        props2.afterRead(items, getDetail());
      }
    };
    const readFile = (files) => {
      const {
        maxCount,
        modelValue,
        resultType
      } = props2;
      if (Array.isArray(files)) {
        const remainCount = +maxCount - modelValue.length;
        if (files.length > remainCount) {
          files = files.slice(0, remainCount);
        }
        Promise.all(files.map((file) => utils.readFileContent(file, resultType))).then((contents) => {
          const fileList = files.map((file, index2) => {
            const result = {
              file,
              status: "",
              message: "",
              objectUrl: URL.createObjectURL(file)
            };
            if (contents[index2]) {
              result.content = contents[index2];
            }
            return result;
          });
          onAfterRead(fileList);
        });
      } else {
        utils.readFileContent(files, resultType).then((content) => {
          const result = {
            file: files,
            status: "",
            message: "",
            objectUrl: URL.createObjectURL(files)
          };
          if (content) {
            result.content = content;
          }
          onAfterRead(result);
        });
      }
    };
    const onChange = (event) => {
      const {
        files
      } = event.target;
      if (props2.disabled || !files || !files.length) {
        return;
      }
      const file = files.length === 1 ? files[0] : [].slice.call(files);
      if (props2.beforeRead) {
        const response = props2.beforeRead(file, getDetail());
        if (!response) {
          resetInput();
          return;
        }
        if (basic.isPromise(response)) {
          response.then((data) => {
            if (data) {
              readFile(data);
            } else {
              readFile(file);
            }
          }).catch(resetInput);
          return;
        }
      }
      readFile(file);
    };
    let imagePreview;
    const onClosePreview = () => emit("closePreview");
    const previewImage = (item) => {
      if (props2.previewFullImage) {
        const imageFiles = props2.modelValue.filter(utils.isImageFile);
        const images = imageFiles.map((item2) => {
          if (item2.objectUrl && !item2.url && item2.status !== "failed") {
            item2.url = item2.objectUrl;
            urls.push(item2.url);
          }
          return item2.url;
        }).filter(Boolean);
        imagePreview = functionCall.showImagePreview(basic.extend({
          images,
          startPosition: imageFiles.indexOf(item),
          onClose: onClosePreview
        }, props2.previewOptions));
      }
    };
    const closeImagePreview = () => {
      if (imagePreview) {
        imagePreview.close();
      }
    };
    const deleteFile = (item, index2) => {
      const fileList = props2.modelValue.slice(0);
      fileList.splice(index2, 1);
      emit("update:modelValue", fileList);
      emit("delete", item, getDetail(index2));
    };
    const reuploadFile = (index2) => {
      isReuploading.value = true;
      reuploadIndex.value = index2;
      Vue.nextTick(() => chooseFile());
    };
    const onInputClick = () => {
      if (!isReuploading.value) {
        reuploadIndex.value = -1;
      }
      isReuploading.value = false;
    };
    const renderPreviewItem = (item, index2) => {
      const needPickData = ["imageFit", "deletable", "reupload", "previewSize", "beforeDelete"];
      const previewData = basic.extend(basic.pick(props2, needPickData), basic.pick(item, needPickData, true));
      return Vue.createVNode(UploaderPreviewItem.default, Vue.mergeProps({
        "item": item,
        "index": index2,
        "onClick": () => emit(props2.reupload ? "clickReupload" : "clickPreview", item, getDetail(index2)),
        "onDelete": () => deleteFile(item, index2),
        "onPreview": () => previewImage(item),
        "onReupload": () => reuploadFile(index2)
      }, basic.pick(props2, ["name", "lazyLoad"]), previewData), basic.pick(slots, ["preview-cover", "preview-delete"]));
    };
    const renderPreviewList = () => {
      if (props2.previewImage) {
        return props2.modelValue.map(renderPreviewItem);
      }
    };
    const onClickUpload = (event) => emit("clickUpload", event);
    const renderUpload = () => {
      const lessThanMax = props2.modelValue.length < +props2.maxCount;
      const Input = props2.readonly ? null : Vue.createVNode("input", {
        "ref": inputRef,
        "type": "file",
        "class": utils.bem("input"),
        "accept": props2.accept,
        "capture": props2.capture,
        "multiple": props2.multiple && reuploadIndex.value === -1,
        "disabled": props2.disabled,
        "onChange": onChange,
        "onClick": onInputClick
      }, null);
      if (slots.default) {
        return Vue.withDirectives(Vue.createVNode("div", {
          "class": utils.bem("input-wrapper"),
          "onClick": onClickUpload
        }, [slots.default(), Input]), [[Vue.vShow, lessThanMax]]);
      }
      return Vue.withDirectives(Vue.createVNode("div", {
        "class": utils.bem("upload", {
          readonly: props2.readonly
        }),
        "style": format.getSizeStyle(props2.previewSize),
        "onClick": onClickUpload
      }, [Vue.createVNode(index.Icon, {
        "name": props2.uploadIcon,
        "class": utils.bem("upload-icon")
      }, null), props2.uploadText && Vue.createVNode("span", {
        "class": utils.bem("upload-text")
      }, [props2.uploadText]), Input]), [[Vue.vShow, props2.showUpload && lessThanMax]]);
    };
    const chooseFile = () => {
      if (inputRef.value && !props2.disabled) {
        inputRef.value.click();
      }
    };
    Vue.onBeforeUnmount(() => {
      urls.forEach((url) => URL.revokeObjectURL(url));
    });
    useExpose.useExpose({
      chooseFile,
      reuploadFile,
      closeImagePreview
    });
    index_esm.useCustomFieldValue(() => props2.modelValue);
    return () => Vue.createVNode("div", {
      "class": utils.bem()
    }, [Vue.createVNode("div", {
      "class": utils.bem("wrapper", {
        disabled: props2.disabled
      })
    }, [renderPreviewList(), renderUpload()])]);
  }
});
exports.default = stdin_default;
exports.uploaderProps = uploaderProps;
