const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_index = require("../../../utils/index.js");
const require_reservationConstants = require("../reservationConstants.js");
const require_calendarAdapter = require("../data/calendarAdapter.js");
const require_reservationDataUtils = require("../data/reservationDataUtils.js");
const require_bookingCalendarMoveIntegration = require("../data/bookingCalendarMoveIntegration.js");
const require_index$1 = require("../components/blockTimeModal/index.js");
const require_ReservationCalendarBookingNode = require("../components/ReservationCalendarBookingNode.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let ahooks = require("ahooks");
//#region src/plus/pisellReservation/hooks/useReservationCalendarSlot.tsx
/**
* 预约看板日历槽：视口合并、预约条渲染、锁台/改期、加载态与 RecordBoard 日历 props。
*/
/**
* 日历拖拽后挡一次误触详情的 ref（仅日历槽内部使用）。
*/
function useCalendarDragSuppressRef() {
	return (0, react.useRef)({
		bookingId: null,
		timer: null
	});
}
function useReservationCalendarSlot(p) {
	const { isInternalListData, floorDayBookingData, operatingDayBoundary, tables, openBookingDetailFromRaw, schedule, handleScheduleChange, calendarResources, calendarBookings, effectiveTimelineRange, runtimeContext } = p;
	const calendarDragSuppressDetailRef = useCalendarDragSuppressRef();
	const [calendarGranularity, setCalendarGranularity] = (0, react.useState)("week");
	const calendarLoadedKeySetRef = (0, react.useRef)(/* @__PURE__ */ new Set());
	const calendarInflightKeyRef = (0, react.useRef)(null);
	const prevFloorDayLoadingRef = (0, react.useRef)(false);
	const handleCalendarAnchorChange = (0, react.useCallback)((d) => {
		const dj = (0, dayjs.default)(d).startOf("day");
		const atSrc = (0, dayjs.default)(schedule.at);
		handleScheduleChange({
			date: dj,
			at: dj.hour(atSrc.hour()).minute(atSrc.minute()).second(0).millisecond(0)
		});
	}, [handleScheduleChange, schedule.at]);
	const handleCalendarViewportChange = (0, react.useCallback)((payload) => {
		if (!isInternalListData) return;
		floorDayBookingData.patchSearchParams((prev) => {
			const merged = require_reservationDataUtils.mergeSearchParamsBookingRange(prev, payload.rangeStart, payload.rangeEnd, operatingDayBoundary);
			const filterObj = merged.filter && typeof merged.filter === "object" ? merged.filter : {};
			const valuesObj = filterObj.values && typeof filterObj.values === "object" ? require_objectSpread2._objectSpread2({}, filterObj.values) : {};
			if (payload.view === "week" || payload.view === "month" || payload.view === "resource") {
				valuesObj.enable_remote_memory_cache = true;
				valuesObj.compact_fields = true;
			} else {
				delete valuesObj.enable_remote_memory_cache;
				delete valuesObj.compact_fields;
			}
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, merged), {}, { filter: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, filterObj), {}, { values: valuesObj }) });
		});
	}, [
		isInternalListData,
		floorDayBookingData.patchSearchParams,
		operatingDayBoundary
	]);
	const handleCalendarBookingClick = (0, react.useCallback)((item) => {
		const raw = item.raw;
		if (!raw || typeof raw !== "object") return false;
		openBookingDetailFromRaw({
			raw,
			row: require_calendarAdapter.findMergedTableRowForBookingRaw(raw, tables)
		});
		return true;
	}, [openBookingDetailFromRaw, tables]);
	const reservationCalendarPersist = (0, react.useMemo)(() => {
		return { beforePersist: () => {
			antd.message.warning(_pisell_utils.locales.getText(require_reservationConstants.I18N_CALENDAR_WRITE_NOT_AVAILABLE));
			return false;
		} };
	}, []);
	const renderReservationCalendarBooking = (0, react.useCallback)((args) => /* @__PURE__ */ react.default.createElement(require_ReservationCalendarBookingNode.ReservationCalendarBookingNode, {
		args,
		tables,
		calendarDragSuppressDetailRef
	}), [tables]);
	const handleBlockedTimePanelRequest = (0, ahooks.useMemoizedFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (payload) {
			const { mergedRange, slotStepMinutes } = payload;
			try {
				yield require_index$1.default.open({
					resources: calendarResources,
					initialResourceId: mergedRange.courtId,
					initialTimeRange: [require_calendarAdapter.dayjsFromCalendarHour(mergedRange.date, mergedRange.startHour), require_calendarAdapter.dayjsFromCalendarHour(mergedRange.date, mergedRange.endHour)],
					minuteStep: slotStepMinutes,
					blockedSalesChannels: ["online_store"],
					onSubmit: function() {
						var _ref = require_asyncToGenerator._asyncToGenerator(function* ({ submitPayload }) {
							yield require_index.request.getRequest().post("/shop/schedule/blocked-time", submitPayload);
							antd.message.success("保存成功");
							yield runtimeContext.refreshAsync();
						});
						return function onSubmit(_x) {
							return _ref.apply(this, arguments);
						};
					}()
				});
				return true;
			} catch (_unused) {
				return false;
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	const handleCalendarBookingMoveRequest = (0, ahooks.useMemoizedFn)(function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (payload) {
			return require_bookingCalendarMoveIntegration.openBookingChangeModalAfterCalendarDrag({
				calendarItem: payload.item,
				draft: payload.draft,
				calendarResources,
				calendarBookings,
				effectiveTimelineRange,
				anchorDate: schedule.date.toDate(),
				slotStepMinutes: 30,
				onSuccessRefresh: function() {
					var _ref3 = require_asyncToGenerator._asyncToGenerator(function* () {
						yield runtimeContext.refreshAsync();
					});
					return function onSuccessRefresh() {
						return _ref3.apply(this, arguments);
					};
				}()
			});
		});
		return function(_x3) {
			return _ref4.apply(this, arguments);
		};
	}());
	const calendarLoadKey = (0, react.useMemo)(() => `${calendarGranularity}_${(0, dayjs.default)(schedule.date).startOf("day").valueOf()}_${(0, dayjs.default)(schedule.at).valueOf()}`, [
		calendarGranularity,
		schedule.date,
		schedule.at
	]);
	(0, react.useEffect)(() => {
		const prev = prevFloorDayLoadingRef.current;
		const now = floorDayBookingData.loading;
		if (!prev && now) calendarInflightKeyRef.current = calendarLoadKey;
		else if (prev && now && calendarInflightKeyRef.current !== calendarLoadKey) calendarInflightKeyRef.current = calendarLoadKey;
		else if (prev && !now) {
			var _calendarInflightKeyR;
			const doneKey = (_calendarInflightKeyR = calendarInflightKeyRef.current) !== null && _calendarInflightKeyR !== void 0 ? _calendarInflightKeyR : calendarLoadKey;
			calendarLoadedKeySetRef.current.add(doneKey);
			calendarInflightKeyRef.current = null;
		}
		prevFloorDayLoadingRef.current = now;
	}, [floorDayBookingData.loading, calendarLoadKey]);
	(0, react.useMemo)(() => {
		if (calendarGranularity === "week" || calendarGranularity === "month" || calendarGranularity === "resource") return false;
		if (!floorDayBookingData.loading) return false;
		return !calendarLoadedKeySetRef.current.has(calendarLoadKey);
	}, [
		floorDayBookingData.loading,
		calendarLoadKey,
		calendarGranularity
	]);
	/** Create booking：仅打印选中的资源与时段（不接本地写入 / 不打开新建弹窗），并绕过 persistGuard */
	const onCreateBookingFromSelection = (0, ahooks.useMemoizedFn)((payload) => {
		const resourceName = (id) => {
			var _calendarResources$fi, _calendarResources$fi2;
			return (_calendarResources$fi = (_calendarResources$fi2 = calendarResources.find((r) => String(r.id) === String(id))) === null || _calendarResources$fi2 === void 0 ? void 0 : _calendarResources$fi2.name) !== null && _calendarResources$fi !== void 0 ? _calendarResources$fi : id;
		};
		if (payload.mode === "day") {
			console.log("[Create booking] 日视图", { groups: payload.groups.map((g) => ({
				resourceId: g.courtId,
				resourceName: resourceName(g.courtId),
				date: g.date,
				startHour: g.startHour,
				endHour: g.endHour
			})) });
			return;
		}
		const { courtId, dates, startHour, endHour } = payload;
		console.log("[Create booking] 资源视图", {
			resourceId: courtId,
			resourceName: resourceName(courtId),
			dates,
			dateRange: dates.length > 1 ? `${dates[0]} ~ ${dates[dates.length - 1]}` : dates[0],
			startHour,
			endHour
		});
	});
	return {
		reservationCalendarSlotProps: (0, react.useMemo)(() => {
			return {
				persistGuard: reservationCalendarPersist,
				resources: calendarResources,
				bookings: calendarBookings,
				loading: false,
				onViewportChange: handleCalendarViewportChange,
				onBookingClick: handleCalendarBookingClick,
				timelineRange: effectiveTimelineRange,
				calendarView: calendarGranularity,
				onCalendarViewChange: setCalendarGranularity,
				anchorDate: schedule.date.toDate(),
				onAnchorDateChange: handleCalendarAnchorChange,
				slotStepMinutes: 30,
				renderBooking: renderReservationCalendarBooking,
				blockedTimeSalesChannels: ["online_store"],
				onBlockedTimePanelRequest: handleBlockedTimePanelRequest,
				onBookingMoveRequest: handleCalendarBookingMoveRequest,
				onCreateBookingFromSelection
			};
		}, [
			reservationCalendarPersist,
			calendarResources,
			calendarBookings,
			handleCalendarViewportChange,
			handleCalendarBookingClick,
			calendarGranularity,
			schedule.date,
			handleCalendarAnchorChange,
			effectiveTimelineRange,
			renderReservationCalendarBooking,
			handleBlockedTimePanelRequest,
			handleCalendarBookingMoveRequest,
			onCreateBookingFromSelection
		]),
		calendarGranularity,
		setCalendarGranularity
	};
}
//#endregion
exports.useReservationCalendarSlot = useReservationCalendarSlot;
