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 { RecordBoardProvider } from "./context/RecordBoardProvider.js";
import { getRecordBoardColumnKey } from "./utils/recordBoardColumns.js";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { getColumnVisibilityFromLocal, getRecordBoardColumnSettingFromLocal, saveColumnVisibilityToLocal } from "@pisell/utils";
//#region src/components/pisellRecordBoard/PisellRecordBoard.tsx
const _excluded = [
	"children",
	"layoutType",
	"rowKey",
	"data",
	"dataSources",
	"gridDataSourceKey",
	"loading",
	"total",
	"pagination",
	"onPageChange",
	"searchParams",
	"onSearch",
	"onReset",
	"floorMap",
	"calendar",
	"resourceWall",
	"floorMapLayoutContext",
	"defaultBodyView",
	"bodyViewStorageKey",
	"bodyViewSwitchable",
	"lockedBodyView",
	"floorMapLayoutRef",
	"floorMapFooter",
	"layoutVariant",
	"className",
	"style"
];
const defaultPagination = {
	pageNumber: 1,
	pageSize: 50
};
function readBodyViewFromStorage(key, fallback) {
	if (typeof window === "undefined" || !key) return fallback;
	try {
		const raw = localStorage.getItem(key);
		if (raw === "grid" || raw === "floorMap" || raw === "calendar" || raw === "resourceWall") return raw;
	} catch (_unused) {}
	return fallback;
}
/**
* 从打散 props 合并出 childComponentProps（供 context 使用）。
*/
function mergeChildComponentProps(props) {
	if (!(props.grid != null || props.toolBar != null || props.search != null || props.paginationConfig != null || props.batchActionBar != null || props.cardList != null)) return void 0;
	return _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, props.grid != null && { grid: props.grid }), props.toolBar != null && { toolBar: props.toolBar }), props.search != null && { search: props.search }), props.paginationConfig != null && { pagination: props.paginationConfig }), props.batchActionBar != null && { batchActionBar: props.batchActionBar }), props.cardList != null && { cardList: props.cardList });
}
/**
* 默认的 context 值（用于无数据源时的占位 / 设计态）
*/
function getDefaultRecordBoardContext(layoutType, selection, rowKey) {
	return {
		data: [],
		loading: false,
		total: 0,
		pagination: defaultPagination,
		onPageChange: () => {},
		searchParams: {},
		onSearch: () => {},
		onReset: () => {},
		layoutType,
		selectedKeys: selection.selectedKeys,
		selectedRows: selection.selectedRows,
		onSelectionChange: selection.onSelectionChange,
		rowKey,
		childComponentProps: void 0,
		scrollAreaHeight: null,
		setScrollAreaHeight: void 0,
		filterResetKey: void 0,
		setFilterResetKey: void 0,
		bodyView: "grid",
		setBodyView: () => {},
		floorMapProps: void 0,
		floorMapLayoutContext: void 0,
		defaultBodyView: void 0,
		bodyViewSwitchable: true,
		floorMapLayoutRef: void 0,
		floorMapFooter: void 0,
		calendarProps: void 0,
		resourceWallProps: void 0,
		dataSources: void 0,
		gridDataSourceKey: void 0,
		paginationRender: void 0
	};
}
/**
* RecordBoard 容器：提供统一的 data / pagination / search 上下文。
* 打散 props：列表/分页/搜索/多选、grid/toolBar/…；可选根级 **floorMap**（兼容透传）。
* 平面图推荐在 ShellFrame 内使用 **PisellRecordBoard.FloorMap** 声明，与根级 `floorMap` 合并（子优先）。
*/
const PisellRecordBoard = (props) => {
	var _props$columnVisibili, _props$grid4;
	const { children, layoutType = "grid", rowKey: rowKeyProp, data: dataProp, dataSources: dataSourcesProp, gridDataSourceKey: gridDataSourceKeyProp, loading: loadingProp, total: totalProp, pagination: paginationProp, onPageChange: onPageChangeProp, searchParams: searchParamsProp, onSearch: onSearchProp, onReset: onResetProp, floorMap: floorMapProp, calendar: calendarProp, resourceWall: resourceWallProp, floorMapLayoutContext: floorMapLayoutContextProp, defaultBodyView, bodyViewStorageKey, bodyViewSwitchable = true, lockedBodyView: lockedBodyViewProp, floorMapLayoutRef, floorMapFooter, layoutVariant = "default", className: classNameProp, style: styleProp } = props;
	_objectWithoutProperties(props, _excluded);
	const effectiveLockedBodyView = bodyViewSwitchable === false ? lockedBodyViewProp !== null && lockedBodyViewProp !== void 0 ? lockedBodyViewProp : "floorMap" : void 0;
	/** 默认占满父容器高度（父容器需有高度，如 height:100vh 或 height:100%） */
	const fillHeight = true;
	/** 列显隐持久化 key：优先 columnVisibilityStorageKey，其次 __id（与 DataSourceContainer 一致，复用 @pisell/utils 的 key 规则） */
	const columnVisibilityStorageKey = (_props$columnVisibili = props.columnVisibilityStorageKey) !== null && _props$columnVisibili !== void 0 ? _props$columnVisibili : props.__id;
	const mergedChildComponentProps = useMemo(() => mergeChildComponentProps(props), [
		props.grid,
		props.toolBar,
		props.search,
		props.paginationConfig,
		props.batchActionBar,
		props.cardList
	]);
	const [internalSelectedKeys, setInternalSelectedKeys] = useState([]);
	const [internalSelectedRows, setInternalSelectedRows] = useState([]);
	const [scrollAreaHeight, setScrollAreaHeight] = useState(null);
	/** 点击重置时递增，供 ToolBar 给 PisellFilter 设 key 以强制重挂载，清空弹窗内高级筛选表单 */
	const [filterResetKey, setFilterResetKey] = useState(0);
	const [bodyView, setBodyViewState] = useState(() => {
		if (effectiveLockedBodyView != null) return effectiveLockedBodyView;
		return readBodyViewFromStorage(bodyViewStorageKey, defaultBodyView === "floorMap" ? "floorMap" : defaultBodyView === "calendar" ? "calendar" : defaultBodyView === "resourceWall" ? "resourceWall" : "grid");
	});
	const setBodyView = useCallback((v) => {
		if (bodyViewSwitchable === false && effectiveLockedBodyView != null && v !== effectiveLockedBodyView) return;
		setBodyViewState(v);
		if (typeof window !== "undefined" && bodyViewStorageKey) try {
			localStorage.setItem(bodyViewStorageKey, v);
		} catch (_unused2) {}
	}, [
		bodyViewStorageKey,
		bodyViewSwitchable,
		effectiveLockedBodyView
	]);
	useEffect(() => {
		if (bodyViewSwitchable === false && effectiveLockedBodyView != null && bodyView !== effectiveLockedBodyView) setBodyViewState(effectiveLockedBodyView);
	}, [
		bodyViewSwitchable,
		effectiveLockedBodyView,
		bodyView
	]);
	const [internalColumnVisibility, setInternalColumnVisibility] = useState(() => {
		var _props$grid$defaultHi, _props$grid, _props$grid$columns, _props$grid2;
		const fromConfig = (_props$grid$defaultHi = (_props$grid = props.grid) === null || _props$grid === void 0 ? void 0 : _props$grid.defaultHiddenColumnKeys) !== null && _props$grid$defaultHi !== void 0 ? _props$grid$defaultHi : [];
		const fromColumns = ((_props$grid$columns = (_props$grid2 = props.grid) === null || _props$grid2 === void 0 ? void 0 : _props$grid2.columns) !== null && _props$grid$columns !== void 0 ? _props$grid$columns : []).filter((col) => col.hidden === true).map((col) => getRecordBoardColumnKey(col)).filter(Boolean);
		const allHiddenKeys = Array.from(new Set([...fromConfig, ...fromColumns]));
		const defaultVis = {};
		allHiddenKeys.forEach((k) => {
			defaultVis[k] = false;
		});
		if (typeof columnVisibilityStorageKey === "string" && columnVisibilityStorageKey) {
			if (typeof getRecordBoardColumnSettingFromLocal === "function") {
				const saved = getRecordBoardColumnSettingFromLocal(columnVisibilityStorageKey);
				if ((saved === null || saved === void 0 ? void 0 : saved.columnVisibility) && Object.keys(saved.columnVisibility).length > 0) return _objectSpread2(_objectSpread2({}, defaultVis), saved.columnVisibility);
			} else if (typeof getColumnVisibilityFromLocal === "function") {
				const savedVis = getColumnVisibilityFromLocal(columnVisibilityStorageKey);
				if (savedVis && Object.keys(savedVis).length > 0) return _objectSpread2(_objectSpread2({}, defaultVis), savedVis);
			}
		}
		return defaultVis;
	});
	const [internalColumnOrder, setInternalColumnOrder] = useState(() => {
		if (typeof columnVisibilityStorageKey === "string" && columnVisibilityStorageKey && typeof getRecordBoardColumnSettingFromLocal === "function") {
			var _saved$columnOrder;
			const saved = getRecordBoardColumnSettingFromLocal(columnVisibilityStorageKey);
			return (_saved$columnOrder = saved === null || saved === void 0 ? void 0 : saved.columnOrder) !== null && _saved$columnOrder !== void 0 ? _saved$columnOrder : null;
		}
		return null;
	});
	useEffect(() => {
		if (typeof columnVisibilityStorageKey !== "string" || !columnVisibilityStorageKey) return;
		saveColumnVisibilityToLocal({
			componentId: columnVisibilityStorageKey,
			columnVisibility: internalColumnVisibility,
			columnOrder: internalColumnOrder !== null && internalColumnOrder !== void 0 ? internalColumnOrder : void 0
		});
	}, [
		columnVisibilityStorageKey,
		internalColumnVisibility,
		internalColumnOrder
	]);
	const onSelectionChangeInternal = useCallback((keys, rows) => {
		setInternalSelectedKeys(keys);
		setInternalSelectedRows(rows);
	}, []);
	const onColumnVisibilityChangeInternal = useCallback((visibility) => {
		setInternalColumnVisibility((prev) => _objectSpread2(_objectSpread2({}, prev), visibility));
	}, []);
	const onColumnOrderChangeInternal = useCallback((columnKeys) => {
		setInternalColumnOrder(columnKeys);
	}, []);
	const contextValue = useMemo(() => {
		var _props$grid3, _gridSelection$select;
		const defaultCtx = getDefaultRecordBoardContext(layoutType, {
			selectedKeys: internalSelectedKeys,
			selectedRows: internalSelectedRows,
			onSelectionChange: onSelectionChangeInternal
		}, rowKeyProp);
		/** 分页状态（推导表格切片前需要） */
		const pagination = paginationProp !== void 0 ? paginationProp : defaultCtx.pagination;
		const gridInfiniteScroll = ((_props$grid3 = props.grid) === null || _props$grid3 === void 0 ? void 0 : _props$grid3.infiniteScroll) === true;
		/**
		* 表格数据：
		* - 显式传入 `data` 时始终用 `data`（如服务端分页当前页）；
		* - 否则若存在 `dataSources` + `gridDataSourceKey`，从对应数组做客户端分页切片。
		* - `infiniteScroll` 时对该路径做**累积**切片：slice(0, pageNumber * pageSize)，与触底加载多页一致。
		*/
		let data;
		let total;
		if (dataProp !== void 0) {
			data = dataProp;
			total = totalProp !== void 0 ? totalProp : defaultCtx.total;
		} else if (dataSourcesProp != null && gridDataSourceKeyProp != null && gridDataSourceKeyProp !== "") {
			var _dataSourcesProp$grid;
			const raw = (_dataSourcesProp$grid = dataSourcesProp[gridDataSourceKeyProp]) !== null && _dataSourcesProp$grid !== void 0 ? _dataSourcesProp$grid : [];
			total = totalProp !== void 0 ? totalProp : raw.length;
			const { pageNumber, pageSize } = pagination;
			const safeSize = Math.max(1, pageSize);
			if (gridInfiniteScroll) {
				const end = Math.min(raw.length, pageNumber * safeSize);
				data = raw.slice(0, end);
			} else {
				const start = Math.max(0, (pageNumber - 1) * safeSize);
				data = raw.slice(start, start + safeSize);
			}
		} else {
			data = defaultCtx.data;
			total = totalProp !== void 0 ? totalProp : defaultCtx.total;
		}
		const loading = loadingProp !== void 0 ? loadingProp : defaultCtx.loading;
		const onPageChange = onPageChangeProp !== null && onPageChangeProp !== void 0 ? onPageChangeProp : defaultCtx.onPageChange;
		const searchParams = searchParamsProp !== void 0 ? searchParamsProp : defaultCtx.searchParams;
		const onSearch = onSearchProp !== null && onSearchProp !== void 0 ? onSearchProp : defaultCtx.onSearch;
		const onReset = onResetProp !== null && onResetProp !== void 0 ? onResetProp : defaultCtx.onReset;
		const rowKey = rowKeyProp !== null && rowKeyProp !== void 0 ? rowKeyProp : defaultCtx.rowKey;
		const gridSelection = props.grid;
		const hasControlledSelection = (gridSelection === null || gridSelection === void 0 ? void 0 : gridSelection.selectedKeys) != null && Array.isArray(gridSelection.selectedKeys) && typeof gridSelection.onSelectionChange === "function";
		const selectedKeys = hasControlledSelection ? gridSelection.selectedKeys : internalSelectedKeys;
		const selectedRows = hasControlledSelection ? (_gridSelection$select = gridSelection.selectedRows) !== null && _gridSelection$select !== void 0 ? _gridSelection$select : [] : internalSelectedRows;
		const onSelectionChange = hasControlledSelection ? gridSelection.onSelectionChange : onSelectionChangeInternal;
		return _objectSpread2(_objectSpread2({}, defaultCtx), {}, {
			layoutType,
			layoutVariant,
			rowKey,
			dataSources: dataSourcesProp,
			gridDataSourceKey: gridDataSourceKeyProp,
			data,
			loading,
			total,
			pagination,
			onPageChange,
			searchParams,
			onSearch,
			onReset,
			selectedKeys,
			selectedRows,
			onSelectionChange,
			columnVisibility: internalColumnVisibility,
			onColumnVisibilityChange: onColumnVisibilityChangeInternal,
			columnOrder: internalColumnOrder,
			onColumnOrderChange: onColumnOrderChangeInternal,
			childComponentProps: mergedChildComponentProps !== null && mergedChildComponentProps !== void 0 ? mergedChildComponentProps : defaultCtx.childComponentProps,
			fillHeight,
			scrollAreaHeight,
			setScrollAreaHeight,
			filterResetKey,
			setFilterResetKey,
			bodyView,
			setBodyView,
			floorMapProps: floorMapProp,
			floorMapLayoutContext: floorMapLayoutContextProp,
			defaultBodyView,
			bodyViewSwitchable,
			floorMapLayoutRef,
			floorMapFooter,
			calendarProps: calendarProp,
			resourceWallProps: resourceWallProp,
			paginationRender: props.paginationRender,
			gridInfiniteScroll
		});
	}, [
		layoutType,
		layoutVariant,
		rowKeyProp,
		dataProp,
		dataSourcesProp,
		gridDataSourceKeyProp,
		loadingProp,
		totalProp,
		paginationProp,
		onPageChangeProp,
		searchParamsProp,
		onSearchProp,
		onResetProp,
		mergedChildComponentProps,
		internalSelectedKeys,
		internalSelectedRows,
		onSelectionChangeInternal,
		internalColumnVisibility,
		onColumnVisibilityChangeInternal,
		internalColumnOrder,
		onColumnOrderChangeInternal,
		fillHeight,
		scrollAreaHeight,
		filterResetKey,
		floorMapProp,
		floorMapLayoutContextProp,
		defaultBodyView,
		bodyViewSwitchable,
		floorMapLayoutRef,
		floorMapFooter,
		calendarProp,
		resourceWallProp,
		bodyView,
		setBodyView,
		props.paginationRender,
		(_props$grid4 = props.grid) === null || _props$grid4 === void 0 ? void 0 : _props$grid4.infiniteScroll
	]);
	const content = /* @__PURE__ */ React.createElement(RecordBoardProvider, { value: contextValue }, children);
	return /* @__PURE__ */ React.createElement("div", {
		className: classNameProp ? `pisell-record-board-root ${classNameProp}` : "pisell-record-board-root",
		style: _objectSpread2({
			height: "100%",
			display: "flex",
			flexDirection: "column",
			minHeight: 0
		}, styleProp)
	}, content);
};
//#endregion
export { PisellRecordBoard as default };
