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