'use strict';

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

var vue = require('vue');
require('../../../hooks/index.js');
require('../../../utils/index.js');
var index$3 = require('../../icon/index.js');
var Icons = require('@element-plus/icons-vue');
var index$2 = require('../../message/index.js');
var uploadDragger = require('./upload-dragger2.js');
var uploadContent = require('./upload-content.js');
var upload = require('./upload.js');
var uploadCropper = require('./upload-cropper2.js');
var pluginVue_exportHelper = require('../../../../_virtual/plugin-vue_export-helper.js');
var index = require('../../../hooks/use-namespace/index.js');
var index$1 = require('../../../hooks/use-common-props/index.js');
var objects = require('../../../utils/objects.js');

const _hoisted_1 = ["onKeydown"];
const _hoisted_2 = ["name", "multiple", "accept"];
const __default__ = vue.defineComponent({
  name: "ElUploadContent",
  inheritAttrs: false
});
const _sfc_main = /* @__PURE__ */ vue.defineComponent({
  ...__default__,
  props: uploadContent.uploadContentProps,
  setup(__props, { expose }) {
    const props = __props;
    const ns = index.useNamespace("upload");
    const disabled = index$1.useDisabled();
    const updateIndex = vue.ref(void 0);
    const showCropper = vue.ref(false);
    const cropperFile = vue.ref("");
    const requests = vue.shallowRef({});
    const inputRef = vue.shallowRef();
    const hookResult = vue.ref();
    const boolListIgnore = vue.ref(false);
    const uploadFile = async (file) => {
      const { autoUpload, onStart } = props;
      const rawFile = file;
      rawFile.uid = upload.genFileId();
      if (props.beforeUpload) {
        try {
          hookResult.value = await props.beforeUpload(rawFile);
        } catch (e) {
          hookResult.value = false;
        }
      } else {
        hookResult.value = void 0;
      }
      const hookResultList = !Array.isArray(hookResult.value) ? [hookResult.value] : hookResult.value;
      boolListIgnore.value = hookResultList.includes("LIST_IGNORE");
      if (!boolListIgnore.value) {
        onStart(rawFile, updateIndex.value);
      }
      if (hookResultList.includes(false)) {
        return;
      }
      if (autoUpload)
        upload$1(rawFile);
    };
    const uploadFiles = (files) => {
      if (files.length === 0)
        return;
      const { limit, fileList, multiple, onExceed } = props;
      if (typeof updateIndex.value !== "number") {
        if (limit && fileList.length + files.length > limit) {
          onExceed(files, fileList);
          const maxFileNum = limit - fileList.length;
          files = files.slice(0, maxFileNum);
        }
      }
      if (!multiple) {
        files = files.slice(0, 1);
      }
      if (props.showCropper) {
        cropperFile.value = files[0];
        showCropper.value = true;
      } else {
        for (const file of files) {
          uploadFile(file);
        }
      }
    };
    const uploadFormDate = (value) => {
      uploadFile(value);
    };
    const upload$1 = async (rawFile) => {
      inputRef.value.value = "";
      if (!props.beforeUpload) {
        if (props.size && props.size * 1024 * 1024 < rawFile.size) {
          index$2.ElMessage.warning(`\u8BF7\u4E0A\u4F20\u5C0F\u4E8E${props.size}M\u7684\u6587\u4EF6`);
          props.revokeObjectURL();
          return;
        }
        return doUpload(rawFile);
      }
      let file = rawFile;
      if (hookResult.value instanceof Blob) {
        if (hookResult.value instanceof File) {
          file = hookResult.value;
        } else {
          file = new File(!Array.isArray(hookResult.value) ? [hookResult.value] : hookResult.value, rawFile.name, {
            type: rawFile.type
          });
        }
      }
      doUpload(Object.assign(file, {
        uid: rawFile.uid
      }));
    };
    const doUpload = (rawFile) => {
      const {
        headers,
        data,
        method,
        withCredentials,
        name: filename,
        action,
        onProgress,
        onSuccess,
        onError,
        httpRequest
      } = props;
      const { uid } = rawFile;
      const options = {
        headers: headers || {},
        withCredentials,
        file: rawFile,
        data,
        method,
        filename,
        action,
        onProgress: (evt) => {
          onProgress(evt, rawFile);
        },
        onSuccess: (res) => {
          onSuccess(res, rawFile, boolListIgnore.value, updateIndex.value);
          delete requests.value[uid];
        },
        onError: (err) => {
          onError(err, rawFile);
          delete requests.value[uid];
        }
      };
      const request = httpRequest(options);
      requests.value[uid] = request;
      if (request instanceof Promise) {
        request.then(options.onSuccess, options.onError);
      }
    };
    const handleChange = (e) => {
      const files = e.target.files;
      if (!files)
        return;
      uploadFiles(Array.from(files));
    };
    const handleClick = (index) => {
      if (!disabled.value) {
        if (typeof index === "number") {
          updateIndex.value = index;
        } else {
          updateIndex.value = void 0;
        }
        if (typeof props.onAppendClick === "function") {
          props.onAppendClick(index);
          return;
        }
        inputRef.value.value = "";
        inputRef.value.click();
      }
    };
    const handleKeydown = () => {
      handleClick();
    };
    const abort = (file) => {
      const _reqs = objects.entriesOf(requests.value).filter(file ? ([uid]) => String(file.uid) === uid : () => true);
      _reqs.forEach(([uid, req]) => {
        if (req instanceof XMLHttpRequest)
          req.abort();
        delete requests.value[uid];
      });
    };
    expose({
      abort,
      upload: upload$1,
      handleClick
    });
    return (_ctx, _cache) => {
      return vue.openBlock(), vue.createElementBlock("div", {
        class: vue.normalizeClass([vue.unref(ns).b(), vue.unref(ns).m(_ctx.listType), vue.unref(ns).is("drag", _ctx.drag)]),
        tabindex: "0",
        onClick: _cache[2] || (_cache[2] = ($event) => handleClick()),
        onKeydown: vue.withKeys(vue.withModifiers(handleKeydown, ["self"]), ["enter", "space"])
      }, [
        _ctx.drag ? (vue.openBlock(), vue.createBlock(uploadDragger["default"], {
          key: 0,
          disabled: vue.unref(disabled),
          onFile: uploadFiles
        }, {
          default: vue.withCtx(() => [
            vue.renderSlot(_ctx.$slots, "default")
          ]),
          _: 3
        }, 8, ["disabled"])) : vue.renderSlot(_ctx.$slots, "default", { key: 1 }, () => [
          vue.createElementVNode("div", {
            class: vue.normalizeClass(vue.unref(ns).e("icon"))
          }, [
            vue.createVNode(vue.unref(index$3.ElIcon), { size: "16" }, {
              default: vue.withCtx(() => [
                vue.createVNode(vue.unref(Icons.Plus))
              ]),
              _: 1
            })
          ], 2),
          vue.createElementVNode("div", {
            class: vue.normalizeClass(vue.unref(ns).e("title"))
          }, vue.toDisplayString(props.btnText), 3)
        ]),
        vue.createVNode(uploadCropper["default"], vue.mergeProps({
          modelValue: showCropper.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => showCropper.value = $event)
        }, props, {
          file: cropperFile.value,
          onCropUploadSuccess: uploadFormDate
        }), null, 16, ["modelValue", "file"]),
        vue.createElementVNode("input", {
          ref_key: "inputRef",
          ref: inputRef,
          class: vue.normalizeClass(vue.unref(ns).e("input")),
          name: _ctx.name,
          multiple: _ctx.multiple,
          accept: _ctx.accept,
          type: "file",
          onChange: handleChange,
          onClick: _cache[1] || (_cache[1] = vue.withModifiers(() => {
          }, ["stop"]))
        }, null, 42, _hoisted_2)
      ], 42, _hoisted_1);
    };
  }
});
var UploadContent = /* @__PURE__ */ pluginVue_exportHelper["default"](_sfc_main, [["__file", "/home/lxj/workspace/element-plus/packages/components/upload/src/upload-content.vue"]]);

exports["default"] = UploadContent;
//# sourceMappingURL=upload-content2.js.map
