import { defineComponent, ref, shallowRef, openBlock, createElementBlock, normalizeClass, unref, withKeys, withModifiers, createBlock, withCtx, renderSlot, createElementVNode, createVNode, toDisplayString, mergeProps } from 'vue';
import '../../../hooks/index.mjs';
import '../../../utils/index.mjs';
import { ElIcon } from '../../icon/index.mjs';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from '../../message/index.mjs';
import UploadDragger from './upload-dragger2.mjs';
import { uploadContentProps } from './upload-content.mjs';
import { genFileId } from './upload.mjs';
import UploadCropper from './upload-cropper2.mjs';
import _export_sfc from '../../../../_virtual/plugin-vue_export-helper.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { useDisabled } from '../../../hooks/use-common-props/index.mjs';
import { entriesOf } from '../../../utils/objects.mjs';

const _hoisted_1 = ["onKeydown"];
const _hoisted_2 = ["name", "multiple", "accept"];
const __default__ = defineComponent({
  name: "ElUploadContent",
  inheritAttrs: false
});
const _sfc_main = /* @__PURE__ */ defineComponent({
  ...__default__,
  props: uploadContentProps,
  setup(__props, { expose }) {
    const props = __props;
    const ns = useNamespace("upload");
    const disabled = useDisabled();
    const showCropper = ref(false);
    const cropperFile = ref("");
    const requests = shallowRef({});
    const inputRef = shallowRef();
    const hookResult = ref();
    const boolListIgnore = ref(false);
    const uploadFile = async (file) => {
      const { autoUpload, onStart } = props;
      const rawFile = file;
      rawFile.uid = 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);
      }
      if (hookResultList.includes(false)) {
        return;
      }
      if (autoUpload)
        upload(rawFile);
    };
    const uploadFiles = (files) => {
      if (files.length === 0)
        return;
      const { limit, fileList, multiple, onExceed } = props;
      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 = async (rawFile) => {
      inputRef.value.value = "";
      if (!props.beforeUpload) {
        if (props.size && props.size * 1024 * 1024 < rawFile.size) {
          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);
          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 = () => {
      if (!disabled.value) {
        if (typeof props.onAppendClick === "function") {
          props.onAppendClick();
          return;
        }
        inputRef.value.value = "";
        inputRef.value.click();
      }
    };
    const handleKeydown = () => {
      handleClick();
    };
    const abort = (file) => {
      const _reqs = 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
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass([unref(ns).b(), unref(ns).m(_ctx.listType), unref(ns).is("drag", _ctx.drag)]),
        tabindex: "0",
        onClick: handleClick,
        onKeydown: withKeys(withModifiers(handleKeydown, ["self"]), ["enter", "space"])
      }, [
        _ctx.drag ? (openBlock(), createBlock(UploadDragger, {
          key: 0,
          disabled: unref(disabled),
          onFile: uploadFiles
        }, {
          default: withCtx(() => [
            renderSlot(_ctx.$slots, "default")
          ]),
          _: 3
        }, 8, ["disabled"])) : renderSlot(_ctx.$slots, "default", { key: 1 }, () => [
          createElementVNode("div", {
            class: normalizeClass(unref(ns).e("icon"))
          }, [
            createVNode(unref(ElIcon), { size: "16" }, {
              default: withCtx(() => [
                createVNode(unref(Plus))
              ]),
              _: 1
            })
          ], 2),
          createElementVNode("div", {
            class: normalizeClass(unref(ns).e("title"))
          }, toDisplayString(props.btnText), 3)
        ]),
        createVNode(UploadCropper, mergeProps({
          modelValue: showCropper.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => showCropper.value = $event)
        }, props, {
          file: cropperFile.value,
          onCropUploadSuccess: uploadFormDate
        }), null, 16, ["modelValue", "file"]),
        createElementVNode("input", {
          ref_key: "inputRef",
          ref: inputRef,
          class: normalizeClass(unref(ns).e("input")),
          name: _ctx.name,
          multiple: _ctx.multiple,
          accept: _ctx.accept,
          type: "file",
          onChange: handleChange,
          onClick: _cache[1] || (_cache[1] = withModifiers(() => {
          }, ["stop"]))
        }, null, 42, _hoisted_2)
      ], 42, _hoisted_1);
    };
  }
});
var UploadContent = /* @__PURE__ */ _export_sfc(_sfc_main, [["__file", "/home/kimihiro/workfiles/dingdandao/element-plus/packages/components/upload/src/upload-content.vue"]]);

export { UploadContent as default };
//# sourceMappingURL=upload-content2.mjs.map
