import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { _objectWithoutProperties } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext, { usePisellOS } from "../../hooks/useEngineContext.js";
import { request } from "../../utils/index.js";
import { getRelationTables } from "../pisellSalesManagement/serve.js";
import { ReservationBookingDetailModal } from "./components/bookingDetailModal/ReservationBookingDetailModal.js";
import { PISELL_RESERVATION_FLOOR_PLAN_CODE } from "./floorMap/floorPlanApi.js";
import { getReservationRenderItemByKind } from "./floorMap/reservationCards.js";
import { ReservationFloorMapHud, ReservationFloorMapHudTitleBar, reservationFloorMapHudSeatStatsTotal } from "./floorMap/ReservationFloorMapHud.js";
import { filterReservationRowsBoundOnCanvas } from "./floorMap/reservationHudTableRows.js";
import { useBookingPerspective } from "../pisellSalesManagement/hooks/useBookingPerspective.js";
import { getGridTableBookingSearchParams, usePisellReservationBookingData } from "./hooks/usePisellReservationBookingData.js";
import { usePisellReservationResourceTableData } from "./hooks/usePisellReservationResourceTableData.js";
import { GRID_DS_KEY, I18N_HUD_TABLE_DRAWER_TITLE, I18N_NEW_MODAL_PLACEHOLDER, I18N_NEW_MODAL_TITLE, PISELL_RESERVATION_HUD_DRAWER_COLUMN_STORAGE_KEY, PISELL_RESERVATION_PAGE_LOCALES, RESERVATION_TIMELINE_BUSINESS_RANGE } from "./reservationConstants.js";
import { computeReservationDensityBuckets, fitTimelineHighlightsToSlotCount, reservationTimelineAxisSlotCount } from "./data/reservationDensity.js";
import { filterBookingsByResourceIds } from "./data/bookingToReservationTables.js";
import { mergeGridBookingSearchParams, mergeSearchParamsBookingWindow, readBodyViewFromStorageKey, shouldUseBuiltinReservationList } from "./data/reservationDataUtils.js";
import { applyHudDrawerLocalListQuery, cloneHudDrawerSearchParams, mergeHudDrawerSearchParams, stripHudDrawerBookingDateQuickFilter } from "./data/hudDrawerLocalListQuery.js";
import { buildReservationMergedTableRows } from "./data/reservationTablesMerge.js";
import { sceneElementsToBoundFormRecordIds } from "./floorMap/floorMapBoundRecordIds.js";
import { PisellReservationScheduleEndActions, PisellReservationToolbarTabs, RecordBoardBodyViewCapture, ReservationDefaultScheduleStart, ReservationGridTopRight, ScheduleSyncOnFloorEnter } from "./components/PisellReservationSubcomponents.js";
import { useReservationFloorPlan } from "./floorMap/useReservationFloorPlan.js";
import { useReservationFloorMapMerged } from "./floorMap/useReservationFloorMapMerged.js";
import { useReservationScheduleDebounced } from "./hooks/useReservationScheduleDebounced.js";
import { useReservationSalesHostData } from "./hooks/useReservationSalesHostData.js";
import { useNewReservationRoutesFromEngine } from "./hooks/useNewReservationRoutesFromEngine.js";
import { useReservationLoadingShownDebounced } from "./hooks/useReservationLoadingShownDebounced.js";
import { useFloorMapBookingInteraction } from "./hooks/useFloorMapBookingInteraction.js";
import dayjs from "dayjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { Icon, PisellModal, PisellRecordBoard } from "@pisell/materials";
import classNames from "classnames";
import { useMemoizedFn, useRequest } from "ahooks";
import "dayjs/locale/zh-cn";
import "dayjs/locale/en";
import "dayjs/locale/zh-tw";
import { LocalizationProvider } from "@pisell/date-picker";
import { AdapterDayjs } from "@pisell/date-picker/es/AdapterDayjs";
import "./PisellReservation.less";
//#region src/plus/pisellReservation/PisellReservation.tsx
const _excluded = [
	"gridDataSourceKey",
	"dataSources",
	"scheduleValue",
	"onScheduleChange",
	"toolBar",
	"floorMap",
	"scheduleStartSlot",
	"scheduleEndSlot",
	"onNewReservation",
	"timeNavigatorProps",
	"scheduleProps",
	"fab",
	"defaultBodyView",
	"data",
	"total",
	"pagination",
	"onPageChange",
	"onSearch",
	"onReset",
	"searchParams",
	"loading",
	"rowKey",
	"className",
	"style",
	"floorPlanId",
	"floorPlanCanvasWidth",
	"floorPlanCanvasHeight",
	"floorPlanCode",
	"floorPlanName",
	"floorPlanSort",
	"floorPlanStatus",
	"onFloorPlanPersisted",
	"putFloorPlan",
	"onFloorMapBookingClick",
	"bodyViewSwitchable",
	"lockedBodyView",
	"bodyViewStorageKey",
	"floorMapHudTableDrawer"
], _excluded2 = [
	"tabs",
	"topRight",
	"bottomLeft"
];
/**
* 场控：仅把平面图 items 同步到父级，视口内不渲染独立 HUD（统计在固定抽屉标题栏）。
*/
function ReservationHudMapItemsSync({ items, setItems }) {
	useEffect(() => {
		setItems(items);
	}, [items, setItems]);
	return null;
}
/**
* 预约看板 Core：内置 Sales 预约列表 + 时间轴 + 平面图。
* 页面壳 {@link PisellReservationBookingPage} / {@link PisellVenueControlPage} 通过 props 组合默认行为。
*/
const PisellReservationCore = (props) => {
	var _engineCtx$engine, _engineCtx$appHelper, _engineCtx$appHelper$, _app$router, _app$router$getRoutes, _engineCtx$appHelper3, _floorMapProp$mode, _timeNavigatorPropsPr2, _timeNavigatorPropsPr3, _scroll$autoCalc, _scroll;
	const { gridDataSourceKey = GRID_DS_KEY, dataSources: dataSourcesProp, scheduleValue: scheduleValueProp, onScheduleChange, toolBar: toolBarProp, floorMap: floorMapProp, scheduleStartSlot: scheduleStartSlotProp, scheduleEndSlot: scheduleEndSlotProp, onNewReservation, timeNavigatorProps: timeNavigatorPropsProp, scheduleProps: schedulePropsProp, fab, defaultBodyView: _unusedDefaultBodyView, data: dataProp, total: totalProp, pagination: paginationProp, onPageChange: onPageChangeProp, onSearch: onSearchProp, onReset: onResetProp, searchParams: searchParamsProp, loading: loadingProp, rowKey = "id", className, style, floorPlanId: floorPlanIdProp, floorPlanCanvasWidth, floorPlanCanvasHeight, floorPlanCode, floorPlanName, floorPlanSort, floorPlanStatus, onFloorPlanPersisted, putFloorPlan, onFloorMapBookingClick, bodyViewSwitchable = true, lockedBodyView, bodyViewStorageKey, floorMapHudTableDrawer = false } = props, rest = _objectWithoutProperties(props, _excluded);
	const hudItemsRef = useRef([]);
	const [hudMapItems, setHudMapItems] = useState([]);
	const [hudDrawerOpen, setHudDrawerOpen] = useState(false);
	/** HUD 抽屉：当前画布绑定资源 id，用于在 floorDayBooking 列表上二次过滤展示 */
	const [hudDrawerResourceIds, setHudDrawerResourceIds] = useState(null);
	/** 抽屉内 RecordBoard：与打开瞬间父级筛参快照一致，后续 onSearch 仅改本地不露父级请求 */
	const [hudDrawerLocalSearchParams, setHudDrawerLocalSearchParams] = useState({});
	const hudDrawerSearchParamsOpenSnapshotRef = useRef({});
	/** HUD 表格：对已过滤全量行做客户端切片分页（与主表 HTTP 分页无关） */
	const [hudDrawerListPagination, setHudDrawerListPagination] = useState({
		pageNumber: 1,
		pageSize: 50
	});
	const isInternalListData = shouldUseBuiltinReservationList(dataProp, totalProp, paginationProp, onPageChangeProp);
	const resolvedFloorPlanId = floorPlanIdProp === null ? null : floorPlanIdProp === void 0 ? 1 : floorPlanIdProp;
	const effectiveFloorPlanCode = floorPlanCode !== null && floorPlanCode !== void 0 ? floorPlanCode : PISELL_RESERVATION_FLOOR_PLAN_CODE;
	const engineCtx = useEngineContext();
	const pisellos = usePisellOS();
	/** 低代码里 context 常每次给新 `pisellos` 对象，勿把 `pisellos` 放进 effect 依赖 */
	const pisellosRef = useRef(pisellos);
	pisellosRef.current = pisellos;
	const hasPisellosGetModule = typeof (pisellos === null || pisellos === void 0 ? void 0 : pisellos.getModule) === "function";
	const engineLocale = (engineCtx === null || engineCtx === void 0 || (_engineCtx$engine = engineCtx.engine) === null || _engineCtx$engine === void 0 || (_engineCtx$engine = _engineCtx$engine.props) === null || _engineCtx$engine === void 0 ? void 0 : _engineCtx$engine.locale) || "zh-CN";
	const app = engineCtx === null || engineCtx === void 0 || (_engineCtx$appHelper = engineCtx.appHelper) === null || _engineCtx$appHelper === void 0 || (_engineCtx$appHelper = _engineCtx$appHelper.utils) === null || _engineCtx$appHelper === void 0 || (_engineCtx$appHelper$ = _engineCtx$appHelper.getApp) === null || _engineCtx$appHelper$ === void 0 ? void 0 : _engineCtx$appHelper$.call(_engineCtx$appHelper);
	const router = app === null || app === void 0 || (_app$router = app.router) === null || _app$router === void 0 || (_app$router$getRoutes = _app$router.getRoutes) === null || _app$router$getRoutes === void 0 ? void 0 : _app$router$getRoutes.call(_app$router);
	const muiDatePickerAdapterLocale = useMemo(() => {
		const loc = String(engineLocale).toLowerCase();
		if (loc.startsWith("zh-cn")) return "zh-cn";
		if (loc.startsWith("zh-tw") || loc.startsWith("zh-hk")) return "zh-tw";
		return "en";
	}, [engineLocale]);
	useEffect(() => {
		var _engineCtx$appHelper2;
		const r = engineCtx === null || engineCtx === void 0 || (_engineCtx$appHelper2 = engineCtx.appHelper) === null || _engineCtx$appHelper2 === void 0 || (_engineCtx$appHelper2 = _engineCtx$appHelper2.utils) === null || _engineCtx$appHelper2 === void 0 ? void 0 : _engineCtx$appHelper2.request;
		if (r) request.setRequest(r);
	}, [engineCtx === null || engineCtx === void 0 || (_engineCtx$appHelper3 = engineCtx.appHelper) === null || _engineCtx$appHelper3 === void 0 || (_engineCtx$appHelper3 = _engineCtx$appHelper3.utils) === null || _engineCtx$appHelper3 === void 0 ? void 0 : _engineCtx$appHelper3.request]);
	locales.init(PISELL_RESERVATION_PAGE_LOCALES, engineLocale);
	const resourceBoardData = usePisellReservationResourceTableData(isInternalListData);
	const gridBookingData = usePisellReservationBookingData(isInternalListData, {
		listPageSize: 50,
		getInitialSearchParams: getGridTableBookingSearchParams,
		subscribeRealtimePush: true
	});
	const { baseFloorConfig, floorPlanRemoteId, setRemoteFloorPlanView } = useReservationFloorPlan({
		resolvedFloorPlanId,
		effectiveFloorPlanCode,
		gridDataSourceKey,
		floorMapConfigFromProp: floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.floorMapConfig,
		engineLocale
	});
	/** 与 `useReservationFloorMapMerged` 一致：受控 prop 覆盖远程合并后的 base */
	const floorConfigForBindings = useMemo(() => {
		var _floorMapProp$floorMa;
		return (_floorMapProp$floorMa = floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.floorMapConfig) !== null && _floorMapProp$floorMa !== void 0 ? _floorMapProp$floorMa : baseFloorConfig;
	}, [floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.floorMapConfig, baseFloorConfig]);
	const floorBoundFormRecordIds = useMemo(() => sceneElementsToBoundFormRecordIds(floorConfigForBindings.sceneElements, gridDataSourceKey), [floorConfigForBindings.sceneElements, gridDataSourceKey]);
	const floorDayBookingData = usePisellReservationBookingData(isInternalListData && !resourceBoardData.loading, {
		listPageSize: 999,
		extraRequestParams: useMemo(() => ({ form_record_ids: floorBoundFormRecordIds }), [floorBoundFormRecordIds])
	});
	const _getRelationTables = useRequest(getRelationTables);
	const bookingPerspective = useBookingPerspective(useMemo(() => ({ relationTables: _getRelationTables.data }), [_getRelationTables.data]));
	const runtimeContext = useMemo(() => ({
		refresh: () => {
			resourceBoardData.refresh();
			gridBookingData.refresh();
			floorDayBookingData.refresh();
		},
		refreshAsync: function() {
			var _ref = _asyncToGenerator(function* () {
				yield Promise.all([
					resourceBoardData.refreshAsync(),
					gridBookingData.refreshAsync(),
					floorDayBookingData.refreshAsync()
				]);
			});
			return function refreshAsync() {
				return _ref.apply(this, arguments);
			};
		}(),
		currentPerspective: "monitor"
	}), [
		resourceBoardData.refresh,
		resourceBoardData.refreshAsync,
		gridBookingData.refresh,
		gridBookingData.refreshAsync,
		floorDayBookingData.refresh,
		floorDayBookingData.refreshAsync
	]);
	const bookingChildProps = useMemo(() => {
		const build = bookingPerspective.getChildComponentProps;
		return build ? build(runtimeContext) : {};
	}, [bookingPerspective, runtimeContext]);
	const { internalSchedule, setInternalSchedule, schedule, debouncedSchedule, flushCommittedSchedule, queueCommittedSchedule } = useReservationScheduleDebounced({ scheduleValueProp });
	/** 上一次「防抖落定」的日历日，用于仅在换日时 patch floorDayBooking 的 booking 时间窗口 */
	const prevCommittedDateRef = useRef(null);
	const { salesResourceBookings, salesTimelineHighlights } = useReservationSalesHostData({
		isInternalListData,
		pisellosRef,
		hasPisellosGetModule,
		debouncedSchedule,
		resourceBoardLoading: resourceBoardData.loading,
		floorDayBookingLoading: floorDayBookingData.loading,
		floorDayBookingData: floorDayBookingData.data,
		scheduleDate: schedule.date,
		timeNavigatorPropsProp
	});
	/** 合并资源行 + 当日预约 + 可选宿主游标列表；平面图 renderItem 与表格共用同一 dataSources */
	const tables = useMemo(() => buildReservationMergedTableRows({
		dataSourcesProp,
		gridDataSourceKey,
		isInternalListData,
		resourceList: resourceBoardData.data,
		floorDayBookingList: floorDayBookingData.data,
		schedule,
		dataProp,
		salesResourceBookings
	}), [
		dataSourcesProp,
		gridDataSourceKey,
		isInternalListData,
		resourceBoardData.data,
		floorDayBookingData.data,
		salesResourceBookings,
		dayjs(schedule.date).isValid() ? dayjs(schedule.date).startOf("day").valueOf() : 0,
		schedule.at != null && dayjs(schedule.at).isValid() ? dayjs(schedule.at).valueOf() : 0,
		dataProp
	]);
	/** 顶栏日程防抖落定后的时间键，避免 dayjs 引用抖动 */
	const debouncedScheduleKey = useMemo(() => `${dayjs(debouncedSchedule.date).startOf("day").valueOf()}_${dayjs(debouncedSchedule.at).valueOf()}`, [debouncedSchedule.date, debouncedSchedule.at]);
	/** 调试：切换时间（防抖落定）后，打印当前用于展示的预约相关数据（含接口返回后的更新） */
	useEffect(() => {
		if (!dayjs(debouncedSchedule.date).isValid() || !dayjs(debouncedSchedule.at).isValid()) return;
		console.log("[PisellReservation] 当前日程下的展示数据", {
			debouncedScheduleKey,
			reservationDate: debouncedSchedule.date.toISOString(),
			reservationAt: debouncedSchedule.at.toISOString(),
			isInternalListData,
			gridBookingLoading: isInternalListData ? gridBookingData.loading : void 0,
			floorDayBookingLoading: isInternalListData ? floorDayBookingData.loading : void 0,
			gridBookingList: isInternalListData ? gridBookingData.data : void 0,
			floorDayBookingList: isInternalListData ? floorDayBookingData.data : void 0,
			mergedTableRows: tables,
			externalControlledData: !isInternalListData ? dataProp : void 0
		});
	}, [
		debouncedScheduleKey,
		debouncedSchedule.date,
		debouncedSchedule.at,
		isInternalListData,
		gridBookingData.data,
		gridBookingData.loading,
		floorDayBookingData.data,
		floorDayBookingData.loading,
		tables,
		dataProp
	]);
	const bodyViewRef = useRef(readBodyViewFromStorageKey(bodyViewStorageKey));
	const floorMapLayoutRef = useRef(null);
	const [followWallClock, setFollowWallClock] = useState(true);
	const [isNewReservationModalOpen, setIsNewReservationModalOpen] = useState(false);
	const newReservationRoutes = useNewReservationRoutesFromEngine(router);
	const searchParamsRefControlled = useRef(searchParamsProp);
	useEffect(() => {
		searchParamsRefControlled.current = searchParamsProp;
	}, [searchParamsProp]);
	const onSearchRef = useRef(onSearchProp);
	const onScheduleChangeRef = useRef(onScheduleChange);
	/** 每帧同步，供 interval / effect 内调用最新 onSearch、onScheduleChange，避免闭包陈旧 */
	useEffect(() => {
		onSearchRef.current = onSearchProp;
		onScheduleChangeRef.current = onScheduleChange;
	});
	/**
	* `debouncedSchedule` 更新后执行（用户停手约 300ms 或 flush）：
	* - 内置列表：换日历日则更新 floorDayBooking 的 booking_time 窗口；
	* - 外部 data + 当前 bodyView 为平面图：把 reservationDate/At 透传给外部 onSearch。
	*/
	useEffect(() => {
		if (isInternalListData) {
			const d = debouncedSchedule.date;
			const prev = prevCommittedDateRef.current;
			if (prev != null) {
				if (!d.startOf("day").isSame(prev.startOf("day"), "day")) floorDayBookingData.patchSearchParams((prevParams) => mergeSearchParamsBookingWindow(prevParams, d));
			}
			prevCommittedDateRef.current = d;
		}
		if (bodyViewRef.current === "floorMap" && !isInternalListData) {
			var _onSearchRef$current, _searchParamsRefContr;
			(_onSearchRef$current = onSearchRef.current) === null || _onSearchRef$current === void 0 || _onSearchRef$current.call(onSearchRef, _objectSpread2(_objectSpread2({}, (_searchParamsRefContr = searchParamsRefControlled.current) !== null && _searchParamsRefContr !== void 0 ? _searchParamsRefContr : {}), {}, {
				reservationDate: debouncedSchedule.date.toISOString(),
				reservationAt: debouncedSchedule.at.toISOString()
			}));
		}
	}, [
		debouncedSchedule,
		isInternalListData,
		floorDayBookingData.patchSearchParams
	]);
	const handleScheduleChange = useCallback((next) => {
		setFollowWallClock(false);
		if (scheduleValueProp === void 0) setInternalSchedule(next);
		onScheduleChange === null || onScheduleChange === void 0 || onScheduleChange(next);
		queueCommittedSchedule(next);
	}, [
		scheduleValueProp,
		onScheduleChange,
		setFollowWallClock,
		queueCommittedSchedule
	]);
	/** 先展开外部 dataSources，再用合并后的 `tables` 覆盖同名 key，避免低代码默认的 `tables: []` 盖掉 resource+booking 合并结果 */
	const dataSources = useMemo(() => {
		return _objectSpread2(_objectSpread2({}, dataSourcesProp), {}, { [gridDataSourceKey]: tables });
	}, [
		gridDataSourceKey,
		tables,
		dataSourcesProp
	]);
	const showVenueHudDock = useMemo(() => floorMapHudTableDrawer && (hudDrawerOpen || reservationFloorMapHudSeatStatsTotal(hudMapItems, dataSources) > 0), [
		floorMapHudTableDrawer,
		hudDrawerOpen,
		hudMapItems,
		dataSources
	]);
	const handleOpenHudTableDrawer = useCallback(() => {
		const boundTableRows = filterReservationRowsBoundOnCanvas(hudItemsRef.current, dataSources, gridDataSourceKey);
		const resourceIdSet = new Set(boundTableRows.map((r) => String(r.id)).filter(Boolean));
		const parentSnapshot = cloneHudDrawerSearchParams(isInternalListData ? floorDayBookingData.searchParams : searchParamsProp !== null && searchParamsProp !== void 0 ? searchParamsProp : {});
		stripHudDrawerBookingDateQuickFilter(parentSnapshot);
		hudDrawerSearchParamsOpenSnapshotRef.current = parentSnapshot;
		setHudDrawerLocalSearchParams(parentSnapshot);
		setHudDrawerResourceIds(resourceIdSet);
		setHudDrawerListPagination({
			pageNumber: 1,
			pageSize: 50
		});
		setHudDrawerOpen(true);
	}, [
		dataSources,
		gridDataSourceKey,
		isInternalListData,
		floorDayBookingData.searchParams,
		searchParamsProp
	]);
	const closeHudTableDrawer = useCallback(() => {
		setHudDrawerOpen(false);
		setHudDrawerResourceIds(null);
		setHudDrawerLocalSearchParams({});
		setHudDrawerListPagination({
			pageNumber: 1,
			pageSize: 50
		});
	}, []);
	useEffect(() => {
		if (!floorMapHudTableDrawer || !hudDrawerOpen) return;
		const onKeyDown = (e) => {
			if (e.key === "Escape") closeHudTableDrawer();
		};
		window.addEventListener("keydown", onKeyDown);
		return () => window.removeEventListener("keydown", onKeyDown);
	}, [
		floorMapHudTableDrawer,
		hudDrawerOpen,
		closeHudTableDrawer
	]);
	/**
	* 数据仍来自父级 floorDayBooking / 受控 data（随接口更新）；画布资源子集后再做抽屉本地 keyword/filter/sort。
	*/
	const hudDrawerDisplayRows = useMemo(() => {
		if (!floorMapHudTableDrawer || !hudDrawerOpen || !hudDrawerResourceIds || hudDrawerResourceIds.size === 0) return [];
		return applyHudDrawerLocalListQuery(filterBookingsByResourceIds(isInternalListData ? floorDayBookingData.data : dataProp !== null && dataProp !== void 0 ? dataProp : [], hudDrawerResourceIds), hudDrawerLocalSearchParams);
	}, [
		floorMapHudTableDrawer,
		hudDrawerOpen,
		hudDrawerResourceIds,
		isInternalListData,
		floorDayBookingData.data,
		dataProp,
		hudDrawerLocalSearchParams
	]);
	const hudDrawerFilteredTotal = hudDrawerDisplayRows.length;
	const hudDrawerMaxPage = Math.max(1, Math.ceil(hudDrawerFilteredTotal / hudDrawerListPagination.pageSize) || 1);
	/** 过滤后条数变少时，避免当前页超出末页 */
	useEffect(() => {
		if (hudDrawerListPagination.pageNumber <= hudDrawerMaxPage) return;
		setHudDrawerListPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: hudDrawerMaxPage }));
	}, [hudDrawerMaxPage, hudDrawerListPagination.pageNumber]);
	const hudDrawerPagedRows = useMemo(() => {
		const { pageNumber, pageSize } = hudDrawerListPagination;
		const start = (pageNumber - 1) * pageSize;
		return hudDrawerDisplayRows.slice(start, start + pageSize);
	}, [hudDrawerDisplayRows, hudDrawerListPagination]);
	const hudDrawerToolBar = useMemo(() => {
		const raw = bookingChildProps.toolBar;
		const base = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
		const baseClass = "className" in base && typeof base.className === "string" ? base.className : void 0;
		return _objectSpread2(_objectSpread2({}, base), {}, {
			toolbarDensity: "compact",
			quickFilter: false,
			className: classNames(baseClass, "pisell-record-board-toolbar--narrow-stack")
		});
	}, [bookingChildProps.toolBar]);
	const hudDrawerLoading = isInternalListData ? floorDayBookingData.loading : loadingProp !== null && loadingProp !== void 0 ? loadingProp : false;
	const hudDrawerBookingPagination = useMemo(() => ({
		pageNumber: hudDrawerListPagination.pageNumber,
		pageSize: hudDrawerListPagination.pageSize
	}), [hudDrawerListPagination.pageNumber, hudDrawerListPagination.pageSize]);
	const hudDrawerOnSearch = useCallback((params) => {
		setHudDrawerListPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: 1 }));
		setHudDrawerLocalSearchParams((prev) => mergeHudDrawerSearchParams(prev, params));
	}, []);
	const hudDrawerOnReset = useCallback(() => {
		setHudDrawerListPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: 1 }));
		setHudDrawerLocalSearchParams(cloneHudDrawerSearchParams(hudDrawerSearchParamsOpenSnapshotRef.current));
	}, []);
	const hudDrawerOnPageChange = useCallback((pageNumber, pageSize) => {
		setHudDrawerListPagination({
			pageNumber,
			pageSize
		});
	}, []);
	/** antd 分页默认不展示「每页条数」；HUD 为本地切片，需显式开启 */
	const hudRecordBoardPaginationConfig = useMemo(() => ({
		showSizeChanger: true,
		pageSizeOptions: [
			"10",
			"20",
			"50",
			"100"
		]
	}), []);
	const renderItemByKind = useMemo(() => getReservationRenderItemByKind(dataSources), [dataSources]);
	const reservationFloorMapViewportOverlay = useCallback((args) => {
		const items = args.items;
		hudItemsRef.current = items;
		if (floorMapHudTableDrawer) return /* @__PURE__ */ React.createElement(ReservationHudMapItemsSync, {
			items,
			setItems: setHudMapItems
		});
		return /* @__PURE__ */ React.createElement(ReservationFloorMapHud, {
			items,
			dataSources: args.dataSources,
			interactive: false
		});
	}, [floorMapHudTableDrawer]);
	const isFloorModeControlled = (floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.mode) !== void 0;
	const [mapEditInternal, setMapEditInternal] = useState(false);
	const effectiveMapMode = (_floorMapProp$mode = floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.mode) !== null && _floorMapProp$mode !== void 0 ? _floorMapProp$mode : mapEditInternal ? "edit" : "read";
	const { bookingDetailOpen, bookingDetailRaw, bookingDetailRow, bookingDetailSceneName, closeBookingDetailModal, floorMapItemClickBefore } = useFloorMapBookingInteraction({
		engineCtx,
		onFloorMapBookingClick
	});
	const floorMapMerged = useReservationFloorMapMerged({
		floorMapProp,
		baseFloorConfig,
		dataSources,
		renderItemByKind,
		gridDataSourceKey,
		effectiveMapMode,
		resolvedFloorPlanId,
		floorPlanRemoteId,
		effectiveFloorPlanCode,
		floorPlanCanvasWidth,
		floorPlanCanvasHeight,
		floorPlanName,
		floorPlanSort,
		floorPlanStatus,
		onFloorPlanPersisted,
		putFloorPlan,
		isFloorModeControlled,
		mapEditInternal,
		setMapEditInternal,
		floorMapLayoutRef,
		reservationFloorMapViewportOverlay,
		setRemoteFloorPlanView,
		floorMapItemClickBefore,
		engineLocale,
		floorMapHudTableDrawer
	});
	const data = isInternalListData ? gridBookingData.data : dataProp !== null && dataProp !== void 0 ? dataProp : [];
	const loadingShown = useReservationLoadingShownDebounced(isInternalListData ? gridBookingData.loading : loadingProp !== null && loadingProp !== void 0 ? loadingProp : false);
	const total = isInternalListData ? gridBookingData.total : totalProp !== null && totalProp !== void 0 ? totalProp : 0;
	const pagination = isInternalListData ? gridBookingData.pagination : paginationProp !== null && paginationProp !== void 0 ? paginationProp : {
		pageNumber: 1,
		pageSize: 50
	};
	const onPageChange = isInternalListData ? gridBookingData.onPageChange : onPageChangeProp;
	const searchParams = isInternalListData ? gridBookingData.searchParams : searchParamsProp !== null && searchParamsProp !== void 0 ? searchParamsProp : {};
	const onGridBookingSearch = useCallback((params) => {
		gridBookingData.onSearch(mergeGridBookingSearchParams(params));
	}, [gridBookingData.onSearch]);
	const onSearch = isInternalListData ? onGridBookingSearch : onSearchProp;
	const onReset = isInternalListData ? gridBookingData.onReset : onResetProp;
	const handleRouteJump = useMemoizedFn((routePath) => {
		var _app$history, _app$history$push;
		if (!routePath) return;
		setIsNewReservationModalOpen(false);
		app === null || app === void 0 || (_app$history = app.history) === null || _app$history === void 0 || (_app$history$push = _app$history.push) === null || _app$history$push === void 0 || _app$history$push.call(_app$history, routePath);
	});
	const handleOpenNewReservationModal = useMemoizedFn(() => {
		if (newReservationRoutes.length === 1) {
			handleRouteJump(newReservationRoutes[0].router);
			return;
		}
		setIsNewReservationModalOpen(true);
	});
	const handleCloseNewReservationModal = useMemoizedFn(() => {
		setIsNewReservationModalOpen(false);
	});
	useEffect(() => {
		if (!followWallClock) return;
		const tick = () => {
			var _onScheduleChangeRef$;
			const now = dayjs();
			const next = {
				date: now.startOf("day"),
				at: now
			};
			if (scheduleValueProp === void 0) setInternalSchedule(next);
			(_onScheduleChangeRef$ = onScheduleChangeRef.current) === null || _onScheduleChangeRef$ === void 0 || _onScheduleChangeRef$.call(onScheduleChangeRef, next);
			/** 跟随当前：立即提交日程，patch / 外部 onSearch 由 debouncedSchedule effect 统一处理 */
			flushCommittedSchedule(next);
		};
		tick();
		const id = window.setInterval(tick, 3e4);
		return () => window.clearInterval(id);
	}, [
		followWallClock,
		scheduleValueProp,
		flushCommittedSchedule
	]);
	const defaultScheduleEnd = useMemo(() => /* @__PURE__ */ React.createElement(PisellReservationScheduleEndActions, { onNewReservation: handleOpenNewReservationModal }), [handleOpenNewReservationModal]);
	const effectiveScheduleEndSlot = useMemo(() => {
		const slotNode = scheduleEndSlotProp !== null && scheduleEndSlotProp !== void 0 ? scheduleEndSlotProp : defaultScheduleEnd;
		return /* @__PURE__ */ React.createElement("div", { onClickCapture: (event) => {
			const target = event.target;
			if (!(target === null || target === void 0 ? void 0 : target.closest(".pisell-reservation-new-btn"))) return;
			/** 日程带子组件内点击「新建」时，阻止事件冒泡到 ScheduleBand，避免误触日期导航 */
			event.preventDefault();
			event.stopPropagation();
			handleOpenNewReservationModal();
		} }, slotNode);
	}, [
		scheduleEndSlotProp,
		defaultScheduleEnd,
		handleOpenNewReservationModal
	]);
	const bookingToolBar = bookingChildProps.toolBar;
	/** 时间轴密度：优先用宿主 getTimelineHighlights；否则用本地按预约行计算 */
	const loadReservationDensity = useCallback(function() {
		var _ref2 = _asyncToGenerator(function* ({ referenceDate, stepMinutes }) {
			var _timeNavigatorPropsPr;
			const slotCount = reservationTimelineAxisSlotCount(referenceDate, stepMinutes, (_timeNavigatorPropsPr = timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 ? void 0 : timeNavigatorPropsProp.range) !== null && _timeNavigatorPropsPr !== void 0 ? _timeNavigatorPropsPr : RESERVATION_TIMELINE_BUSINESS_RANGE);
			if (salesTimelineHighlights != null && salesTimelineHighlights.length > 0) return fitTimelineHighlightsToSlotCount(salesTimelineHighlights, slotCount);
			return computeReservationDensityBuckets(isInternalListData ? floorDayBookingData.data : data, referenceDate, stepMinutes);
		});
		return function(_x) {
			return _ref2.apply(this, arguments);
		};
	}(), [
		isInternalListData,
		floorDayBookingData.data,
		data,
		salesTimelineHighlights,
		timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 || (_timeNavigatorPropsPr2 = timeNavigatorPropsProp.range) === null || _timeNavigatorPropsPr2 === void 0 ? void 0 : _timeNavigatorPropsPr2.start,
		timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 || (_timeNavigatorPropsPr3 = timeNavigatorPropsProp.range) === null || _timeNavigatorPropsPr3 === void 0 ? void 0 : _timeNavigatorPropsPr3.end
	]);
	const toolBarMerged = useMemo(() => {
		const _ref3 = toolBarProp !== null && toolBarProp !== void 0 ? toolBarProp : {}, { tabs: extraTabs, topRight: topRightProp, bottomLeft: bottomLeftProp } = _ref3, restToolbar = _objectWithoutProperties(_ref3, _excluded2);
		return _objectSpread2(_objectSpread2(_objectSpread2({}, bookingToolBar !== null && bookingToolBar !== void 0 ? bookingToolBar : {}), restToolbar), {}, {
			tabs: /* @__PURE__ */ React.createElement(PisellReservationToolbarTabs, {
				extraTabs,
				schedule,
				onScheduleChange: handleScheduleChange,
				scheduleProps: schedulePropsProp,
				timeNavigatorProps: timeNavigatorPropsProp,
				scheduleStartSlot: scheduleStartSlotProp !== null && scheduleStartSlotProp !== void 0 ? scheduleStartSlotProp : /* @__PURE__ */ React.createElement(ReservationDefaultScheduleStart, null),
				scheduleEndSlot: effectiveScheduleEndSlot,
				followWallClock,
				onFollowWallClockToggle: () => setFollowWallClock((v) => !v),
				onTimeNavigatorUserInteraction: () => setFollowWallClock(false),
				loadDensity: loadReservationDensity
			}),
			topRight: /* @__PURE__ */ React.createElement(ReservationGridTopRight, { extra: topRightProp }),
			bottomLeft: bottomLeftProp !== null && bottomLeftProp !== void 0 ? bottomLeftProp : null
		});
	}, [
		bookingToolBar,
		toolBarProp,
		schedule,
		handleScheduleChange,
		scheduleStartSlotProp,
		effectiveScheduleEndSlot,
		followWallClock,
		timeNavigatorPropsProp,
		schedulePropsProp,
		loadReservationDensity
	]);
	const recordBoardGrid = useMemo(() => {
		return bookingChildProps.grid;
	}, [bookingChildProps.grid]);
	/** HUD 内嵌表单独小号，不修改主 RecordBoard 共用的 grid 引用 */
	const hudDrawerGrid = useMemo(() => {
		const g = recordBoardGrid;
		if (g == null || typeof g !== "object") return { size: "small" };
		return _objectSpread2(_objectSpread2({}, g), {}, { size: "small" });
	}, [recordBoardGrid]);
	const fillHeight = (_scroll$autoCalc = recordBoardGrid === null || recordBoardGrid === void 0 || (_scroll = recordBoardGrid.scroll) === null || _scroll === void 0 ? void 0 : _scroll.autoCalc) !== null && _scroll$autoCalc !== void 0 ? _scroll$autoCalc : true;
	return /* @__PURE__ */ React.createElement(LocalizationProvider, {
		dateAdapter: AdapterDayjs,
		adapterLocale: muiDatePickerAdapterLocale
	}, /* @__PURE__ */ React.createElement("div", {
		className: classNames("pisell-reservation-page", className),
		style
	}, /* @__PURE__ */ React.createElement(PisellRecordBoard, _objectSpread2(_objectSpread2({}, rest), {}, {
		fillHeight,
		rowKey,
		data,
		dataSources,
		loading: loadingShown,
		total,
		pagination,
		onPageChange,
		searchParams,
		onSearch,
		onReset,
		grid: recordBoardGrid,
		toolBar: toolBarMerged,
		search: bookingChildProps.search,
		batchActionBar: bookingChildProps.batchActionBar,
		floorMap: floorMapMerged,
		defaultBodyView: "floorMap",
		bodyViewStorageKey,
		bodyViewSwitchable,
		lockedBodyView,
		floorMapLayoutRef
	}), /* @__PURE__ */ React.createElement(PisellRecordBoard.ShellFrame, null, /* @__PURE__ */ React.createElement(RecordBoardBodyViewCapture, { bodyViewRef }), /* @__PURE__ */ React.createElement(ScheduleSyncOnFloorEnter, {
		schedule,
		isInternalListData,
		patchSearchParams: floorDayBookingData.patchSearchParams
	}), /* @__PURE__ */ React.createElement(PisellRecordBoard.GridLayout, null), /* @__PURE__ */ React.createElement(PisellRecordBoard.FloorMap, null))), /* @__PURE__ */ React.createElement(PisellModal, {
		platform: "pc",
		open: isNewReservationModalOpen,
		title: locales.getText(I18N_NEW_MODAL_TITLE),
		onCancel: handleCloseNewReservationModal,
		maskClosable: true,
		footer: null,
		width: 520,
		wrapClassName: "pisell-reservation-new-modal-wrap",
		destroyOnClose: true
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-reservation-new-modal-placeholder" }, newReservationRoutes.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "pisell-reservation-new-modal-route-list" }, newReservationRoutes.map((routeItem) => /* @__PURE__ */ React.createElement("button", {
		key: `${routeItem.router}-${routeItem.pageName}`,
		type: "button",
		className: "pisell-reservation-new-modal-route-item",
		onClick: () => handleRouteJump(routeItem.router)
	}, /* @__PURE__ */ React.createElement("span", { className: "pisell-reservation-new-modal-route-name" }, routeItem.pageName), /* @__PURE__ */ React.createElement(Icon, {
		type: "icon-right-arrow",
		className: "pisell-reservation-new-modal-route-arrow"
	})))) : /* @__PURE__ */ React.createElement("p", { className: "pisell-reservation-new-modal-empty" }, locales.getText(I18N_NEW_MODAL_PLACEHOLDER)))), /* @__PURE__ */ React.createElement(ReservationBookingDetailModal, {
		open: bookingDetailOpen,
		onClose: closeBookingDetailModal,
		raw: bookingDetailRaw,
		tableRow: bookingDetailRow,
		sceneElementName: bookingDetailSceneName
	}), fab ? /* @__PURE__ */ React.createElement("div", { className: "pisell-reservation-fab" }, fab) : null, showVenueHudDock ? /* @__PURE__ */ React.createElement("div", {
		className: classNames("pisell-reservation-hud-dock", hudDrawerOpen && "pisell-reservation-hud-dock--expanded"),
		role: "dialog",
		"aria-modal": "false",
		"aria-expanded": hudDrawerOpen,
		"aria-label": locales.getText(I18N_HUD_TABLE_DRAWER_TITLE)
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-reservation-hud-dock-header" }, /* @__PURE__ */ React.createElement(ReservationFloorMapHudTitleBar, {
		items: hudMapItems,
		dataSources,
		actionMode: hudDrawerOpen ? "collapse" : "expand",
		onAction: hudDrawerOpen ? closeHudTableDrawer : handleOpenHudTableDrawer,
		embedded: true,
		className: "pisell-reservation-hud-dock-title-inner"
	})), hudDrawerOpen ? /* @__PURE__ */ React.createElement("div", { className: "pisell-reservation-hud-dock-body" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-reservation-hud-dock-record-board" }, /* @__PURE__ */ React.createElement(PisellRecordBoard, {
		columnVisibilityStorageKey: PISELL_RESERVATION_HUD_DRAWER_COLUMN_STORAGE_KEY,
		rowKey,
		data: hudDrawerPagedRows,
		loading: hudDrawerLoading,
		total: hudDrawerFilteredTotal,
		pagination: hudDrawerBookingPagination,
		onPageChange: hudDrawerOnPageChange,
		paginationConfig: hudRecordBoardPaginationConfig,
		searchParams: hudDrawerLocalSearchParams,
		onSearch: hudDrawerOnSearch,
		onReset: hudDrawerOnReset,
		grid: hudDrawerGrid,
		toolBar: hudDrawerToolBar,
		batchActionBar: bookingChildProps.batchActionBar,
		defaultBodyView: "grid",
		bodyViewSwitchable: false,
		lockedBodyView: "grid"
	}, /* @__PURE__ */ React.createElement(PisellRecordBoard.ShellFrame, null, /* @__PURE__ */ React.createElement(PisellRecordBoard.GridLayout, null))))) : null) : null));
};
//#endregion
export { PisellReservationCore };
