import { defineComponent as Po, useSlots as Vo, ref as y, toRef as C, unref as n, computed as s, nextTick as D, watch as U, openBlock as v, createElementBlock as j, normalizeStyle as $, normalizeClass as R, createVNode as zo, mergeProps as q, createSlots as Ko, withCtx as Se, Fragment as Oo, renderList as Go, createBlock as J, resolveDynamicComponent as Lo, renderSlot as he, createCommentVNode as ye, createElementVNode as N } from "vue";
import { AG_GRID_LOCALE_EN as Ho, AG_GRID_LOCALE_CN as Wo } from "@ag-grid-community/locale";
import { Pagination as Uo } from "@aplus-frontend/antdv";
import { useToken as jo } from "@aplus-frontend/antdv/es/theme/internal";
import { ModuleRegistry as $o, ValidationModule as qo, ColumnAutoSizeModule as Jo, PinnedRowModule as Qo, RowAutoHeightModule as Xo, RowStyleModule as Yo, CellSpanModule as Zo, CellStyleModule as _o, TooltipModule as et, RowSelectionModule as ot, LocaleModule as tt, ValueCacheModule as nt, GridStateModule as at, ColumnApiModule as lt, RowApiModule as rt, CellApiModule as st, RenderApiModule as it, EventApiModule as ut, ScrollApiModule as dt, ClientSideRowModelApiModule as ct, ClientSideRowModelModule as mt, RowDragModule as pt } from "ag-grid-community";
import { AgGridVue as ft } from "ag-grid-vue3";
import { isUndefined as F, isFunction as T, omit as gt } from "lodash-unified";
import { DEFAULT_ROW_SELECTION_CONFIG as ve, sizeReverseMap as wt, sizeMap as Ct } from "../ap-grid/constants.mjs";
import { useProvideApTable as St } from "../ap-table/context.mjs";
import { useTablePaging as ht } from "../ap-table/hooks/use-table-paging-ng.mjs";
import { recursionApColumns as yt } from "../ap-table/utils.mjs";
import "../config-provider/index.mjs";
import "../utils/index.mjs";
import { retryUntil as vt } from "../utils/retry.mjs";
import { getValidVNodeList as Rt } from "../utils/slot.mjs";
import { ApForm as bt } from "../ap-form/index.mjs";
import "./components/empty/index.vue.mjs";
import "./components/loading/index.vue.mjs";
import "./components/row/index.vue.mjs";
import { useProvideSorter as xt, useProvideExpandable as Mt, useProvideMaskVisible as kt } from "./context.mjs";
import { useColumns as Ft } from "./hooks/use-columns.mjs";
import { useColumnsDef as Bt } from "./hooks/use-columns-def.mjs";
import { useExportToExcel as It } from "./hooks/use-export-to-excel.mjs";
import { useMask as At } from "./hooks/use-mask.mjs";
import { usePinnedRow as Dt } from "./hooks/use-pinned-row.mjs";
import { useRowDrag as Nt } from "./hooks/use-row-drag.mjs";
import Tt from "./hooks/use-row-selection.mjs";
import { useSearchForm as Et } from "./hooks/use-search-form.mjs";
import Pt from "./hooks/use-selection-col-def.mjs";
import Vt from "./hooks/use-virtual-config.mjs";
import zt from "./style/index.mjs";
import { useTheme as Kt } from "./theme.mjs";
import { runPipelineHooks as Ot, flatColumnConfig as Gt, runEffectHooks as Q, mergeProps as Lt } from "./utils.mjs";
import { useNamespace as Ht } from "../config-provider/hooks/use-namespace.mjs";
import { useLocale as Wt } from "../config-provider/hooks/use-locale.mjs";
import { useGlobalConfig as Ut } from "../config-provider/hooks/use-global-config.mjs";
import { isDef as jt } from "../utils/is.mjs";
import $t from "./components/row/index.vue2.mjs";
import qt from "./components/loading/index.vue2.mjs";
import Jt from "./components/empty/index.vue2.mjs";
const Vn = /* @__PURE__ */ Po({
  name: "AgGrid",
  __name: "index",
  props: {
    dropdownPrefixCls: {},
    bordered: { type: Boolean },
    locale: {},
    onChange: {},
    onResizeColumn: {},
    getPopupContainer: {},
    scroll: {},
    sortDirections: {},
    showSorterTooltip: { type: [Boolean, Object] },
    prefixCls: {},
    rowKey: { type: [String, Function], default: "key" },
    tableLayout: {},
    title: {},
    id: {},
    showHeader: { type: Boolean },
    components: {},
    customHeaderRow: {},
    direction: {},
    expandFixed: { type: [String, Boolean] },
    expandColumnWidth: {},
    expandedRowKeys: {},
    defaultExpandedRowKeys: {},
    expandedRowRender: {},
    expandRowByClick: { type: Boolean },
    expandIcon: {},
    onExpand: {},
    onExpandedRowsChange: {},
    defaultExpandAllRows: { type: Boolean },
    indentSize: {},
    expandIconColumnIndex: {},
    showExpandColumn: { type: Boolean },
    expandedRowClassName: {},
    childrenColumnName: {},
    rowExpandable: {},
    transformCellText: {},
    rowHoverable: { type: Boolean },
    columns: {},
    rowSelection: { type: [Boolean, Object] },
    card: { type: Boolean },
    params: {},
    request: {},
    defaultData: {},
    dataSource: {},
    onLoadingChange: {},
    onShownColumnsChange: {},
    searchForm: { type: [Boolean, Object], default: void 0 },
    beforeSearchSubmit: {},
    pagination: { type: [Boolean, Object], default: void 0 },
    searchFormWrapperStyle: {},
    tableWrapperStyle: {},
    wrapperStyle: {},
    tableStyle: {},
    manual: { type: Boolean, default: void 0 },
    size: { default: "mini" },
    adaptive: { type: Boolean },
    columnResizable: { type: Boolean, default: !1 },
    loading: { type: Boolean, default: void 0 },
    summary: {},
    rowHeight: {},
    getRowHeight: {},
    advanceRenderer: { type: Boolean },
    browserTooltips: { type: Boolean },
    virtual: { type: [Boolean, Object], default: void 0 },
    onRowClicked: {},
    onScrollEnd: {},
    rowClassName: {},
    rowClassRules: {},
    autoHeight: { type: Boolean },
    onUpdate: {},
    onModelUpdated: {},
    customRow: {},
    theme: {},
    emptyComponent: {},
    emptyText: {},
    onColumnResized: {},
    animateRows: { type: Boolean, default: !0 },
    plugins: { default: () => [] },
    rowDrag: {}
  },
  setup(i, { expose: Re }) {
    const be = {
      "zh-cn": Wo,
      en: Ho
    };
    $o.registerModules([
      qo,
      Jo,
      Qo,
      Xo,
      Yo,
      Zo,
      _o,
      et,
      ot,
      tt,
      nt,
      at,
      lt,
      rt,
      st,
      it,
      ut,
      dt,
      ct,
      mt,
      pt
    ]);
    const t = i, E = Vo(), { e: P, b: m, be: xe } = Ht("ag-grid"), { lang: X } = Wt(), Me = zt("ag-grid"), b = y(t.size), ke = Kt(
      b,
      C(t, "rowHeight"),
      C(t, "theme")
    ), Fe = Vt(C(t, "virtual")), { rowPinnedGridConfig: Y, getRowPinnedCellClass: Be } = Dt(
      C(t, "summary")
    ), { rowDragConfig: Ie } = Nt(C(t, "rowDrag")), Z = Ut("agGrid"), r = y(), [, Ae] = jo();
    let x = !!t.dataSource;
    async function V(e, o = {}) {
      const a = await Ot(
        t.plugins,
        e,
        (l) => l.beforeApplyColumnState?.bind(l)
      );
      r.value.applyColumnState({ state: a, ...o });
    }
    const _ = Et(t), {
      shownColumns: g,
      columns: ee,
      columnKeys: De,
      getTargetColumnByKey: Ne,
      defaultSortOrder: B,
      getColKeys: Te,
      awaitedColumns: Ee
    } = Ft(t), { defaultColDef: Pe, columnDefs: oe, gridWrapperRef: Ve } = Bt(
      ee,
      t,
      Be,
      E.headerCell
    ), ze = {
      asc: "ascend",
      desc: "descend"
    }, te = {
      ascend: "asc",
      descend: "desc"
    };
    function Ke() {
      const e = B.value;
      return e ? {
        [e.colKey]: te[e.order]
      } : {};
    }
    function Oe() {
      const e = ne.value, o = B.value;
      if (o && e.includes(o.field))
        return o;
    }
    const I = y(Ke());
    xt({
      sorter: I,
      setSorter(e) {
        I.value = e;
      }
    });
    function Ge() {
      const e = r.value.getColumns()?.filter((f) => f.getSort() != null), o = n(I) || {};
      let a = e?.[0];
      const l = Object.keys(o);
      if (l.length && l.every((f) => o[f] === null)) {
        const f = Object.keys(o)[0];
        f && (a = r.value?.getColumn(f));
      }
      if (!a)
        return;
      const c = a.getColDef(), p = a.getSort(), M = Ne(c.colId);
      re(void 0, void 0, {
        column: c,
        field: M?.field ?? c.field ?? c.colId,
        order: p ? ze[p] : null
      });
    }
    const ne = s(() => {
      const e = n(g).length ? n(g) : t.columns;
      return yt(e, (o) => {
        if (o.sorter === !0)
          return o.field ?? o.dataIndex ?? o.key;
      }).filter(Boolean);
    }), Le = () => {
      I.value = {};
      const e = r.value;
      if (!e)
        return;
      const o = e.getColumnState()?.map((a) => ({ ...a, sort: null }));
      V(o);
    }, z = y({});
    Mt({ expandable: z });
    function He(e) {
      const o = e.columnGroup;
      o && (z.value = {
        ...z.value,
        [o.getGroupId()]: o.isExpanded()
      });
    }
    const { masks: ae, setMaskVisible: We } = At(C(t, "columns"), r);
    kt({ masks: ae, setMaskVisible: We });
    const K = y(!0), Ue = s(() => jt(t.manual) ? t.manual : Rt(E.searchFormExtra?.() || []).some((o) => o.type?.name === "ApView")), {
      formRef: S,
      submit: O,
      reset: G,
      data: w,
      tableProps: le,
      handleTableChangeOptional: re,
      submitWith: se,
      refresh: ie,
      getPaging: je,
      setPaging: $e,
      setDataSource: qe,
      getLastParams: Je
    } = ht({
      async request(e) {
        if (x = !1, h.value && !h.value.preserveSelectedRowKeys && F(t.dataSource) && !K.value && W(), K.value && (K.value = !1), !F(t.dataSource)) {
          const a = e.pageSize * (e.current - 1);
          return {
            data: (t.pagination === !1 ? t.dataSource : t.dataSource.slice(a, a + e.pageSize)) || [],
            total: t.dataSource.length || 0
          };
        }
        const o = await t.request?.(e);
        return {
          data: o?.data || [],
          total: o?.total || 0
        };
      },
      namespace: "ap-grid",
      filterFields: y([]),
      params: C(t, "params"),
      defaultData: t.defaultData,
      manual: n(Ue),
      formatParams: t.beforeSearchSubmit,
      pagination: t.pagination,
      sortFields: ne,
      onClickReset: Le,
      defaultSortOrder: Oe()
    }), Qe = s(() => ({ masks: ae.value })), h = s(() => {
      const e = t.rowSelection || Z.value?.rowSelection;
      if (e)
        return e === !0 ? ve : {
          ...ve,
          ...e
        };
    }), Xe = Pt(t, g), ue = s(
      () => F(t.dataSource) ? w.records : t.dataSource
    ), {
      select: Ye,
      unSelect: Ze,
      selectedRows: L,
      selectedRowKeys: _e,
      clearAll: eo,
      selectMultiByKeys: oo,
      selectMulti: to,
      unSelectMulti: no
    } = Tt({
      ...h.value,
      dataSource: ue,
      rowKey: t.rowKey
    }), ao = {
      checkbox: "multiRow",
      radio: "singleRow"
    }, lo = s(() => {
      const e = h.value;
      if (!e)
        return;
      const { type: o = "checkbox", disabled: a } = e;
      return {
        mode: ao[o],
        isRowSelectable: (l) => a ? !a(l.data) : !0,
        hideDisabledCheckboxes: e.hideDisabled ?? !1
      };
    });
    function H(e) {
      return T(t.rowKey) ? t.rowKey(e) : e[t.rowKey];
    }
    const A = ({
      api: e = r.value
    }) => {
      if (t.onUpdate?.(), !h.value)
        return;
      const o = L.value || [];
      x = !1;
      const a = [];
      e.forEachNode((l) => {
        const d = l.data, c = H(d), p = l.isSelected();
        o.find((M) => H(M) === c) ? !p && a.push(l) : p && l.setSelected(!1);
      }), e.setNodesSelected({ nodes: a, newValue: !0 }), setTimeout(() => {
        x = !0;
      }, 0);
    }, ro = (e) => {
      x && (e.node.isSelected() ? Ye(e.data) : Ze(e.data), T(h.value?.tooltip) && e.api.refreshCells({
        rowNodes: [e.node],
        // todo: 取消硬编码
        columns: ["ag-Grid-SelectionColumn"],
        force: !0
      }));
    }, so = () => {
      x = !0;
      const e = r.value;
      if (!e || !B.value)
        return;
      const o = e.getColumnState(), { colKey: a, order: l } = B.value, d = o.map((c) => ({
        ...c,
        sort: c.colId === a ? te[l] : null
      }));
      V(d);
    }, W = () => {
      eo(), r.value?.deselectAll();
    };
    function io(e) {
      oo(e), D(() => {
        A({});
      });
    }
    const uo = s(() => {
      const e = t.customRow;
      return e ? {
        isFullWidthRow: e.isCustomRow,
        fullWidthCellRenderer: $t,
        fullWidthCellRendererParams: {
          render: e.render
        }
      } : {};
    });
    function co(e) {
      to(e), D(() => {
        A({});
      });
    }
    function mo(e) {
      no(e), D(() => {
        A({});
      });
    }
    function de(e = !1) {
      const o = e ? "getFieldsValueTransformed" : "getFieldsValue";
      return S.value?.apForm?.[o]?.(!0);
    }
    function ce(e) {
      S.value?.apForm?.setFieldsValue?.(e);
    }
    function me() {
      return S.value?.getSorterItems() || [];
    }
    function pe(e) {
      S.value?.setSorterItems(e);
    }
    function fe() {
      S.value?.resetSorterItems();
    }
    function ge(e) {
      return e && String(e);
    }
    function po(e) {
      const o = r.value;
      if (!o)
        return;
      const a = Gt(e), l = o.getColumnState() || [], d = Te(a), c = l.map((u) => {
        if (!De.value.includes(u.colId))
          return u;
        const k = !d.includes(u.colId), we = {
          ...u,
          hide: k
        }, Ce = a.find(
          (Eo) => ge(Eo.key) === u.colId
        );
        return Ce && (we.pinned = Ce.fixed || null), we;
      }), p = new Map(
        a.map((u, k) => [ge(u.key), k])
      ), M = c.filter((u) => p.has(u.colId)).sort(
        (u, k) => p.get(u.colId) - p.get(k.colId)
      ), f = [];
      let To = 0;
      for (const u of c)
        p.has(u.colId) ? f.push(M[To++]) : f.push(u);
      V(f, { applyOrder: !0 });
    }
    St({
      columns: s(() => g.value),
      columnsBackup: s(() => ee.value),
      awaitedColumns: Ee,
      size: s(() => Ct[b.value]),
      updateColumns(e) {
        g.value = e, t.onShownColumnsChange?.(e), vt(
          () => r.value?.getColumns(),
          () => {
            po(e);
          },
          {
            interval: 17,
            check: (o) => !!(o && o.length > 0)
          }
        );
      },
      updateSize(e) {
        b.value = wt[e];
      },
      renderConfig: s(() => ({
        className: xe("table-header", "title"),
        color: Ae.value.colorTextTertiary
      })),
      dataSource: s(() => n(w).records),
      getSearchFormValues: de,
      setSearchFormValues: ce,
      submit: O,
      submitWith: se,
      reset: G,
      refresh: ie,
      getSearchFormSorterItems: me,
      setSearchFormSorterItems: pe,
      resetSearchFormSorterItems: fe,
      getLastParams: Je
    });
    const { exportToExcel: fo } = It(g, ue), go = s(() => (F(t.loading) ? w.loading : t.loading) || oe.value.length === 0), wo = s(() => [
      m(),
      t.card ? null : m("wrapper"),
      m("adaptive"),
      m(`size-${b.value}`),
      t.autoHeight && w.records.length ? m("auto-height") : null,
      Me.value,
      t.theme?.wrapperBorder ? null : m("borderless")
    ].filter(Boolean)), Co = s(() => ({
      height: "100%",
      ...t.tableStyle || {}
    })), So = (e, o) => {
      re({ current: e, pageSize: o });
    };
    function ho(e) {
      const o = e.data;
      return H(o);
    }
    function yo(e, o) {
      (T(e) ? r.value?.ensureNodeVisible : r.value?.ensureIndexVisible)?.(e, o);
    }
    function vo(e, o) {
      r.value?.ensureColumnVisible(e, o);
    }
    function Ro(e) {
      t.onRowClicked?.(e.data, e.event);
    }
    function bo(e) {
      t.onScrollEnd?.(e.direction);
    }
    function xo(e) {
      return r.value?.refreshCells(e);
    }
    function Mo(e) {
      return r.value?.redrawRows(e);
    }
    function ko({
      finished: e,
      columns: o,
      source: a
    }) {
      if (!e || a !== "uiColumnResized")
        return;
      const l = (o || []).map((d) => ({
        key: d.getColId(),
        width: d.getActualWidth()
      }));
      Q(t.plugins, (d) => d.onColumnResized?.bind(d), l), t.onColumnResized?.(l);
    }
    const Fo = (e) => {
      const o = [
        Y.value.getRowClass?.(e)
      ];
      if (!e.node.rowPinned) {
        const a = T(t.rowClassName) ? t.rowClassName(e.data, e.rowIndex) : t.rowClassName;
        o.push(a);
      }
      return o.flat().filter(Boolean);
    }, Bo = ({ api: e }) => {
      r.value = e, Q(t.plugins, (o) => o.init?.bind(o), e);
    }, Io = ({ api: e }) => {
      t.onModelUpdated?.(e), Z.value?.onModelUpdated?.(e);
    }, Ao = (e, o, a) => {
      Q(
        t.plugins,
        (l) => l.searchParamsChange?.bind(this),
        o
      ), t.searchForm && t.searchForm.onValuesChange?.(e, o, a);
    }, Do = (e, o, a) => {
      if (!r.value)
        return;
      r.value.getRowNode(e)?.setDataValue(o, a);
    }, No = (e, o, a = "update") => {
      if (!r.value)
        return;
      const l = r.value.getRowNode(e);
      (a === "update" ? l?.updateData : l?.setData)?.bind(l)?.(o);
    };
    return U(
      () => t.dataSource,
      (e) => {
        D(() => {
          qe(e, !0);
        });
      },
      { immediate: !0, deep: !0 }
    ), U(
      () => t.size,
      (e) => {
        b.value = e;
      }
    ), U(
      () => n(w).loading,
      (e) => {
        t.onLoadingChange?.(e);
      }
    ), Re({
      submit: O,
      reset: G,
      refresh: ie,
      submitWith: se,
      setSearchFormValues: ce,
      getSearchFormValues: de,
      getShowColumns: () => n(g),
      rowSelection: {
        selectedRows: s(() => L.value),
        setSelectedRowKeys: io,
        setSelectedRows: co,
        clearAll: W,
        unSelectRows: mo
      },
      scrollToRow: yo,
      scrollToColumn: vo,
      getDataSource: () => n(w.records),
      getPaging: je,
      setPaging: $e,
      getSearchFormSorterItems: me,
      setSearchFormSorterItems: pe,
      resetSearchFormSorterItems: fe,
      refreshCells: xo,
      redrawRows: Mo,
      _internalGridApi: s(() => r.value),
      updateCell: Do,
      updateRow: No,
      exportToExcel: fo
    }), (e, o) => (v(), j("div", {
      class: R(wo.value),
      style: $(i.wrapperStyle)
    }, [
      n(F)(i.dataSource) && i.searchForm !== !1 && n(_).length > 0 ? (v(), j("div", {
        key: 0,
        class: R(i.card ? n(P)("search-wrapper") : null),
        style: $(i.searchFormWrapperStyle)
      }, [
        zo(n(bt).SearchForm, q(n(gt)(i.searchForm || {}, ["onValuesChange"]), {
          ref_key: "formRef",
          ref: S,
          "custom-reset": "",
          "submit-loading": n(le).loading,
          onSubmit: n(O),
          onReset: n(G),
          onValuesChange: Ao
        }), Ko({
          default: Se(() => [
            (v(!0), j(Oo, null, Go(n(_), (a) => (v(), J(Lo(a.renderNode), {
              key: a.dataIndex
            }))), 128))
          ]),
          _: 2
        }, [
          E.searchFormExtra ? {
            name: "extra",
            fn: Se(() => [
              he(e.$slots, "searchFormExtra")
            ]),
            key: "0"
          } : void 0
        ]), 1040, ["submit-loading", "onSubmit", "onReset"])
      ], 6)) : ye("", !0),
      N("div", {
        class: R([n(P)("table-wrapper"), i.card ? n(P)("table-wrapper-card") : null]),
        style: $(i.tableWrapperStyle)
      }, [
        N("div", {
          class: R(n(m)("header-wrapper"))
        }, [
          he(e.$slots, "title", {
            selectedRows: n(L),
            selectedRowKeys: n(_e),
            shownColumns: n(g),
            clearAll: W
          })
        ], 2),
        N("div", {
          ref_key: "gridWrapperRef",
          ref: Ve,
          class: R(n(m)("grid-wrapper"))
        }, [
          (v(), J(n(ft), q(
            n(Lt)(
              n(Fe),
              n(Y),
              uo.value,
              n(Ie)
            ),
            {
              key: n(X),
              "animate-rows": i.animateRows,
              "get-row-class": Fo,
              style: Co.value,
              "row-data": n(w).records,
              "column-defs": n(oe),
              "default-col-def": n(Pe),
              "suppress-loading-overlay": "",
              "row-selection": lo.value,
              "selection-column-def": n(Xe),
              "get-row-id": ho,
              "get-row-height": t.getRowHeight,
              theme: n(ke),
              "tooltip-show-delay": 500,
              "enable-browser-tooltips": i.browserTooltips,
              "tooltip-interaction": "",
              "row-class-rules": i.rowClassRules,
              "no-rows-overlay-component": Jt,
              "no-rows-overlay-component-params": { emptyComponent: i.emptyComponent, emptyText: i.emptyText },
              "loading-overlay-component": qt,
              loading: go.value,
              "suppress-cell-focus": "",
              "tab-to-next-cell": () => !1,
              "enable-cell-span": "",
              "dom-layout": i.autoHeight ? "autoHeight" : "normal",
              "locale-text": be[n(X)],
              context: Qe.value,
              onSortChanged: Ge,
              onGridReady: Bo,
              onRowDataUpdated: A,
              onRowSelected: ro,
              onFirstDataRendered: so,
              onRowClicked: Ro,
              onBodyScrollEnd: bo,
              onColumnResized: ko,
              onColumnGroupOpened: He,
              onModelUpdated: Io
            }
          ), null, 16, ["animate-rows", "style", "row-data", "column-defs", "default-col-def", "row-selection", "selection-column-def", "get-row-height", "theme", "enable-browser-tooltips", "row-class-rules", "no-rows-overlay-component-params", "loading", "dom-layout", "locale-text", "context"]))
        ], 2),
        N("div", {
          class: R(n(m)("pagination-wrapper"))
        }, [
          i.pagination !== !1 ? (v(), J(n(Uo), q({
            key: 0,
            class: n(m)("pagination")
          }, n(le).pagination, { onChange: So }), null, 16, ["class"])) : ye("", !0)
        ], 2)
      ], 6)
    ], 6));
  }
});
export {
  Vn as default
};
