import { defineComponent as se, inject as i, ref as $, watch as oe, nextTick as ne, openBlock as h, createElementBlock as v, normalizeClass as ie, unref as n, createElementVNode as m, renderSlot as re, Fragment as ce, renderList as ue, withDirectives as le, createVNode as b, createCommentVNode as D, vShow as pe, toDisplayString as S } from "vue";
import { CloseOutlined as de, PlusOutlined as me } from "@ant-design/icons-vue";
import { message as f, Progress as fe } from "@aplus-frontend/antdv";
import { omit as ge } from "lodash-unified";
import "../../../config-provider/index.mjs";
import { randomStr as he } from "../../../utils/index.mjs";
import { useOss as ve, getOssInstance as L } from "../hooks/useOss.mjs";
import xe from "../style/index.mjs";
import { fileMatchesAccept as ye, getAcceptText as we } from "../utils/accept.mjs";
import { getPath as _e, getName as ke, getReturnData as O } from "../utils/returnData.mjs";
import { useLocale as Ue } from "../../../config-provider/hooks/use-locale.mjs";
import { useNamespace as Ce } from "../../../config-provider/hooks/use-namespace.mjs";
const be = ["accept"], Se = { class: "picture-context" }, Ee = { class: "picture-item-box" }, Ne = ["src"], Re = { class: "picture-item-shadow" }, ze = ["onClick"], Ae = {
  key: 0,
  class: "picture-item-uploading"
}, Me = { class: "picture-title" }, Pe = { key: 0 }, Ie = { key: 1 }, Qe = /* @__PURE__ */ se({
  __name: "Picture",
  setup(Ve, { expose: B }) {
    const { t: l } = Ue(), { b: T } = Ce("ap-upload-picture"), q = xe("ap-upload"), { put: j } = ve(), G = i("dirName"), H = i("baseDirName"), k = i("accept") || "image/*", U = i("maxSize") ?? 5, E = i("title"), p = i("maxCount") ?? 10, x = i("uploadingCount"), N = i("beforeUpload"), R = i("customRequest"), y = i("getOssAccess"), J = i("maxSizeErrorMsg"), K = i("maxCountErrorMsg"), Q = i("acceptErrorMsg"), w = $(null), c = i("value"), _ = i("needName"), z = i("onRemove"), C = i("showUploadErrorMsg"), A = i("bucket");
    let o = $([]);
    const g = [];
    oe(
      () => c?.value,
      async (t) => {
        !o?.value?.length && t && M(t);
      },
      { immediate: !0 }
    );
    function M(t) {
      if (!t) {
        c.value = void 0, g.splice(0, g.length), o.value = [];
        return;
      }
      ne(async () => {
        const s = [];
        for (let e of t) {
          const a = _e(_, e), r = ke(_, e), u = a?.match(/^([^:]+):(.*)$/), d = u?.[1], ee = u?.[2] ?? a, V = await L(
            () => d ? y?.(d) : y?.()
          ), te = await V.getSignatureUrl(ee), ae = {
            ...typeof e == "string" ? {} : e,
            ...new File([e], r, {}),
            uid: he(18),
            thumbUrl: te,
            status: "success",
            percent: 100,
            path: a
          };
          s.push(ae), V.destroy();
        }
        if (p && s.length > p) {
          f.warning(
            l("ap.apUpload.fileInitializationException", {
              maxCount: p
            })
          );
          return;
        }
        s.forEach((e) => {
          o.value.push(e), g.push({
            uid: e.uid,
            path: e.path
          });
        }), c.value = t;
      });
    }
    B({ setValue: M });
    function W() {
      w.value?.click();
    }
    function X(t) {
      const s = t.target;
      Y(s?.files);
    }
    function Y(t) {
      if (t?.length)
        for (let s = 0; s < t.length; s++)
          Z(t[s]);
      w.value && (w.value.value = "");
    }
    let P;
    async function Z(t) {
      if (p && p > 1 && o.value.length >= p)
        return clearTimeout(P), P = setTimeout(() => {
          f.warning(
            K || l("ap.apUpload.maxUploadPicture", { maxCount: p })
          );
        }), !1;
      if (t.size > U * 1024 * 1024)
        return f.warning(
          J || l("ap.apUpload.maxUploadFileSize", { maxSize: U })
        ), !1;
      if (!/image\/\w+/.test(t.type) || !ye(t, k))
        return f.warning(
          Q || l("ap.apUpload.pictureFormatNotSupported")
        ), !1;
      if (typeof N == "function" && await N(t) === !1)
        return !1;
      const s = new FileReader();
      s.readAsDataURL(t), s.onload = function() {
        const e = {
          ...t,
          uid: `${Date.now()}-${Math.random()}`,
          thumbUrl: this.result,
          status: "uploading",
          percent: 0
        };
        F(e, t);
      }, s.onerror = () => {
        f.warning(l("ap.apUpload.imageParsingFailed"));
      };
    }
    async function F(t, s) {
      if (x.value++, typeof R == "function") {
        R({
          onProgress: (e) => {
            const a = o.value.find((r) => r.uid === t.uid);
            a && (a.percent = e);
          },
          onError: (e) => {
            C && f.warning(e || l("ap.apUpload.networkAnomaly"));
            const a = o.value.findIndex(
              (r) => r.uid === t.uid
            );
            a > -1 && o.value.splice(a, 1), x.value--;
          },
          onSuccess: (e) => {
            const a = o.value.find((r) => r.uid === t.uid);
            a && (a.status = "success", a.path = e), c.value = [
              ...c.value || [],
              O(_, e, s.name)
            ], g.push({
              uid: t.uid,
              path: e
            }), x.value--;
          },
          file: s
        });
        return;
      }
      try {
        const e = await (A ? y(A) : y()), a = await L(async () => e);
        t.oss = a, o.value.push(t), j({
          file: s,
          dirName: G,
          oss: a,
          successCallBack(r) {
            const u = o.value.find((d) => d.uid === t.uid);
            u && (u.status = "success", u.path = r), c.value = [
              ...c.value || [],
              O(_, r, s.name)
            ], g.push({
              uid: t.uid,
              path: r
            }), x.value--;
          },
          errorCallBack(r) {
            C && f.warning(r || l("ap.apUpload.networkAnomaly"));
            const u = o.value.findIndex(
              (d) => d.uid === t.uid
            );
            u > -1 && o.value.splice(u, 1), x.value--;
          },
          progressCallBack(r) {
            const u = o.value.find((d) => d.uid === t.uid);
            u && (u.percent = r);
          },
          baseDirName: H,
          bucket: e?.bucket
        });
      } catch (e) {
        C && f.warning(
          typeof e?.message == "string" ? e.message : l("ap.apUpload.networkAnomaly")
        );
        const a = o.value.findIndex((r) => r.uid === t.uid);
        a > -1 && o.value.splice(a, 1), x.value--;
      }
    }
    function I(t) {
      if (z && z?.(t), t.path && c) {
        if (Array.isArray(c.value)) {
          const e = g.findIndex(
            (a) => a.uid === t.uid
          );
          if (e >= 0) {
            const a = c?.value?.slice() ?? [];
            a?.splice(e, 1), c.value = a, g.splice(e, 1);
          }
          c.value.length === 0 && (c.value = void 0);
        }
      } else
        t?.oss?.pauseUpload();
      const s = o.value.findIndex(
        (e) => e.uid === t.uid
      );
      return o.value.splice(s, 1), Promise.resolve(!0);
    }
    return (t, s) => (h(), v("div", {
      class: ie({
        [n(T)()]: !0,
        [n(q) ?? ""]: !0
      })
    }, [
      m("input", {
        ref_key: "fileRef",
        ref: w,
        style: { display: "none" },
        type: "file",
        accept: n(k),
        onChange: X
      }, null, 40, be),
      m("div", Se, [
        re(t.$slots, "pictureContext", {
          fileList: n(o).map((e) => ({
            ...n(ge)(e, "oss"),
            oss: {
              pauseUpload: e?.oss?.pauseUpload
            }
          })),
          remove: I
        }, () => [
          (h(!0), v(ce, null, ue(n(o), (e) => (h(), v("div", {
            key: e.uid,
            class: "picture-item"
          }, [
            m("div", Ee, [
              m("img", {
                src: e.thumbUrl,
                alt: ""
              }, null, 8, Ne),
              le(m("div", Re, [
                m("div", {
                  class: "picture-item-close",
                  onClick: (a) => I(e)
                }, [
                  b(n(de))
                ], 8, ze),
                e.status === "uploading" ? (h(), v("div", Ae, [
                  b(n(fe), {
                    percent: e.percent,
                    "stroke-color": "#ffffff",
                    "trail-color": "rgba(255, 255, 255, 0.3)",
                    size: 4,
                    "show-info": !1
                  }, null, 8, ["percent"])
                ])) : D("", !0)
              ], 512), [
                [pe, e.status === "uploading"]
              ])
            ])
          ]))), 128))
        ]),
        n(p) === void 0 || n(o).length < n(p) ? (h(), v("div", {
          key: 0,
          class: "picture-upload",
          onClick: W
        }, [
          b(n(me)),
          m("div", null, S(n(l)("ap.apUpload.update")), 1)
        ])) : D("", !0)
      ]),
      m("div", Me, [
        n(E) ? (h(), v("div", Pe, S(n(E)), 1)) : (h(), v("div", Ie, S(`${n(l)("ap.apUpload.supportExtension")}：${n(we)(n(k))}，${n(l)(
          "ap.apUpload.maxUploadPictureSize",
          { maxSize: n(U) }
        )}`), 1))
      ])
    ], 2));
  }
});
export {
  Qe as default
};
