import { getText } from "../../../../locales/index.js";
import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import { computeUniformColumnSummary, getRecordBoardColumnKey, isTrivialUniformSummaryReactContent, processColumnsForGrid } from "../../utils/recordBoardColumns.js";
import { useRecordBoardContext } from "../../hooks/useRecordBoardContext.js";
import { resolveRecordBoardPhoneScrollX } from "../../utils/recordBoardPhoneGrid.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Spin, Table } from "antd";
import classNames from "classnames";
import "./Grid.less";
//#region src/components/pisellRecordBoard/layouts/GridLayout/Grid.tsx
const _excluded = [
	"render",
	"columns",
	"rowKey",
	"rowSelection"
], _excluded2 = ["autoCalc"], _excluded3 = ["onScroll"], _excluded4 = ["summary"];
function getRowKey(record, rowKey) {
	var _ref, _record$id;
	if (typeof rowKey === "function") return rowKey(record);
	if (typeof rowKey === "string" && record != null && rowKey in record) return record[rowKey];
	return (_ref = (_record$id = record === null || record === void 0 ? void 0 : record.id) !== null && _record$id !== void 0 ? _record$id : record === null || record === void 0 ? void 0 : record.key) !== null && _ref !== void 0 ? _ref : record;
}
/**
* Grid 布局下的数据视图：使用 antd Table，从 context 取 data / loading / 多选态。
*/
/** Context 中与 Table 无关的 key，透传 Table 时排除，避免覆盖或无效传递（含 grid 合并进的 columns/scroll 等） */
const 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"
];
const RecordBoardGridView = (props) => {
	var _ref2, _ctx$data2, _ctx$data4;
	const ctx = useRecordBoardContext({ displayName: "grid" });
	const { render, columns: columnsProp, rowKey: rowKeyProp, rowSelection: rowSelectionProp } = props, rest = _objectWithoutProperties(props, _excluded);
	const rawColumns = (_ref2 = columnsProp !== null && columnsProp !== void 0 ? columnsProp : ctx.columns) !== null && _ref2 !== void 0 ? _ref2 : [];
	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;
	/** 同值列总结区高度，用于 autoCalc 时正确计算 scroll.y */
	const summaryRef = useRef(null);
	const [uniformSummaryHeight, setUniformSummaryHeight] = useState(0);
	const { columns, uniformSummaryItems: summaryItems, processedColumnsForSummary } = useMemo(() => {
		var _ctx$data;
		let list = rawColumns;
		if (Array.isArray(columnOrder) && columnOrder.length > 0) {
			const keyToCol = new Map(list.map((c) => [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 = getRecordBoardColumnKey(col);
				if (!columnOrder.includes(key)) ordered.push(col);
			});
			list = ordered;
		}
		const visibleByUser = columnVisibility == null ? list : list.filter((col) => columnVisibility[getRecordBoardColumnKey(col)] !== false);
		const data = (_ctx$data = ctx.data) !== null && _ctx$data !== void 0 ? _ctx$data : [];
		if (!(collapseUniformColumns && data.length > 5)) return {
			columns: processColumnsForGrid(visibleByUser),
			uniformSummaryItems: [],
			processedColumnsForSummary: void 0
		};
		const processedAllVisible = processColumnsForGrid(visibleByUser);
		const { uniformHiddenColumnKeys, summaryItems: items } = computeUniformColumnSummary(data, visibleByUser);
		/** 有 render 时以实际渲染为准：「-」、空等不展示总结项；列仍按折叠规则隐藏 */
		const finalSummaryItems = items.filter((item) => {
			var _item$record, _item$displayValue;
			const processedCol = processedAllVisible.find((c) => getRecordBoardColumnKey(c) === item.columnKey);
			return !isTrivialUniformSummaryReactContent(typeof (processedCol === null || processedCol === void 0 ? void 0 : processedCol.render) === "function" ? processedCol.render(item.cellValue, (_item$record = item.record) !== null && _item$record !== void 0 ? _item$record : {}, 0) : item.type === "empty" ? getText("record-board-uniform-summary-empty") : (_item$displayValue = item.displayValue) !== null && _item$displayValue !== void 0 ? _item$displayValue : getText("record-board-uniform-summary-same"));
		});
		return {
			columns: processedAllVisible.filter((col) => !uniformHiddenColumnKeys.includes(getRecordBoardColumnKey(col))),
			uniformSummaryItems: finalSummaryItems,
			processedColumnsForSummary: finalSummaryItems.length > 0 ? processedAllVisible : void 0
		};
	}, [
		rawColumns,
		columnVisibility,
		columnOrder,
		collapseUniformColumns,
		ctx.data,
		isPhoneLayout
	]);
	const tableRowKey = useMemo(() => {
		var _ref3, _ctx$rowKey;
		const key = (_ref3 = (_ctx$rowKey = ctx.rowKey) !== null && _ctx$rowKey !== void 0 ? _ctx$rowKey : rowKeyProp) !== null && _ref3 !== void 0 ? _ref3 : "id";
		return typeof key === "function" ? key : (record) => getRowKey(record, typeof key === "string" ? key : String(key));
	}, [ctx.rowKey, rowKeyProp]);
	const rowSelectionConfig = rowSelectionProp !== null && rowSelectionProp !== void 0 ? rowSelectionProp : ctx.rowSelection;
	const rowSelection = useMemo(() => {
		if (rowSelectionConfig === false) return void 0;
		const base = typeof rowSelectionConfig === "object" ? rowSelectionConfig : {};
		return _objectSpread2(_objectSpread2({}, base), {}, {
			selectedRowKeys: ctx.selectedKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				var _onChange;
				ctx.onSelectionChange(selectedRowKeys, selectedRows);
				(_onChange = base.onChange) === null || _onChange === void 0 || _onChange.call(base, selectedRowKeys, selectedRows);
			}
		});
	}, [
		ctx.selectedKeys,
		ctx.onSelectionChange,
		rowSelectionConfig
	]);
	/** 测量同值列总结区高度，供 autoCalc 时 scroll.y 减去该高度 */
	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 = 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__ */ React.createElement(React.Fragment, null, render(_objectSpread2(_objectSpread2({}, ctx), rest)));
	const dataSource = (_ctx$data2 = ctx.data) !== null && _ctx$data2 !== void 0 ? _ctx$data2 : [];
	const isEmpty = !Array.isArray(dataSource) || dataSource.length === 0;
	const sumColumnWidths = 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 = 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 = useMemo(() => {
		var _rest$scroll;
		const scroll = (_rest$scroll = rest.scroll) !== null && _rest$scroll !== void 0 ? _rest$scroll : ctx.scroll;
		const rawScrollX = isEmpty && scroll && typeof scroll.x !== "number" ? sumColumnWidths : scroll === null || scroll === void 0 ? void 0 : scroll.x;
		const scrollX = isPhoneLayout ? resolveRecordBoardPhoneScrollX(rawScrollX, sumColumnWidths, { selectionColumnWidth }) : rawScrollX;
		if ((scroll === null || scroll === void 0 ? void 0 : scroll.autoCalc) && typeof ctx.scrollAreaHeight === "number") {
			const wrapHeight = ctx.scrollAreaHeight;
			const reservedHeight = 40 + (uniformSummaryHeight > 0 ? uniformSummaryHeight + 25 : 0);
			return {
				x: scrollX !== null && scrollX !== void 0 ? scrollX : sumColumnWidths,
				y: Math.max(wrapHeight - reservedHeight, 100),
				scrollToFirstRowOnChange: gridInfiniteScroll ? false : scroll.scrollToFirstRowOnChange
			};
		}
		if (scroll && typeof scroll === "object") {
			const _ref4 = scroll, { autoCalc: _a } = _ref4, restScroll = _objectWithoutProperties(_ref4, _excluded2);
			const resolved = Object.keys(restScroll).length ? restScroll : void 0;
			if (resolved) {
				var _ref5;
				return _objectSpread2(_objectSpread2({}, resolved), {}, { x: (_ref5 = scrollX !== null && scrollX !== void 0 ? scrollX : resolved.x) !== null && _ref5 !== void 0 ? _ref5 : sumColumnWidths }, gridInfiniteScroll ? { scrollToFirstRowOnChange: false } : {});
			}
			return resolved;
		}
		return scroll;
	}, [
		rest.scroll,
		ctx.scroll,
		ctx.scrollAreaHeight,
		ctx.pagination,
		columns,
		sumColumnWidths,
		isEmpty,
		uniformSummaryHeight,
		gridInfiniteScroll,
		isPhoneLayout,
		selectionColumnWidth
	]);
	/** 触底加载下一页：距底部约 48px 内触发，避免 loading 与重复 onPageChange */
	const infiniteLoadLockRef = useRef(false);
	/** 已触发 onPageChange、等待下一页数据：宿主可能不设 ctx.loading，需单独驱动表尾「加载中」 */
	const [infiniteScrollFetching, setInfiniteScrollFetching] = useState(false);
	useEffect(() => {
		if (!ctx.loading) infiniteLoadLockRef.current = false;
	}, [ctx.loading, dataSource.length]);
	useEffect(() => {
		setInfiniteScrollFetching(false);
	}, [dataSource.length]);
	/**
	* 无限滚动：监听**实际发生滚动**的节点。
	* - 有 `scroll.y` 时表体在内部滚动，类名在 ConfigProvider 下为 `.pisell-lowcode-table-body`（非 `.ant-table-body`）；
	* - `scrollAreaHeight` 未就绪或仅 `autoCalc` 未算高时，整表在 Shell 的 `.pisell-record-board-scroll-body` 内滚，仅绑表体会漏事件（如 HUD 抽屉内嵌表）。
	*/
	const gridWrapRef = useRef(null);
	const ctxRef = useRef(ctx);
	ctxRef.current = ctx;
	const restRef = useRef(rest);
	restRef.current = rest;
	const gridInfiniteRef = useRef(false);
	gridInfiniteRef.current = gridInfiniteScroll;
	useEffect(() => {
		if (!gridInfiniteScroll) return;
		const root = gridWrapRef.current;
		if (!root) return;
		const handler = (e) => {
			var _r$onScroll, _onScroll2, _e$currentTarget, _c$data, _c$total;
			const r = restRef.current;
			const c = ctxRef.current;
			const ev = e;
			(_r$onScroll = r.onScroll) === null || _r$onScroll === void 0 || _r$onScroll.call(r, ev);
			(_onScroll2 = c.onScroll) === null || _onScroll2 === void 0 || _onScroll2.call(c, ev);
			if (!gridInfiniteRef.current) return;
			if (c.loading || infiniteLoadLockRef.current) return;
			const st = (_e$currentTarget = e.currentTarget) !== null && _e$currentTarget !== void 0 ? _e$currentTarget : e.target;
			const dataLen = ((_c$data = c.data) !== null && _c$data !== void 0 ? _c$data : []).length;
			const tot = (_c$total = c.total) !== null && _c$total !== void 0 ? _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;
			listScrollTargets(root).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 = useMemo(() => {
		if (!gridInfiniteScroll) return rest;
		const _ref6 = rest, { onScroll: _onScroll } = _ref6;
		return _objectWithoutProperties(_ref6, _excluded3);
	}, [gridInfiniteScroll, rest]);
	const userGridSummary = gridTableProps.summary;
	const infiniteSummaryColSpan = useMemo(() => {
		return (Array.isArray(columns) ? columns.length : 1) + (rowSelection ? 1 : 0);
	}, [columns, rowSelection]);
	/** 无限滚动：在 Table.Summary 内展示状态（与宿主 summary 合并） */
	const mergedTableSummary = useMemo(() => {
		if (!gridInfiniteScroll) return userGridSummary;
		return (pageData) => {
			var _ctx$data3;
			const userNode = typeof userGridSummary === "function" ? userGridSummary(pageData) : userGridSummary;
			const len = ((_ctx$data3 = ctx.data) !== null && _ctx$data3 !== void 0 ? _ctx$data3 : []).length;
			const tot = ctx.total;
			const loadingMore = !!ctx.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__ */ React.createElement("span", { className: "pisell-record-board-infinite-scroll-tip-done" }, getText("record-board-infinite-scroll-all-loaded"));
				else if (hasMore && len > 0) statusInner = /* @__PURE__ */ React.createElement("span", { className: "pisell-record-board-infinite-scroll-tip-loading" }, /* @__PURE__ */ React.createElement(Spin, { size: "small" }), /* @__PURE__ */ React.createElement("span", null, getText("record-board-infinite-scroll-loading-more")));
			}
			const statusBlock = statusInner != null ? /* @__PURE__ */ React.createElement(Table.Summary, { fixed: "bottom" }, /* @__PURE__ */ React.createElement(Table.Summary.Row, { className: "pisell-record-board-infinite-scroll-summary-row" }, /* @__PURE__ */ React.createElement(Table.Summary.Cell, {
				index: 0,
				colSpan: infiniteSummaryColSpan,
				align: "left"
			}, /* @__PURE__ */ React.createElement("div", { className: "pisell-record-board-infinite-scroll-tip" }, statusInner)))) : null;
			if (!userNode && !statusBlock) return null;
			return /* @__PURE__ */ React.createElement(React.Fragment, null, userNode, statusBlock);
		};
	}, [
		gridInfiniteScroll,
		userGridSummary,
		infiniteSummaryColSpan,
		ctx.data,
		ctx.total,
		ctx.loading,
		infiniteScrollFetching
	]);
	const _ref7 = gridTableProps, { summary: _userSummaryOmitted } = _ref7, gridTablePropsWithoutSummary = _objectWithoutProperties(_ref7, _excluded4);
	return /* @__PURE__ */ React.createElement("div", {
		ref: gridWrapRef,
		"data-layout-slot": "grid",
		className: classNames("pisell-lowcode-record-board-grid", isPhoneLayout && "pisell-record-board-grid--phone", gridClassName)
	}, summaryItems.length > 0 && /* @__PURE__ */ React.createElement("div", {
		ref: summaryRef,
		className: "pisell-record-board-uniform-summary"
	}, summaryItems.map((item) => {
		var _item$record2, _item$displayValue2;
		const processedCol = processedColumnsForSummary === null || processedColumnsForSummary === void 0 ? void 0 : processedColumnsForSummary.find((c) => getRecordBoardColumnKey(c) === item.columnKey);
		const content = typeof (processedCol === null || processedCol === void 0 ? void 0 : processedCol.render) === "function" ? processedCol.render(item.cellValue, (_item$record2 = item.record) !== null && _item$record2 !== void 0 ? _item$record2 : {}, 0) : item.type === "empty" ? getText("record-board-uniform-summary-empty") : (_item$displayValue2 = item.displayValue) !== null && _item$displayValue2 !== void 0 ? _item$displayValue2 : getText("record-board-uniform-summary-same");
		return /* @__PURE__ */ React.createElement("div", {
			key: item.columnKey,
			className: "pisell-record-board-uniform-summary-item"
		}, /* @__PURE__ */ React.createElement("span", { className: "pisell-record-board-uniform-summary-label" }, item.title), /* @__PURE__ */ React.createElement("span", { className: "pisell-record-board-uniform-summary-value" }, content));
	})), /* @__PURE__ */ React.createElement(Table, _objectSpread2(_objectSpread2(_objectSpread2({}, tableRest), gridTablePropsWithoutSummary), {}, {
		summary: mergedTableSummary,
		scroll: tableScroll,
		rowKey: tableRowKey,
		dataSource: (_ctx$data4 = ctx.data) !== null && _ctx$data4 !== void 0 ? _ctx$data4 : [],
		loading: ctx.loading,
		columns,
		rowSelection,
		pagination: false
	})));
};
//#endregion
export { RecordBoardGridView as default };
