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