import { defineComponent, useAttrs, ref, computed, watch, resolveComponent, createElementBlock, openBlock, normalizeClass, unref, createElementVNode, createCommentVNode, createVNode, withCtx, mergeProps, createBlock, renderSlot, withModifiers, Fragment, toDisplayString, renderList } from 'vue';
import '../../../utils/index.mjs';
import { Form, message } from 'ant-design-vue';
import { uploadImageEmits, uploadImageProps } from './upload-image.mjs';
import { omit } from 'lodash-es';
import '../../image/index.mjs';
import '../../watermark/index.mjs';
import { createNamespace } from '../../../utils/create-namespace.mjs';
import { imageProps } from '../../image/src/image.mjs';
import { watermarkProps } from '../../watermark/src/watermark.mjs';
import { formatFileSize, fileToBase64 } from '../../../utils/file.mjs';

"use strict";
const _hoisted_1 = { style: { "display": "none" } };
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{ name: "LlUploadImage" },
  __name: "upload-image",
  props: uploadImageProps,
  emits: uploadImageEmits,
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const bem = createNamespace("upload-image");
    const attrs = useAttrs();
    const fileList = ref([]);
    const imageVisible = ref(false);
    const innerValue = ref(
      Array.isArray(props.value) ? [...props.value] : props.value ? [props.value] : []
    );
    const formItemContext = Form.useInjectFormItemContext();
    const getBindValue = computed(() => ({
      ...omit({ ...attrs }, [...Object.keys(imageProps)])
    }));
    const getImgBindValue = computed(() => {
      const imagePropKeys = Object.keys({ ...imageProps, ...watermarkProps });
      return Object.fromEntries(
        Object.entries(attrs).filter(([key]) => imagePropKeys.includes(key))
      );
    });
    function getSizeStyle(size) {
      if (typeof size === "number") {
        return `${size}px`;
      }
      if (typeof size === "string") {
        return size;
      }
      return void 0;
    }
    const handleDragEvent = (e) => {
      if (!props.isDrag) {
        e.preventDefault();
        e.stopPropagation();
      }
    };
    const getBorderType = computed(() => {
      switch (props.borderType) {
        // 虚线
        case "dashed":
          return "dashed";
        // 实线
        case "solid":
          return "solid";
        // 点线
        case "dotted":
          return "dotted";
        default:
          return "";
      }
    });
    const computedAccept = computed(() => {
      return props.accept ? props.accept.split(",").map((e) => e.replace(".", "")).join(",") : props.accept;
    });
    const computedTip = computed(() => {
      return typeof props.uploadTip === "string" ? props.uploadTip : props.uploadTip ? `\u652F\u6301${computedAccept.value}\u683C\u5F0F\uFF0C\u4E0D\u8D85\u8FC7${formatFileSize(
        props.imgSize * 1024 * 1024
      )}\u3002` : "";
    });
    const computedMultiple = computed(() => props.maxCount > 1);
    const beforeUpload = async (file, FileList) => {
      const fileType = file.type.toLowerCase().replace("image/", "");
      const isType = fileType === "svg+xml" ? true : props.accept.includes(fileType);
      const fileSizeInMB = file.size / (1024 * 1024);
      const isSize = props.imgSize === 0 ? true : fileSizeInMB <= props.imgSize;
      if (!isType) {
        message.error(`${file.name} \u9700\u8981\u4E3A${computedAccept.value}\u683C\u5F0F\u3002`);
        return false;
      }
      if (!isSize) {
        message.error(
          `${file.name} \u6587\u4EF6\u4E0D\u5F97\u5927\u4E8E${formatFileSize(
            props.imgSize * 1024 * 1024
          )}\u3002`
        );
        return false;
      }
      return isType && isSize && props.beforeUpload?.(file, FileList);
    };
    const customRequest = async (res) => {
      const fileUrl = await fileToBase64(res.file);
      if (props.useBase64) {
        props.maxCount === 1 ? innerValue.value = [fileUrl] : innerValue.value.push(fileUrl);
      }
      try {
        props.customRequest?.(res, fileUrl);
      } catch (error) {
        innerValue.value.splice(innerValue.value.length - 1, 1);
        message.error("\u4E0A\u4F20\u5931\u8D25");
      }
    };
    const handleRemoveImage = async () => {
      const index = innerValue.value.length - 1;
      innerValue.value.splice(index, 1);
      setValue();
    };
    const setValue = () => {
      const value = props.maxCount === 1 ? innerValue.value.length ? innerValue.value[0] : "" : innerValue.value;
      emits("update:value", value);
      emits("change", value);
      formItemContext.onFieldChange();
    };
    watch(
      () => props.value,
      (newVal) => {
        if (newVal !== innerValue.value) {
          innerValue.value = Array.isArray(newVal) ? [...newVal] : newVal ? [newVal] : [];
        }
      }
    );
    watch(
      innerValue,
      () => {
        setValue();
      },
      {
        deep: true
      }
    );
    return (_ctx, _cache) => {
      const _component_ll_icon = resolveComponent("ll-icon");
      const _component_ll_image = resolveComponent("ll-image");
      const _component_a_upload = resolveComponent("a-upload");
      const _component_a_spin = resolveComponent("a-spin");
      const _component_a_image = resolveComponent("a-image");
      const _component_a_image_preview_group = resolveComponent("a-image-preview-group");
      return openBlock(), createElementBlock(
        "div",
        {
          class: normalizeClass(unref(bem).b())
        },
        [
          createElementVNode(
            "div",
            {
              class: normalizeClass(unref(bem).m("preview-box"))
            },
            [
              createVNode(_component_a_spin, {
                size: "small",
                spinning: props.imgLoading
              }, {
                default: withCtx(() => [
                  createVNode(_component_a_upload, mergeProps({
                    "file-list": fileList.value,
                    "onUpdate:fileList": _cache[1] || (_cache[1] = ($event) => fileList.value = $event)
                  }, getBindValue.value, {
                    accept: props.accept,
                    "show-upload-list": false,
                    "max-count": props.maxCount,
                    multiple: computedMultiple.value,
                    "before-upload": beforeUpload,
                    "custom-request": customRequest,
                    class: [unref(bem).m("upload"), unref(bem).is(getBorderType.value)],
                    style: {
                      width: getSizeStyle(_ctx.width + 2),
                      height: getSizeStyle(_ctx.height + 2),
                      borderRadius: _ctx.borderRadius
                    },
                    "list-type": "picture-card",
                    onDragenterCapture: handleDragEvent,
                    onDragoverCapture: handleDragEvent,
                    onDropCapture: handleDragEvent
                  }), {
                    default: withCtx(() => [
                      innerValue.value.length > 0 ? (openBlock(), createBlock(_component_ll_image, mergeProps({ key: 0 }, getImgBindValue.value, {
                        preview: { visible: false },
                        width: getSizeStyle(_ctx.width),
                        height: getSizeStyle(_ctx.height),
                        "border-radius": "0",
                        src: innerValue.value[0],
                        "is-show-border": false
                      }), {
                        previewMaskContent: withCtx(() => [
                          createElementVNode(
                            "div",
                            {
                              class: normalizeClass(unref(bem).m("preview-mask"))
                            },
                            [
                              _ctx.isPreview ? (openBlock(), createBlock(_component_ll_icon, {
                                key: 0,
                                "icon-name": `icon-pwd-look`,
                                class: normalizeClass(unref(bem).e("image-icon")),
                                onClick: _cache[0] || (_cache[0] = withModifiers(($event) => imageVisible.value = true, ["stop"]))
                              }, null, 8, ["class"])) : createCommentVNode("v-if", true),
                              _ctx.isDelete ? (openBlock(), createBlock(_component_ll_icon, {
                                key: 1,
                                "icon-name": `icon-delete`,
                                class: normalizeClass(unref(bem).e("image-icon")),
                                onClick: withModifiers(handleRemoveImage, ["stop"])
                              }, null, 8, ["class"])) : createCommentVNode("v-if", true),
                              _cache[2] || (_cache[2] = createElementVNode(
                                "div",
                                null,
                                null,
                                -1
                                /* CACHED */
                              ))
                            ],
                            2
                            /* CLASS */
                          )
                        ]),
                        _: 1
                        /* STABLE */
                      }, 16, ["width", "height", "src"])) : !_ctx.$slots.iconRender ? (openBlock(), createElementBlock(
                        Fragment,
                        { key: 1 },
                        [
                          createCommentVNode(" \u65E0\u56FE\u7247\u65F6\u5C55\u793A\u56FE\u6807 "),
                          createElementVNode(
                            "div",
                            {
                              class: normalizeClass(unref(bem).e("upload-content"))
                            },
                            [
                              createVNode(_component_ll_icon, {
                                "icon-name": _ctx.uploadIcon || "icon-add",
                                size: _ctx.uploadIconSize
                              }, null, 8, ["icon-name", "size"]),
                              createCommentVNode(" \u4E0A\u4F20\u6807\u9898 "),
                              _ctx.uploadTitle ? (openBlock(), createElementBlock(
                                "div",
                                {
                                  key: 0,
                                  class: normalizeClass(unref(bem).m("upload-title"))
                                },
                                toDisplayString(_ctx.uploadTitle),
                                3
                                /* TEXT, CLASS */
                              )) : createCommentVNode("v-if", true),
                              createCommentVNode(" \u4E0A\u4F20\u63D0\u793A "),
                              computedTip.value ? (openBlock(), createElementBlock(
                                "div",
                                {
                                  key: 1,
                                  class: normalizeClass(unref(bem).m("upload-tip"))
                                },
                                toDisplayString(computedTip.value),
                                3
                                /* TEXT, CLASS */
                              )) : createCommentVNode("v-if", true)
                            ],
                            2
                            /* CLASS */
                          )
                        ],
                        2112
                        /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
                      )) : renderSlot(_ctx.$slots, "iconRender", { key: 2 })
                    ]),
                    _: 3
                    /* FORWARDED */
                  }, 16, ["file-list", "accept", "max-count", "multiple", "class", "style"])
                ]),
                _: 3
                /* FORWARDED */
              }, 8, ["spinning"])
            ],
            2
            /* CLASS */
          ),
          createCommentVNode(" \u9884\u89C8\u5C55\u793A "),
          createElementVNode("div", _hoisted_1, [
            createVNode(_component_a_image_preview_group, {
              preview: {
                visible: imageVisible.value,
                onVisibleChange: (vis) => imageVisible.value = vis
              }
            }, {
              default: withCtx(() => [
                (openBlock(true), createElementBlock(
                  Fragment,
                  null,
                  renderList(innerValue.value, (item) => {
                    return openBlock(), createBlock(_component_a_image, {
                      key: item,
                      src: item
                    }, null, 8, ["src"]);
                  }),
                  128
                  /* KEYED_FRAGMENT */
                ))
              ]),
              _: 1
              /* STABLE */
            }, 8, ["preview"])
          ])
        ],
        2
        /* CLASS */
      );
    };
  }
});

export { _sfc_main as default };
//# sourceMappingURL=upload-image.vue2.mjs.map
