import { Modal as S } from "@aplus-frontend/antdv";
import { isValid as _ } from "@aplus-frontend/utils";
import { ModalMessage as u } from "../enums/modalMessage.mjs";
import { createModal as h } from "./createModal.mjs";
const A = (M, g) => {
  const E = g ?? (Array.isArray(M) ? M[0]?.modalId : void 0), a = /* @__PURE__ */ new Map();
  let x, y, p = 1e3;
  const m = async ({
    modalId: s,
    params: l,
    handleCurrentModal: f,
    handleModal: O
  } = {}) => {
    if (!_(s)) {
      d();
      return;
    }
    x = l;
    const c = M.find((t) => t.modalId === s);
    let i = !1;
    if (y) {
      const t = a.get(y), n = {
        ...t,
        destroy: () => {
          t?.destroy?.(), a.delete(y);
        },
        open: () => {
          i = !0;
        }
      };
      await f?.(n), await O?.({
        getModal: (e) => {
          const r = a.get(e);
          return r ? {
            ...r,
            destroy: () => {
              r?.destroy?.(), a.delete(e);
            }
          } : void 0;
        }
      });
    }
    return c && setTimeout(() => {
      C(c);
    }), i;
  }, d = () => {
    for (const [s, l] of a)
      l?.destroy?.();
  }, C = async (s) => {
    const {
      modalId: l,
      modalType: f = "createModal",
      props: O
    } = s;
    y = l;
    const c = a.get(l), i = await O?.(x, async (e) => (n = !0, await m(e)));
    p = Math.max(i?.zIndex ?? 0, p), p += 1;
    let t, n = !1;
    if (f === "createModal") {
      const e = i, r = async (o) => (n = !0, await m(o));
      t = {
        ...e,
        destroyOnClose: !1,
        zIndex: p,
        onOk: async (o) => {
          const w = await e?.onOk?.(o, r);
          if (n || d(), w)
            throw new Error(u.NOT_NEED_CLOSE);
        },
        onCancel: async (o) => {
          const w = await e?.onCancel?.(o, r);
          if (n || d(), w)
            throw new Error(u.NOT_NEED_CLOSE);
        }
      };
    } else {
      const e = i, r = async (o) => (n = !0, await m(o));
      t = {
        ...e,
        zIndex: p,
        onOk: async () => {
          const o = await e?.onOk?.(r);
          if (n || d(), o)
            throw new Error(u.NOT_NEED_CLOSE);
        },
        onCancel: async () => {
          const o = await e?.onCancel?.(r);
          if (n || d(), o)
            throw new Error(u.NOT_NEED_CLOSE);
        }
      };
    }
    if (c) {
      c?.update(t), c?.open?.();
      return;
    } else if (f === "createModal") {
      const e = h(t);
      e?.open?.(), a.set(l, e);
    } else
      S?.[f]?.(t);
  }, N = M.find((s) => _(E) && s.modalId === E);
  if (N !== void 0)
    return C(N), {
      getModal: a.get.bind(a),
      clearAllModal: d,
      next: m
    };
};
export {
  A as createModalStream
};
