import { defineComponent as se, ref as L, computed as x, useTemplateRef as ie, watch as ue, toRaw as de, onMounted as ce, onUnmounted as fe, openBlock as R, createBlock as ge, unref as D, withCtx as me, createElementVNode as pe, normalizeStyle as U, normalizeClass as V, createElementBlock as j, Fragment as ve, renderList as he, renderSlot as we } from "vue";
import { Spin as ye } from "@aplus-frontend/antdv";
import { warning as K, note as w } from "../../utils/warning.mjs";
import "../../config-provider/index.mjs";
import { ApDraggableGridProps as be } from "./constans.mjs";
import $e from "./style/index.mjs";
import { sortItemsByRowAndCol as E } from "./utils/sortItemsByRowAndCol.mjs";
import { useNamespace as De } from "../../config-provider/hooks/use-namespace.mjs";
const Ee = ["data-span", "data-index", "data-row", "data-col", "data-height", "data-module", "draggable"], He = /* @__PURE__ */ se({
  __name: "ApDraggableGrid",
  props: be(),
  emits: ["onGridListChange"],
  setup(Q, { expose: X, emit: Y }) {
    const d = Q, { b: O, e: C, m: Z } = De("ap-draggable-grid"), ee = $e("ap-draggable-grid"), G = L(!1), P = L(!1), W = x(() => C("item")), k = x(() => C("dragging")), H = x(() => C("overlay")), re = x(() => d.customWrapper ? `.${d.customWrapper} .${W.value}:not(.${k.value})` : `.${W.value}:not(.${k.value})`), te = Y, f = ie("gridContainer"), S = L([]);
    ue(
      () => d.gridList,
      (e) => {
        Array.isArray(e) && s(e);
      },
      { deep: !0, immediate: !0 }
    );
    function s(e) {
      const a = [...e].sort((r, i) => r.row - i.row);
      S.value = a.map((r) => ({
        ...r
      })), te(
        "onGridListChange",
        JSON.parse(JSON.stringify(S.value))
      );
    }
    const ae = (e) => ({
      gridColumn: `${e.col} / span ${e.span}`,
      gridRow: e.row,
      minHeight: e.showHeight ? e.showHeight + "px" : `${d.gridItemHeight}px`,
      height: e.showHeight ? e.showHeight + "px" : `${d.gridItemHeight}px`,
      boxShadow: d.gridItemShadow ? d.gridItemShadow : "none"
    });
    async function J() {
      if (s([]), typeof d.request == "function")
        try {
          G.value = !0;
          const e = await d.request();
          Array.isArray(e) && s(e), K(
            Array.isArray(e),
            "ApDraggableGrid: 请求函数必须返回一个符合 ApDraggableGridItemBase 数组的格式"
          );
        } catch (e) {
          K(!1, `ApDraggableGrid: 请求错误: ${e}`);
        } finally {
          G.value = !1;
        }
    }
    let I = L(null), N = L(null), v = null, M = !1, y = null;
    const q = (e) => {
      if (!M && (M = !0, e.dataTransfer && e.target instanceof HTMLElement)) {
        const a = e.target.dataset;
        e.dataTransfer.setData("text/plain", a.module), e.dataTransfer.effectAllowed = "move", I.value = {
          span: Number(a.span),
          col: Number(a.col),
          row: Number(a.row),
          module: a.module,
          height: Number(a.height),
          index: Number(a.index)
        }, v = e.target, v.style.opacity = "0";
      }
    }, B = (e) => {
      if (e.preventDefault(), y && clearTimeout(y), y = window.setTimeout(() => {
        M = !1, y = null;
      }, 300), e.dataTransfer && e.target instanceof HTMLElement) {
        const a = e.target.closest(
          re.value
        );
        if (!a) return;
        const r = a.dataset;
        document.querySelectorAll(
          `.${d.customWrapper} div[data-row="${r.row}"]`
        ).forEach((l) => {
          l.classList.add(H.value);
        }), N.value = {
          span: Number(r.span),
          col: Number(r.col),
          row: Number(r.row),
          module: r.module,
          height: Number(r.height),
          index: Number(r.index)
        };
      }
    }, _ = (e) => {
      e.preventDefault(), v && (v.style.opacity = "1", v = null), oe(I, N) && ne(I, N), document.querySelectorAll(`.${H.value}`).forEach((a) => {
        a.classList.remove(H.value);
      }), I.value = null, N.value = null, P.value = !1;
    }, z = () => {
      v && (v.style.opacity = "1", v = null), I.value = null, N.value = null, P.value = !1;
    }, oe = (e, a) => {
      const { span: r, module: i } = e.value, { span: l, module: c } = a.value;
      return !(i === c && r === l);
    }, ne = (e, a) => {
      if (!e.value || !a.value) return;
      const {
        span: r,
        col: i,
        row: l,
        module: c,
        height: T,
        index: u
      } = e.value, {
        span: $,
        col: h,
        row: m,
        module: le,
        height: F,
        index: g
      } = a.value;
      if (l === m && i === h && r === $ && T === F && c === le)
        return;
      let t = [...de(S.value)];
      const A = JSON.parse(JSON.stringify(t));
      if (l === m)
        if (u > g) {
          u - g === 1 ? (t[g].col = r + h, t[u].col = h) : (t.forEach((p, o) => {
            o < u && o >= g && (p.col += $);
          }), t[u].col = h);
          const n = E(t);
          if (!b(n)) {
            w(!1, "交换后的布局无效，恢复原始布局");
            return;
          }
          s(n);
          return;
        } else {
          g - u === 1 ? (t[u].col = $ + 1, t[g].col = i) : (t.forEach((p, o) => {
            o > u && o <= g && (p.col -= $);
          }), t[u].col = h);
          const n = E(t);
          if (!b(n)) {
            s(A);
            return;
          }
          s(n);
          return;
        }
      else if (m < l) {
        if (r === 24) {
          const n = [];
          for (let o = m; o < l; o++)
            n.push(o);
          t.forEach((o) => {
            n.includes(o.row) && (o.row += 1);
          }), t[u].row = m;
          const p = E(t);
          if (!b(p)) {
            w(!1, "交换后的布局无效，恢复原始布局"), s(A);
            return;
          }
          s(p);
          return;
        }
        if (r === $ && T === F) {
          t[u].row = m, t[u].col = h, t[g].row = l, t[g].col = i;
          const n = E(t);
          if (!b(n)) {
            w(!1, "交换后的布局无效，恢复原始布局"), s(A);
            return;
          }
          s(n);
          return;
        }
      } else {
        if (r === 24) {
          const n = [];
          for (let o = l + 1; o <= m; o++)
            n.push(o);
          t.forEach((o) => {
            n.includes(o.row) && (o.row -= 1);
          }), t[u].row = m;
          const p = E(t);
          if (!b(p)) {
            w(!1, "交换后的布局无效，恢复原始布局"), s(A);
            return;
          }
          s(p);
          return;
        }
        if (r === $ && T === F) {
          t[u].row = m, t[u].col = h, t[g].row = l, t[g].col = i;
          const n = E(t);
          if (!b(n)) {
            w(!1, "交换后的布局无效，恢复原始布局"), s(A);
            return;
          }
          s(n);
          return;
        }
      }
    }, b = (e) => {
      const a = {};
      e.forEach((r) => {
        a[r.row] || (a[r.row] = []), a[r.row].push(r);
      });
      for (const r in a) {
        const i = a[r].sort((c, T) => c.col - T.col);
        let l = 1;
        for (const c of i) {
          if (c.col < l)
            return w(
              !1,
              `行 ${r} 中的元素重叠: 元素 ${c.module} 在列 ${c.col}, 但当前列已经是 ${l}`
            ), !1;
          if (l = c.col + c.span, l > 25)
            return w(
              !1,
              `行 ${r} 中的元素超出界限: 元素 ${c.module} 在列 ${c.col} 跨度 ${c.span}`
            ), !1;
        }
      }
      return !0;
    };
    return ce(async () => {
      await J(), !d.disableDrag && f.value && (f.value.addEventListener("dragstart", q), f.value.addEventListener("dragover", B), f.value.addEventListener("drop", _), f.value.addEventListener("dragend", z));
    }), fe(() => {
      f.value && (f.value.removeEventListener("dragstart", q), f.value.removeEventListener("dragover", B), f.value.removeEventListener("drop", _), f.value.removeEventListener("dragend", z), y && clearTimeout(y));
    }), X({
      setGridItems: (e) => {
        s(e);
      },
      getGridItems: () => JSON.parse(JSON.stringify(S.value)),
      refreshGrid: () => {
        (async () => await J())();
      }
    }), (e, a) => (R(), ge(D(ye), { spinning: G.value }, {
      default: me(() => [
        pe("div", {
          ref_key: "gridContainer",
          ref: f,
          class: V([G.value ? D(O)("loading") : D(O)(), d.customWrapper, D(ee)]),
          style: U({
            width: typeof e.gridWidth == "number" ? `${e.gridWidth}px` : e.gridWidth,
            gap: `${e.gapWidth}px`
          })
        }, [
          (R(!0), j(ve, null, he(S.value, (r, i) => (R(), j("div", {
            key: i,
            class: V([D(C)("item"), d.disableDrag ? "" : D(Z)("canDrag")]),
            "data-span": r.span,
            "data-index": i,
            "data-row": r.row,
            "data-col": r.col,
            "data-height": r.height,
            "data-module": r.module,
            style: U([ae(r)]),
            draggable: !d.disableDrag
          }, [
            we(e.$slots, "item", {
              item: r,
              index: i
            })
          ], 14, Ee))), 128))
        ], 6)
      ]),
      _: 3
    }, 8, ["spinning"]));
  }
});
export {
  He as default
};
