var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/pisellRecordBoard/layouts/GridLayout/Grid.tsx
var Grid_exports = {};
__export(Grid_exports, {
  default: () => Grid_default
});
module.exports = __toCommonJS(Grid_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_antd = require("antd");
var import_useRecordBoardContext = require("../../hooks/useRecordBoardContext");
var import_recordBoardColumns = require("../../utils/recordBoardColumns");
var import_recordBoardPhoneGrid = require("../../utils/recordBoardPhoneGrid");
var import_locales = require("../../../../locales");
var import_Grid = require("./Grid.less");
function getRowKey(record, rowKey) {
  if (typeof rowKey === "function") {
    return rowKey(record);
  }
  if (typeof rowKey === "string" && record != null && rowKey in record) {
    return record[rowKey];
  }
  return (record == null ? void 0 : record.id) ?? (record == null ? void 0 : record.key) ?? record;
}
var CONTEXT_ONLY_KEYS = [
  "data",
  "loading",
  "total",
  "pagination",
  "onPageChange",
  "searchParams",
  "onSearch",
  "onReset",
  "layoutType",
  "selectedKeys",
  "selectedRows",
  "onSelectionChange",
  "rowKey",
  "childComponentProps",
  "columnVisibility",
  "onColumnVisibilityChange",
  "columns",
  "scroll",
  "size",
  "defaultHiddenColumnKeys",
  "scrollAreaHeight",
  "setScrollAreaHeight",
  "collapseUniformColumns",
  "columnOrder",
  "onColumnOrderChange",
  "gridInfiniteScroll",
  "infiniteScroll",
  "paginationRender",
  "layoutVariant",
  "phoneColumnWidthCaps",
  "phoneColumnWidthRatioByKey",
  "phoneColumnWidthRatio"
];
var RecordBoardGridView = (props) => {
  const ctx = (0, import_useRecordBoardContext.useRecordBoardContext)({ displayName: "grid" });
  const {
    render,
    columns: columnsProp,
    rowKey: rowKeyProp,
    rowSelection: rowSelectionProp,
    ...rest
  } = props;
  const rawColumns = columnsProp ?? ctx.columns ?? [];
  const columnVisibility = ctx.columnVisibility;
  const columnOrder = ctx.columnOrder;
  const collapseUniformColumns = ctx.collapseUniformColumns !== false;
  const isPhoneLayout = ctx.layoutVariant === "phone";
  const gridClassName = typeof ctx.className === "string" ? ctx.className : void 0;
  const summaryRef = (0, import_react.useRef)(null);
  const [uniformSummaryHeight, setUniformSummaryHeight] = (0, import_react.useState)(0);
  const {
    columns,
    uniformSummaryItems: summaryItems,
    processedColumnsForSummary
  } = (0, import_react.useMemo)(() => {
    let list = rawColumns;
    if (Array.isArray(columnOrder) && columnOrder.length > 0) {
      const keyToCol = new Map(
        list.map((c) => [(0, import_recordBoardColumns.getRecordBoardColumnKey)(c), c])
      );
      const ordered = [];
      for (const key of columnOrder) {
        const col = keyToCol.get(key);
        if (col) ordered.push(col);
      }
      list.forEach((col) => {
        const key = (0, import_recordBoardColumns.getRecordBoardColumnKey)(col);
        if (!columnOrder.includes(key)) ordered.push(col);
      });
      list = ordered;
    }
    const visibleByUser = columnVisibility == null ? list : list.filter(
      (col) => columnVisibility[(0, import_recordBoardColumns.getRecordBoardColumnKey)(col)] !== false
    );
    const data = ctx.data ?? [];
    const shouldCollapseUniform = collapseUniformColumns && data.length > 5;
    if (!shouldCollapseUniform) {
      return {
        columns: (0, import_recordBoardColumns.processColumnsForGrid)(visibleByUser),
        uniformSummaryItems: [],
        processedColumnsForSummary: void 0
      };
    }
    const processedAllVisible = (0, import_recordBoardColumns.processColumnsForGrid)(visibleByUser);
    const { uniformHiddenColumnKeys, summaryItems: items } = (0, import_recordBoardColumns.computeUniformColumnSummary)(data, visibleByUser);
    const finalSummaryItems = items.filter((item) => {
      const processedCol = processedAllVisible.find(
        (c) => (0, import_recordBoardColumns.getRecordBoardColumnKey)(c) === item.columnKey
      );
      const useRender = typeof (processedCol == null ? void 0 : processedCol.render) === "function";
      const content = useRender ? processedCol.render(item.cellValue, item.record ?? {}, 0) : item.type === "empty" ? (0, import_locales.getText)("record-board-uniform-summary-empty") : item.displayValue ?? (0, import_locales.getText)("record-board-uniform-summary-same");
      return !(0, import_recordBoardColumns.isTrivialUniformSummaryReactContent)(content);
    });
    const columnsForTable = processedAllVisible.filter(
      (col) => !uniformHiddenColumnKeys.includes((0, import_recordBoardColumns.getRecordBoardColumnKey)(col))
    );
    return {
      columns: columnsForTable,
      uniformSummaryItems: finalSummaryItems,
      processedColumnsForSummary: finalSummaryItems.length > 0 ? processedAllVisible : void 0
    };
  }, [
    rawColumns,
    columnVisibility,
    columnOrder,
    collapseUniformColumns,
    ctx.data,
    isPhoneLayout
  ]);
  const tableRowKey = (0, import_react.useMemo)(() => {
    const key = ctx.rowKey ?? rowKeyProp ?? "id";
    return typeof key === "function" ? key : (record) => getRowKey(record, typeof key === "string" ? key : String(key));
  }, [ctx.rowKey, rowKeyProp]);
  const rowSelectionConfig = rowSelectionProp ?? ctx.rowSelection;
  const rowSelection = (0, import_react.useMemo)(() => {
    if (rowSelectionConfig === false)
      return void 0;
    const base = typeof rowSelectionConfig === "object" ? rowSelectionConfig : {};
    return {
      ...base,
      selectedRowKeys: ctx.selectedKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        var _a;
        ctx.onSelectionChange(selectedRowKeys, selectedRows);
        (_a = base.onChange) == null ? void 0 : _a.call(base, selectedRowKeys, selectedRows);
      }
    };
  }, [ctx.selectedKeys, ctx.onSelectionChange, rowSelectionConfig]);
  (0, import_react.useEffect)(() => {
    if (summaryItems.length === 0) {
      setUniformSummaryHeight(0);
      return;
    }
    const el = summaryRef.current;
    if (!el) return;
    const ro = new ResizeObserver((entries) => {
      const entry = entries[0];
      if (entry) setUniformSummaryHeight(entry.contentRect.height);
    });
    ro.observe(el);
    return () => {
      ro.disconnect();
      setUniformSummaryHeight(0);
    };
  }, [summaryItems.length]);
  const gridTableProps = (0, import_react.useMemo)(() => {
    const picked = {};
    Object.keys(ctx).forEach((k) => {
      if (k === "onScroll") return;
      if (CONTEXT_ONLY_KEYS.includes(
        k
      ))
        return;
      picked[k] = ctx[k];
    });
    return picked;
  }, [ctx]);
  if (typeof render === "function") {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, render({ ...ctx, ...rest }));
  }
  const dataSource = ctx.data ?? [];
  const isEmpty = !Array.isArray(dataSource) || dataSource.length === 0;
  const sumColumnWidths = (0, import_react.useMemo)(() => {
    const sum = columns.reduce((acc, col) => {
      if (typeof col.width === "number" && Number.isFinite(col.width)) {
        return acc + col.width;
      }
      return isPhoneLayout ? acc : acc + 250;
    }, 0);
    if (sum > 0) {
      return sum;
    }
    return isPhoneLayout ? 0 : 2e3;
  }, [columns, isPhoneLayout]);
  const selectionColumnWidth = (0, import_react.useMemo)(() => {
    if (!rowSelection || typeof rowSelection !== "object") return 0;
    const w = rowSelection.columnWidth;
    return typeof w === "number" && Number.isFinite(w) ? w : 48;
  }, [rowSelection]);
  const gridInfiniteScroll = ctx.gridInfiniteScroll === true;
  const tableScroll = (0, import_react.useMemo)(() => {
    const scroll = rest.scroll ?? ctx.scroll;
    const rawScrollX = isEmpty && scroll && typeof scroll.x !== "number" ? sumColumnWidths : scroll == null ? void 0 : scroll.x;
    const scrollX = isPhoneLayout ? (0, import_recordBoardPhoneGrid.resolveRecordBoardPhoneScrollX)(rawScrollX, sumColumnWidths, {
      selectionColumnWidth
    }) : rawScrollX;
    if ((scroll == null ? void 0 : scroll.autoCalc) && typeof ctx.scrollAreaHeight === "number") {
      const wrapHeight = ctx.scrollAreaHeight;
      const reservedHeight = 40 + uniformSummaryHeight + 24;
      return {
        x: scrollX ?? sumColumnWidths,
        y: Math.max(wrapHeight - reservedHeight, 100),
        scrollToFirstRowOnChange: gridInfiniteScroll ? false : scroll.scrollToFirstRowOnChange
      };
    }
    if (scroll && typeof scroll === "object") {
      const { autoCalc: _a, ...restScroll } = scroll;
      const resolved = Object.keys(restScroll).length ? restScroll : void 0;
      if (resolved) {
        return {
          ...resolved,
          x: scrollX ?? resolved.x ?? sumColumnWidths,
          ...gridInfiniteScroll ? { scrollToFirstRowOnChange: false } : {}
        };
      }
      return resolved;
    }
    return scroll;
  }, [
    rest.scroll,
    ctx.scroll,
    ctx.scrollAreaHeight,
    ctx.pagination,
    columns,
    sumColumnWidths,
    isEmpty,
    uniformSummaryHeight,
    gridInfiniteScroll,
    isPhoneLayout,
    selectionColumnWidth
  ]);
  const infiniteLoadLockRef = (0, import_react.useRef)(false);
  const [infiniteScrollFetching, setInfiniteScrollFetching] = (0, import_react.useState)(false);
  (0, import_react.useEffect)(() => {
    if (!ctx.loading) {
      infiniteLoadLockRef.current = false;
    }
  }, [ctx.loading, dataSource.length]);
  (0, import_react.useEffect)(() => {
    setInfiniteScrollFetching(false);
  }, [dataSource.length]);
  const gridWrapRef = (0, import_react.useRef)(null);
  const ctxRef = (0, import_react.useRef)(ctx);
  ctxRef.current = ctx;
  const restRef = (0, import_react.useRef)(rest);
  restRef.current = rest;
  const gridInfiniteRef = (0, import_react.useRef)(false);
  gridInfiniteRef.current = gridInfiniteScroll;
  (0, import_react.useEffect)(() => {
    if (!gridInfiniteScroll) return;
    const root = gridWrapRef.current;
    if (!root) {
      return;
    }
    const handler = (e) => {
      var _a, _b;
      const r = restRef.current;
      const c = ctxRef.current;
      const ev = e;
      (_a = r.onScroll) == null ? void 0 : _a.call(r, ev);
      (_b = c.onScroll) == null ? void 0 : _b.call(
        c,
        ev
      );
      if (!gridInfiniteRef.current) return;
      if (c.loading || infiniteLoadLockRef.current) {
        return;
      }
      const st = e.currentTarget ?? e.target;
      const dataLen = (c.data ?? []).length;
      const tot = c.total ?? 0;
      const { scrollTop, clientHeight, scrollHeight } = st;
      const dist = scrollHeight - scrollTop - clientHeight;
      if (dataLen >= tot) {
        return;
      }
      if (dist > 48) return;
      infiniteLoadLockRef.current = true;
      setInfiniteScrollFetching(true);
      c.onPageChange(c.pagination.pageNumber + 1, c.pagination.pageSize);
    };
    const listScrollTargets = (r) => {
      const out = [];
      const seen = /* @__PURE__ */ new Set();
      const add = (el) => {
        if (el && !seen.has(el)) {
          seen.add(el);
          out.push(el);
        }
      };
      r.querySelectorAll(".ant-table-body, .pisell-lowcode-table-body").forEach(
        (n) => add(n)
      );
      add(r.closest(".pisell-record-board-scroll-body"));
      return out;
    };
    const cleanups = [];
    const bind = () => {
      cleanups.forEach((fn) => fn());
      cleanups.length = 0;
      const targets = listScrollTargets(root);
      targets.forEach((el) => {
        el.addEventListener("scroll", handler, { passive: true });
        cleanups.push(() => el.removeEventListener("scroll", handler));
      });
    };
    const t0 = window.setTimeout(() => bind(), 0);
    const t1 = window.setTimeout(() => bind(), 120);
    const t2 = window.setTimeout(() => bind(), 400);
    return () => {
      clearTimeout(t0);
      clearTimeout(t1);
      clearTimeout(t2);
      cleanups.forEach((fn) => fn());
    };
  }, [
    gridInfiniteScroll,
    dataSource.length,
    isEmpty,
    ctx.scrollAreaHeight,
    columns,
    summaryItems.length
  ]);
  const tableRest = (0, import_react.useMemo)(() => {
    if (!gridInfiniteScroll) return rest;
    const { onScroll: _onScroll, ...r } = rest;
    return r;
  }, [gridInfiniteScroll, rest]);
  const userGridSummary = gridTableProps.summary;
  const infiniteSummaryColSpan = (0, import_react.useMemo)(() => {
    const n = Array.isArray(columns) ? columns.length : 1;
    return n + (rowSelection ? 1 : 0);
  }, [columns, rowSelection]);
  const mergedTableSummary = (0, import_react.useMemo)(() => {
    if (!gridInfiniteScroll) {
      return userGridSummary;
    }
    return (pageData) => {
      const userNode = typeof userGridSummary === "function" ? userGridSummary(pageData) : userGridSummary;
      const len = (ctx.data ?? []).length;
      const tot = ctx.total;
      const loading = !!ctx.loading;
      const loadingMore = loading || infiniteScrollFetching;
      const showBar = len > 0 || loadingMore;
      if (!showBar && !userNode) {
        return null;
      }
      const hasMore = tot == null || typeof tot !== "number" ? true : len < tot;
      const allLoaded = typeof tot === "number" && tot > 0 && len > 0 && len >= tot;
      let statusInner = null;
      if (showBar) {
        if (allLoaded) {
          statusInner = /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-record-board-infinite-scroll-tip-done" }, (0, import_locales.getText)("record-board-infinite-scroll-all-loaded"));
        } else if (hasMore && len > 0) {
          statusInner = /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-record-board-infinite-scroll-tip-loading" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { size: "small" }), /* @__PURE__ */ import_react.default.createElement("span", null, (0, import_locales.getText)("record-board-infinite-scroll-loading-more")));
        }
      }
      const statusBlock = statusInner != null ? /* @__PURE__ */ import_react.default.createElement(import_antd.Table.Summary, { fixed: "bottom" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Table.Summary.Row, { className: "pisell-record-board-infinite-scroll-summary-row" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Table.Summary.Cell, { index: 0, colSpan: infiniteSummaryColSpan, align: "left" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-record-board-infinite-scroll-tip" }, statusInner)))) : null;
      if (!userNode && !statusBlock) return null;
      return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, userNode, statusBlock);
    };
  }, [
    gridInfiniteScroll,
    userGridSummary,
    infiniteSummaryColSpan,
    ctx.data,
    ctx.total,
    ctx.loading,
    infiniteScrollFetching
  ]);
  const { summary: _userSummaryOmitted, ...gridTablePropsWithoutSummary } = gridTableProps;
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: gridWrapRef,
      "data-layout-slot": "grid",
      className: (0, import_classnames.default)(
        "pisell-lowcode-record-board-grid",
        isPhoneLayout && "pisell-record-board-grid--phone",
        gridClassName
      )
    },
    summaryItems.length > 0 && /* @__PURE__ */ import_react.default.createElement("div", { ref: summaryRef, className: "pisell-record-board-uniform-summary" }, summaryItems.map((item) => {
      const processedCol = processedColumnsForSummary == null ? void 0 : processedColumnsForSummary.find(
        (c) => (0, import_recordBoardColumns.getRecordBoardColumnKey)(c) === item.columnKey
      );
      const useRender = typeof (processedCol == null ? void 0 : processedCol.render) === "function";
      const content = useRender ? processedCol.render(item.cellValue, item.record ?? {}, 0) : item.type === "empty" ? (0, import_locales.getText)("record-board-uniform-summary-empty") : item.displayValue ?? (0, import_locales.getText)("record-board-uniform-summary-same");
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          key: item.columnKey,
          className: "pisell-record-board-uniform-summary-item"
        },
        /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-record-board-uniform-summary-label" }, item.title),
        /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-record-board-uniform-summary-value" }, content)
      );
    })),
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Table,
      {
        ...tableRest,
        ...gridTablePropsWithoutSummary,
        summary: mergedTableSummary,
        scroll: tableScroll,
        rowKey: tableRowKey,
        dataSource: ctx.data ?? [],
        loading: ctx.loading,
        columns,
        rowSelection,
        pagination: false
      }
    )
  );
};
var Grid_default = RecordBoardGridView;
