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