import { defineComponent as Ao, useSlots as To, ref as S, toRef as F, unref as n, computed as s, watch as E, nextTick as N, openBlock as v, createElementBlock as $, normalizeStyle as q, normalizeClass as R, createVNode as Eo, mergeProps as J, createSlots as No, withCtx as Ce, Fragment as Do, renderList as Po, createBlock as Q, resolveDynamicComponent as Vo, renderSlot as Se, createCommentVNode as he, createElementVNode as D } from "vue";
import { AG_GRID_LOCALE_EN as zo, AG_GRID_LOCALE_CN as Ko } from "@ag-grid-community/locale";
import { Pagination as Oo } from "@aplus-frontend/antdv";
import { useToken as Go } from "@aplus-frontend/antdv/es/theme/internal";
import { ModuleRegistry as Lo, ValidationModule as Ho, ColumnAutoSizeModule as Wo, PinnedRowModule as Uo, RowAutoHeightModule as jo, RowStyleModule as $o, CellSpanModule as qo, CellStyleModule as Jo, TooltipModule as Qo, RowSelectionModule as Xo, LocaleModule as Yo, ValueCacheModule as Zo, GridStateModule as _o, ColumnApiModule as et, RowApiModule as ot, CellApiModule as tt, RenderApiModule as nt, EventApiModule as lt, ScrollApiModule as at, ClientSideRowModelApiModule as rt, ClientSideRowModelModule as st } from "ag-grid-community";
import { AgGridVue as it } from "ag-grid-vue3";
import { isUndefined as B, isFunction as P, omit as ut } from "lodash-unified";
import { DEFAULT_ROW_SELECTION_CONFIG as ye, sizeReverseMap as dt, sizeMap as ct } from "../ap-grid/constants.mjs";
import { useProvideApTable as mt } from "../ap-table/context.mjs";
import { useTablePaging as pt } from "../ap-table/hooks/use-table-paging-ng.mjs";
import { recursionApColumns as ft } from "../ap-table/utils.mjs";
import "../config-provider/index.mjs";
import "../utils/index.mjs";
import { retryUntil as gt } from "../utils/retry.mjs";
import { getValidVNodeList as wt } from "../utils/slot.mjs";
import { ApForm as Ct } 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 St, useProvideExpandable as ht, useProvideMaskVisible as yt } from "./context.mjs";
import { useColumns as vt } from "./hooks/use-columns.mjs";
import { useColumnsDef as Rt } from "./hooks/use-columns-def.mjs";
import { usePinnedRow as bt } from "./hooks/use-pinned-row.mjs";
import xt from "./hooks/use-row-selection.mjs";
import { useSearchForm as Mt } from "./hooks/use-search-form.mjs";
import kt from "./hooks/use-selection-col-def.mjs";
import Ft from "./hooks/use-virtual-config.mjs";
import Bt from "./style/index.mjs";
import { useTheme as It } from "./theme.mjs";
import { runPipelineHooks as At, pickColumnConfig as Tt, runEffectHooks as X, mergeProps as Et } from "./utils.mjs";
import { useNamespace as Nt } from "../config-provider/hooks/use-namespace.mjs";
import { useLocale as Dt } from "../config-provider/hooks/use-locale.mjs";
import { useGlobalConfig as Pt } from "../config-provider/hooks/use-global-config.mjs";
import { isDef as Vt } from "../utils/is.mjs";
import zt from "./components/row/index.vue2.mjs";
import Kt from "./components/loading/index.vue2.mjs";
import Ot from "./components/empty/index.vue2.mjs";
const xn = /* @__PURE__ */ Ao({
  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": Ko,
      en: zo
    };
    Lo.registerModules([
      Ho,
      Wo,
      Uo,
      jo,
      $o,
      qo,
      Jo,
      Qo,
      Xo,
      Yo,
      Zo,
      _o,
      et,
      ot,
      tt,
      nt,
      lt,
      at,
      rt,
      st
    ]);
    const t = i, V = To(), { e: z, b: m, be } = Nt("ag-grid"), { lang: Y } = Dt(), xe = Bt("ag-grid"), b = S(t.size), Me = It(
      b,
      F(t, "rowHeight"),
      F(t, "theme")
    ), ke = Ft(F(t, "virtual")), { rowPinnedGridConfig: Z, getRowPinnedCellClass: Fe } = bt(
      F(t, "summary")
    ), _ = Pt("agGrid"), r = S(), [, Be] = Go();
    let x = !!t.dataSource;
    async function K(e, o = {}) {
      const l = await At(
        t.plugins,
        e,
        (a) => a.beforeApplyColumnState?.bind(a)
      );
      r.value.applyColumnState({ state: l, ...o });
    }
    const ee = Mt(t), {
      shownColumns: f,
      columns: oe,
      columnKeys: Ie,
      getTargetColumnByKey: Ae,
      defaultSortOrder: I,
      getColKeys: Te,
      awaitedColumns: Ee
    } = vt(t), { defaultColDef: Ne, columnDefs: te, gridWrapperRef: De } = Rt(
      oe,
      t,
      Fe,
      V.headerCell
    ), Pe = {
      asc: "ascend",
      desc: "descend"
    }, ne = {
      ascend: "asc",
      descend: "desc"
    };
    function Ve() {
      const e = I.value;
      return e ? {
        [e.colKey]: ne[e.order]
      } : {};
    }
    function ze() {
      const e = le.value, o = I.value;
      if (o && e.includes(o.field))
        return o;
    }
    const A = S(Ve());
    St({
      sorter: A,
      setSorter(e) {
        A.value = e;
      }
    });
    function Ke() {
      const e = r.value.getColumns()?.filter((p) => p.getSort() != null), o = n(A) || {};
      let l = e?.[0];
      const a = Object.keys(o);
      if (a.length && a.every((p) => o[p] === null)) {
        const p = Object.keys(o)[0];
        p && (l = r.value?.getColumn(p));
      }
      if (!l)
        return;
      const u = l.getColDef(), w = l.getSort(), C = Ae(u.colId);
      re(void 0, void 0, {
        column: u,
        field: C?.field ?? u.field ?? u.colId,
        order: w ? Pe[w] : null
      });
    }
    const le = s(() => {
      const e = n(f).length ? n(f) : t.columns;
      return ft(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((l) => ({ ...l, sort: null }));
      K(o);
    }, O = S({});
    ht({ expandable: O });
    function Ge(e) {
      const o = e.columnGroup;
      o && (O.value = {
        ...O.value,
        [o.getGroupId()]: o.isExpanded()
      });
    }
    const M = S({});
    E(
      () => t.columns,
      (e) => {
        const l = {
          ...Tt(
            e,
            "defaultMaskVisible",
            !1
          ),
          ...M.value
        };
        M.value = l;
      },
      {
        immediate: !0
      }
    );
    function Le(e, o) {
      M.value[e] = o, r.value && r.value?.refreshCells({ columns: [e], force: !0 });
    }
    yt({ masks: M, setMaskVisible: Le });
    const G = S(!0), He = s(() => Vt(t.manual) ? t.manual : wt(V.searchFormExtra?.() || []).some((o) => o.type?.name === "ApView")), {
      formRef: h,
      submit: L,
      reset: H,
      data: g,
      tableProps: ae,
      handleTableChangeOptional: re,
      submitWith: se,
      refresh: ie,
      getPaging: We,
      setPaging: Ue,
      setDataSource: je,
      getLastParams: $e
    } = pt({
      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 l = e.pageSize * (e.current - 1);
          return {
            data: (t.pagination === !1 ? t.dataSource : t.dataSource.slice(l, l + 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: le,
      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 = kt(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
    } = xt({
      ...y.value,
      dataSource: Qe,
      rowKey: t.rowKey
    }), no = {
      checkbox: "multiRow",
      radio: "singleRow"
    }, lo = s(() => {
      const e = y.value;
      if (!e)
        return;
      const { type: o = "checkbox", disabled: l } = e;
      return {
        mode: no[o],
        isRowSelectable: (a) => l ? !l(a.data) : !0,
        hideDisabledCheckboxes: e.hideDisabled ?? !1
      };
    });
    function U(e) {
      return P(t.rowKey) ? t.rowKey(e) : e[t.rowKey];
    }
    const T = ({
      api: e = r.value
    }) => {
      if (t.onUpdate?.(), !y.value)
        return;
      const o = W.value || [];
      x = !1;
      const l = [];
      e.forEachNode((a) => {
        const c = a.data, u = U(c), w = a.isSelected();
        o.find((C) => U(C) === u) ? !w && l.push(a) : w && a.setSelected(!1);
      }), e.setNodesSelected({ nodes: l, newValue: !0 }), setTimeout(() => {
        x = !0;
      }, 0);
    }, ao = (e) => {
      x && (e.node.isSelected() ? Xe(e.data) : Ye(e.data), P(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: l, order: a } = I.value, c = o.map((u) => ({
        ...u,
        sort: u.colId === l ? ne[a] : null
      }));
      K(c);
    }, j = () => {
      _e(), r.value?.deselectAll();
    };
    function so(e) {
      eo(e), N(() => {
        T({});
      });
    }
    const io = s(() => {
      const e = t.customRow;
      return e ? {
        isFullWidthRow: e.isCustomRow,
        fullWidthCellRenderer: zt,
        fullWidthCellRendererParams: {
          render: e.render
        }
      } : {};
    });
    function uo(e) {
      oo(e), N(() => {
        T({});
      });
    }
    function co(e) {
      to(e), N(() => {
        T({});
      });
    }
    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 l = o.getColumnState() || [], a = Te(e), c = l.map((d) => {
        if (!Ie.value.includes(d.colId))
          return d;
        const k = !a.includes(d.colId), ge = {
          ...d,
          hide: k
        }, we = e.find(
          (Io) => fe(Io.key) === d.colId
        );
        return we && (ge.pinned = we.fixed || null), ge;
      }), u = new Map(
        e.map((d, k) => [fe(d.key), k])
      ), w = c.filter((d) => u.has(d.colId)).sort(
        (d, k) => u.get(d.colId) - u.get(k.colId)
      ), C = [];
      let p = 0;
      for (const d of c)
        u.has(d.colId) ? C.push(w[p++]) : C.push(d);
      K(C, { applyOrder: !0 });
    }
    mt({
      columns: s(() => f.value),
      columnsBackup: s(() => oe.value),
      awaitedColumns: Ee,
      size: s(() => ct[b.value]),
      updateColumns(e) {
        f.value = e, t.onShownColumnsChange?.(e), gt(
          () => r.value?.getColumns(),
          () => {
            mo(e);
          },
          {
            interval: 17,
            check: (o) => !!(o && o.length > 0)
          }
        );
      },
      updateSize(e) {
        b.value = dt[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) {
      (P(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: l
    }) {
      if (!e || l !== "uiColumnResized")
        return;
      const a = (o || []).map((c) => ({
        key: c.getColId(),
        width: c.getActualWidth()
      }));
      X(t.plugins, (c) => c.onColumnResized?.bind(c), a), t.onColumnResized?.(a);
    }
    const Mo = (e) => {
      const o = [
        Z.value.getRowClass?.(e)
      ];
      if (!e.node.rowPinned) {
        const l = P(t.rowClassName) ? t.rowClassName(e.data, e.rowIndex) : t.rowClassName;
        o.push(l);
      }
      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, l) => {
      X(
        t.plugins,
        (a) => a.searchParamsChange?.bind(this),
        o
      ), t.searchForm && t.searchForm.onValuesChange?.(e, o, l);
    };
    return E(
      () => t.dataSource,
      (e) => {
        N(() => {
          je(e, !0);
        });
      },
      { immediate: !0, deep: !0 }
    ), E(
      () => t.size,
      (e) => {
        b.value = e;
      }
    ), E(
      () => 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)
    }), (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(Ct).SearchForm, J(n(ut)(i.searchForm || {}, ["onValuesChange"]), {
          ref_key: "formRef",
          ref: h,
          "custom-reset": "",
          "submit-loading": n(ae).loading,
          onSubmit: n(L),
          onReset: n(H),
          onValuesChange: Bo
        }), No({
          default: Ce(() => [
            (v(!0), $(Do, null, Po(n(ee), (l) => (v(), Q(Vo(l.renderNode), {
              key: l.dataIndex
            }))), 128))
          ]),
          _: 2
        }, [
          V.searchFormExtra ? {
            name: "extra",
            fn: Ce(() => [
              Se(e.$slots, "searchFormExtra")
            ]),
            key: "0"
          } : void 0
        ]), 1040, ["submit-loading", "onSubmit", "onReset"])
      ], 6)) : he("", !0),
      D("div", {
        class: R([n(z)("table-wrapper"), i.card ? n(z)("table-wrapper-card") : null]),
        style: q(i.tableWrapperStyle)
      }, [
        D("div", {
          class: R(n(m)("header-wrapper"))
        }, [
          Se(e.$slots, "title", {
            selectedRows: n(W),
            selectedRowKeys: n(Ze),
            shownColumns: n(f),
            clearAll: j
          })
        ], 2),
        D("div", {
          ref_key: "gridWrapperRef",
          ref: De,
          class: R(n(m)("grid-wrapper"))
        }, [
          (v(), Q(n(it), 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(Ne),
              "suppress-loading-overlay": "",
              "row-selection": lo.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": Ot,
              "no-rows-overlay-component-params": { emptyComponent: i.emptyComponent, emptyText: i.emptyText },
              "loading-overlay-component": Kt,
              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: T,
              onRowSelected: ao,
              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),
        D("div", {
          class: R(n(m)("pagination-wrapper"))
        }, [
          i.pagination !== !1 ? (v(), Q(n(Oo), J({
            key: 0,
            class: n(m)("pagination")
          }, n(ae).pagination, { onChange: wo }), null, 16, ["class"])) : he("", !0)
        ], 2)
      ], 6)
    ], 6));
  }
});
export {
  xn as default
};
