import { defineComponent as ne, inject as s, ref as re, watch as ie, nextTick as le, openBlock as g, createElementBlock as N, normalizeClass as ce, unref as a, createVNode as h, withCtx as w, createElementVNode as L, createTextVNode as M, toDisplayString as U, createBlock as z, resolveDynamicComponent as B, createCommentVNode as ue, createSlots as pe } from "vue";
import { UploadOutlined as de } from "@ant-design/icons-vue";
import { message as d, Upload as me, Button as fe, Tooltip as we } from "@aplus-frontend/antdv";
import { IconApAdLineDownload as ge } from "@aplus-frontend/icon";
import { ApFilePreview as he } from "../../ap-file-preview/index.mjs";
import "../../../config-provider/index.mjs";
import { randomStr as ve } from "../../../utils/index.mjs";
import { useOss as xe, getOssInstance as O } from "../hooks/useOss.mjs";
import ye from "../style/index.mjs";
import { fileMatchesAccept as ke, getAcceptText as be } from "../utils/accept.mjs";
import { getPath as Ce, getName as _e, getReturnData as V } from "../utils/returnData.mjs";
import { useGlobalConfig as Ne } from "../../../config-provider/hooks/use-global-config.mjs";
import { useLocale as Ue } from "../../../config-provider/hooks/use-locale.mjs";
import { useNamespace as Ee } from "../../../config-provider/hooks/use-namespace.mjs";
const Fe = { class: "multiple-file-context" }, Ae = { key: 0 }, Pe = { key: 1 }, We = /* @__PURE__ */ ne({
  __name: "MultipleFile",
  setup(Te, { expose: q }) {
    const E = Ne(
      "downloadCenterTriggerConfig"
    ), { t: r } = Ue(), { b: j } = Ee("ap-upload-multiple-file"), $ = ye("ap-upload"), { put: G } = xe(), W = s("dirName"), H = s("baseDirName"), C = s("accept") || "*", F = s("maxSize") ?? 500, J = s("title") || r("ap.apUpload.uploadFile"), v = s("subTitle"), l = s("maxCount") ?? 10, m = s("uploadingCount"), A = s("beforeUpload"), P = s("customRequest"), x = s("getOssAccess"), K = s("maxSizeErrorMsg"), Q = s("maxCountErrorMsg"), X = s("acceptErrorMsg"), T = s("onRemove"), _ = s("showUploadErrorMsg"), R = s("bucket"), Y = s("showDownload") ?? !0, c = s("showPreview") ?? !0, i = s("value"), u = [], y = s("needName"), f = re(null);
    ie(
      () => i?.value,
      (e) => {
        !f?.value?.fileList?.length && e && I(e);
      },
      { immediate: !0 }
    );
    function I(e) {
      if (!e) {
        p = [], f.value.fileList = [], i.value = void 0, u.splice(0, u.length);
        return;
      }
      le(() => {
        const o = e.map((t) => {
          const n = Ce(y, t), D = _e(y, t), b = new File(
            [t],
            D,
            {}
          );
          return b.response = n, b.uid = ve(18), b.status = "done", b;
        });
        if (l && o.length > l) {
          d.warning(
            r("ap.apUpload.fileInitializationException", {
              maxCount: l
            })
          );
          return;
        }
        o.forEach((t) => {
          p.push(t), u.push({
            uid: t.uid,
            path: t.response
          });
        }), f.value.fileList = o, i.value = e;
      });
    }
    q({ setValue: I });
    let p = [], S;
    function k(e) {
      setTimeout(() => {
        const o = f.value.fileList.findIndex(
          (t) => t.uid === e.uid
        );
        o >= 0 && f.value.fileList.splice(o, 1);
      });
    }
    async function Z(e) {
      if (l && l > 1 && p.length >= l)
        return clearTimeout(S), S = setTimeout(() => {
          d.warning(
            Q || r("ap.apUpload.maxUploadFiles", {
              maxCount: l
            })
          );
        }), k(e), !1;
      if (e.size > F * 1024 * 1024)
        return d.warning(
          K || r("ap.apUpload.maxUploadFileSize", {
            maxSize: F
          })
        ), k(e), !1;
      if (!ke(e, C))
        return d.warning(
          X || r("ap.apUpload.fileFormatNotSupported")
        ), k(e), !1;
      if (typeof A == "function" && await A(e) === !1)
        return k(e), !1;
      l && l === 1 && (p = [], i.value = void 0), p.push(e);
    }
    async function ee(e) {
      if (m.value++, typeof P == "function") {
        P({
          onProgress: (o) => {
            setTimeout(() => {
              e.onProgress({
                percent: o
              });
            });
          },
          onError: (o) => {
            _ && d.warning(o || r("ap.apUpload.networkAnomaly")), setTimeout(() => {
              e.onError({
                name: o,
                message: o
              });
            }), m.value--;
          },
          onSuccess: (o) => {
            setTimeout(() => {
              e.onSuccess(o);
            }), i.value = [
              ...i.value || [],
              V(y, o, e.file.name)
            ], u.push({
              uid: e.file.uid,
              path: o
            }), m.value--;
          },
          file: e.file
        });
        return;
      }
      try {
        const o = await (R ? x(R) : x()), t = await O(async () => o);
        e.file.oss = t, G({
          file: e.file,
          dirName: W,
          oss: t,
          successCallBack(n) {
            e.onSuccess(n), i.value = [
              ...i.value || [],
              V(y, n, e.file.name)
            ], u.push({
              uid: e.file.uid,
              path: n
            }), m.value--;
          },
          errorCallBack(n) {
            _ && d.warning(n || r("ap.apUpload.networkAnomaly")), e.onError({
              name: n,
              message: n
            }), m.value--;
          },
          progressCallBack(n) {
            e.onProgress({
              percent: n
            });
          },
          baseDirName: H,
          bucket: o?.bucket
        });
      } catch (o) {
        _ && d.warning(
          typeof o?.message == "string" ? o.message : r("ap.apUpload.networkAnomaly")
        ), e.onError({
          name: o?.message || r("ap.apUpload.networkAnomaly"),
          message: o?.message || r("ap.apUpload.networkAnomaly")
        }), m.value--;
      }
    }
    function oe(e) {
      if (T && T?.(e), e.response) {
        if (Array.isArray(i.value)) {
          const t = u.findIndex((n) => n.uid === e.uid);
          t >= 0 && (i?.value.splice(t, 1), u.splice(t, 1)), i.value.length === 0 && (i.value = void 0);
        }
      } else
        e?.oss?.pauseUpload();
      const o = p.findIndex(
        (t) => t.uid === e.uid
      );
      return p.splice(o, 1), Promise.resolve(!0);
    }
    const te = async (e) => {
      if (E.value?.trigger) {
        let o = [e].map((t) => ({
          objectName: t.response,
          fileName: t.name
        }));
        E.value?.trigger?.(o);
      } else {
        const o = e.response?.match(/^([^:]+):(.*)$/), t = o?.[1], n = o?.[2] ?? e.response;
        (await O(
          () => t ? x?.(t) : x?.()
        )).downloadFile([
          {
            path: n,
            fileName: e.name
          }
        ]);
      }
    }, se = (e) => {
      (typeof c == "function" ? c(e) : c) && he.createFilePreviewModal({
        src: e.response,
        fileName: e.name
      });
    }, ae = (e) => (typeof c == "function" ? c(e) : c) ? ["done"].includes(e.status) : !1;
    return (e, o) => (g(), N("div", {
      class: ce({
        [a(j)()]: !0,
        [a($) ?? ""]: !0
      })
    }, [
      h(a(me), {
        ref_key: "uploadRef",
        ref: f,
        accept: a(C),
        multiple: "",
        "max-count": a(l),
        progress: {
          strokeWidth: 3,
          showInfo: !1,
          strokeColor: "#0070FF"
        },
        "before-upload": Z,
        "custom-request": ee,
        "show-upload-list": {
          showDownloadIcon: a(Y),
          showRemoveIcon: !0,
          showPreviewIcon: a(c)
        },
        onPreview: se,
        onRemove: oe,
        onDownload: te
      }, {
        downloadIcon: w(() => [
          h(a(ge), { class: "anticon anticon-vertical-align-bottom" })
        ]),
        itemRender: w(({ originNode: t, file: n }) => [
          h(a(we), null, pe({
            default: w(() => [
              (g(), z(B(t)))
            ]),
            _: 2
          }, [
            ae(n) ? {
              name: "title",
              fn: w(() => [
                M(U(a(r)("ap.apAppendix.previewFile")), 1)
              ]),
              key: "0"
            } : void 0
          ]), 1024)
        ]),
        default: w(() => [
          L("div", Fe, [
            h(a(fe), { class: "file-btn" }, {
              default: w(() => [
                h(a(de)),
                M(" " + U(a(J)), 1)
              ]),
              _: 1
            }),
            L("div", {
              class: "sub-title",
              onClick: o[0] || (o[0] = (t) => t.stopPropagation())
            }, [
              typeof a(v) == "string" ? (g(), N("div", Ae, U(a(v) || `${a(r)("ap.apUpload.supportExtension")}：${a(be)(a(C))}`), 1)) : a(v) ? (g(), N("div", Pe, [
                (g(), z(B(a(v))))
              ])) : ue("", !0)
            ])
          ])
        ]),
        _: 1
      }, 8, ["accept", "max-count", "show-upload-list"])
    ], 2));
  }
});
export {
  We as default
};
