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