"use strict";
const vue = require("vue");
const types = require("./types.js");
const is = require("../_utils/is.js");
const vueUtils = require("../_utils/vue-utils.js");
const UploadItem_vue_vue_type_script_setup_true_lang = require("./UploadItem.vue.js");
const slot = require("./slot.js");
const util = require("./util.js");
const UploadSelect_vue_vue_type_script_setup_true_lang = require("./UploadSelect.vue.js");
const icons = require("../_utils/icons.js");
const InputSelect_vue_vue_type_script_setup_true_lang = require("./InputSelect.vue.js");
const provide = require("../form/provide.js");
const index = require("../locale/index.js");
const _hoisted_1 = {
  key: 0,
  class: "o-upload-select-wrap"
};
const _hoisted_2 = {
  key: 0,
  class: "o-upload-select-extra"
};
const _hoisted_3 = { class: "o-upload-card-label" };
const _sfc_main = /* @__PURE__ */ vue.defineComponent({
  __name: "OUpload",
  props: types.uploadProps,
  emits: ["progress", "success", "error", "change", "select", "update:modelValue"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const emitUpdateValue = (value) => {
      emits("update:modelValue", value);
    };
    const { t } = index.useI18n();
    const fileList = vue.ref(props.modelValue ?? props.defaultFileList ?? []);
    vue.watch(
      () => props.modelValue,
      (v) => {
        if (fileList.value === v) {
          return;
        }
        if (is.isArray(v)) {
          fileList.value = [...v];
        } else {
          fileList.value = [];
        }
      }
    );
    const formItemInjection = vue.inject(provide.formItemInjectKey, null);
    let fileId = 1;
    const uploadOption = vue.computed(() => {
      return {
        uploadRequest: props.uploadRequest,
        onBeforeUpload: props.onBeforeUpload,
        onProgress: (file) => {
          emits("progress", file);
        },
        onSuccess: (file) => {
          emits("success", file);
          emitUpdateValue(fileList.value);
          emits("change", fileList.value);
        },
        onError: (file) => {
          emits("error", file);
          emitUpdateValue(fileList.value);
          emits("change", fileList.value);
        }
      };
    });
    const selectRef = vue.ref(null);
    let replaceId = "";
    const uploadAll = () => {
      return util.doUploadFileList(fileList.value, uploadOption.value);
    };
    const afterSelected = (files) => {
      var _a, _b, _c, _d, _e, _f, _g;
      if (replaceId) {
        const idx = fileList.value.findIndex((item) => item.id === replaceId);
        if (idx > -1) {
          const f = fileList.value[idx];
          (_a = f.request) == null ? void 0 : _a.abort();
          fileList.value[idx] = files[0];
          replaceId = "";
          emitUpdateValue(fileList.value);
          emits("select", fileList.value);
          (_c = formItemInjection == null ? void 0 : (_b = formItemInjection.fieldHandlers).onChange) == null ? void 0 : _c.call(_b);
          if (!props.lazyUpload) {
            util.doUploadFile(fileList.value[idx], uploadOption.value);
          }
        }
      } else {
        let s = fileList.value.length;
        let l = files.length;
        if (props.multiple) {
          fileList.value = fileList.value.concat(files);
        } else {
          (_e = (_d = fileList.value[0]) == null ? void 0 : _d.request) == null ? void 0 : _e.abort();
          fileList.value = files;
          s = 0;
          l = 1;
        }
        emitUpdateValue(fileList.value);
        emits("select", fileList.value);
        (_g = formItemInjection == null ? void 0 : (_f = formItemInjection.fieldHandlers).onChange) == null ? void 0 : _g.call(_f);
        if (!props.lazyUpload) {
          util.doUploadFileList(fileList.value.slice(s, s + l), uploadOption.value);
        }
      }
    };
    const onFileSelected = async (files) => {
      let list = [];
      const isPicture = util.isPictureType(props.listType);
      if (is.isFunction(props.onAfterSelect)) {
        list = await props.onAfterSelect(files);
        if (isPicture) {
          list.forEach((item) => {
            if (!item.imgUrl && item.file) {
              item.imgUrl = util.generateImageDataUrl(item.file);
            }
          });
        }
      } else {
        list = Array.from(files).map((item) => {
          return {
            id: `${fileId++}`,
            name: item.name,
            file: item,
            imgUrl: isPicture ? util.generateImageDataUrl(item) : ""
          };
        });
      }
      afterSelected(list);
    };
    const removeFile = async (file) => {
      var _a, _b, _c;
      if (is.isFunction(props.onBeforeRemove)) {
        const sure = await props.onBeforeRemove(file);
        if (sure === false) {
          return false;
        }
      }
      (_a = file.request) == null ? void 0 : _a.abort();
      fileList.value = fileList.value.filter((f) => f.id !== file.id);
      (_c = formItemInjection == null ? void 0 : (_b = formItemInjection.fieldHandlers).onChange) == null ? void 0 : _c.call(_b);
      emitUpdateValue(fileList.value);
      return true;
    };
    const removeFileByIndex = (index2) => {
      if (index2 > -1 && index2 < fileList.value.length) {
        return removeFile(fileList.value[index2]);
      }
    };
    const removeAllFiles = () => {
      return new Promise((resolve) => {
        Promise.allSettled(fileList.value.map((f) => removeFile(f))).then((res) => {
          resolve(res);
        });
        fileList.value = [];
        emitUpdateValue(fileList.value);
      });
    };
    const onFileUploadRetry = (file) => {
      if (!file.retry || !file.file) {
        return;
      }
      util.doUploadFile(file, uploadOption.value);
    };
    const onFileReplace = (file) => {
      var _a;
      (_a = selectRef.value) == null ? void 0 : _a.select(false);
      replaceId = file.id;
    };
    const doSelect = async () => {
      var _a;
      if (is.isFunction(props.beforeSelect)) {
        const goon = await props.beforeSelect(fileList.value);
        if (goon === false) {
          return;
        }
      }
      (_a = selectRef.value) == null ? void 0 : _a.select(props.multiple);
    };
    __expose({
      upload: uploadAll,
      select: doSelect,
      retry: onFileUploadRetry,
      replace: onFileReplace,
      removeByIndex: removeFileByIndex,
      removeAll: removeAllFiles
    });
    return (_ctx, _cache) => {
      return vue.openBlock(), vue.createElementBlock(
        "div",
        {
          class: vue.normalizeClass(["o-upload", { "o-upload-draggable": _ctx.draggable }])
        },
        [
          vue.createVNode(InputSelect_vue_vue_type_script_setup_true_lang, {
            ref_key: "selectRef",
            ref: selectRef,
            accept: props.accept,
            disabled: props.disabled,
            onSelected: onFileSelected
          }, null, 8, ["accept", "disabled"]),
          ["text", "picture"].includes(props.listType) ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_1, [
            vue.createVNode(UploadSelect_vue_vue_type_script_setup_true_lang, {
              disabled: props.disabled,
              draggable: props.draggable,
              "btn-label": props.btnLabel,
              "drag-label": props.dragLabel,
              "drag-hover-label": props.dragHoverLabel,
              onToSelect: doSelect,
              onSelected: onFileSelected
            }, vue.createSlots({
              _: 2
              /* DYNAMIC */
            }, [
              vue.renderList(vue.unref(vueUtils.filterSlots)(_ctx.$slots, vue.unref(slot).names), (name) => {
                return {
                  name,
                  fn: vue.withCtx((slotData) => [
                    vue.renderSlot(_ctx.$slots, name, vue.normalizeProps(vue.guardReactiveProps(slotData)))
                  ])
                };
              })
            ]), 1032, ["disabled", "draggable", "btn-label", "drag-label", "drag-hover-label"]),
            _ctx.$slots["select-extra"] ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_2, [
              vue.renderSlot(_ctx.$slots, "select-extra")
            ])) : vue.createCommentVNode("v-if", true)
          ])) : vue.createCommentVNode("v-if", true),
          vue.createElementVNode(
            "div",
            {
              class: vue.normalizeClass(["o-upload-list", {
                "o-upload-card-list": props.listType === "picture-card"
              }])
            },
            [
              (vue.openBlock(true), vue.createElementBlock(
                vue.Fragment,
                null,
                vue.renderList(fileList.value, (item) => {
                  return vue.openBlock(), vue.createBlock(UploadItem_vue_vue_type_script_setup_true_lang, {
                    key: item.id,
                    file: item,
                    "list-type": props.listType,
                    onRemove: removeFile,
                    onRetry: onFileUploadRetry,
                    onReplace: onFileReplace
                  }, vue.createSlots({
                    _: 2
                    /* DYNAMIC */
                  }, [
                    vue.renderList(vue.unref(vueUtils.filterSlots)(_ctx.$slots, vue.unref(slot).names), (name) => {
                      return {
                        name,
                        fn: vue.withCtx((slotData) => [
                          vue.renderSlot(_ctx.$slots, name, vue.mergeProps({ ref_for: true }, slotData))
                        ])
                      };
                    })
                  ]), 1032, ["file", "list-type"]);
                }),
                128
                /* KEYED_FRAGMENT */
              )),
              props.listType === "picture-card" ? (vue.openBlock(), vue.createElementBlock(
                "div",
                {
                  key: 0,
                  class: vue.normalizeClass(["o-upload-card-add", {
                    "is-disabled": props.disabled
                  }]),
                  onClick: doSelect
                },
                [
                  vue.createElementVNode("div", null, [
                    vue.renderSlot(_ctx.$slots, "select-add", {}, () => [
                      vue.createVNode(vue.unref(icons.IconAdd), { class: "o-upload-card-add-icon" }),
                      vue.createElementVNode("div", _hoisted_3, [
                        vue.renderSlot(_ctx.$slots, "select-add-label", {}, () => [
                          vue.createTextVNode(
                            vue.toDisplayString(props.btnLabel ?? vue.unref(t)("upload.buttonLabel")),
                            1
                            /* TEXT */
                          )
                        ])
                      ])
                    ])
                  ])
                ],
                2
                /* CLASS */
              )) : vue.createCommentVNode("v-if", true)
            ],
            2
            /* CLASS */
          )
        ],
        2
        /* CLASS */
      );
    };
  }
});
module.exports = _sfc_main;
