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 { request } from "../../../utils/index.js";
import { I18N_CALENDAR_WRITE_NOT_AVAILABLE } from "../reservationConstants.js";
import { dayjsFromCalendarHour, findMergedTableRowForBookingRaw } from "../data/calendarAdapter.js";
import { mergeSearchParamsBookingRange } from "../data/reservationDataUtils.js";
import { openBookingChangeModalAfterCalendarDrag } from "../data/bookingCalendarMoveIntegration.js";
import blockTimeModal from "../components/blockTimeModal/index.js";
import { ReservationCalendarBookingNode } from "../components/ReservationCalendarBookingNode.js";
import dayjs from "dayjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { message } from "antd";
import { locales } from "@pisell/utils";
import { useMemoizedFn } from "ahooks";
//#region src/plus/pisellReservation/hooks/useReservationCalendarSlot.tsx
/**
* 预约看板日历槽：视口合并、预约条渲染、锁台/改期、加载态与 RecordBoard 日历 props。
*/
/**
* 日历拖拽后挡一次误触详情的 ref（仅日历槽内部使用）。
*/
function useCalendarDragSuppressRef() {
	return 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] = useState("week");
	const calendarLoadedKeySetRef = useRef(/* @__PURE__ */ new Set());
	const calendarInflightKeyRef = useRef(null);
	const prevFloorDayLoadingRef = useRef(false);
	const handleCalendarAnchorChange = useCallback((d) => {
		const dj = dayjs(d).startOf("day");
		const atSrc = dayjs(schedule.at);
		handleScheduleChange({
			date: dj,
			at: dj.hour(atSrc.hour()).minute(atSrc.minute()).second(0).millisecond(0)
		});
	}, [handleScheduleChange, schedule.at]);
	const handleCalendarViewportChange = useCallback((payload) => {
		if (!isInternalListData) return;
		floorDayBookingData.patchSearchParams((prev) => {
			const merged = 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" ? _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 _objectSpread2(_objectSpread2({}, merged), {}, { filter: _objectSpread2(_objectSpread2({}, filterObj), {}, { values: valuesObj }) });
		});
	}, [
		isInternalListData,
		floorDayBookingData.patchSearchParams,
		operatingDayBoundary
	]);
	const handleCalendarBookingClick = useCallback((item) => {
		const raw = item.raw;
		if (!raw || typeof raw !== "object") return false;
		openBookingDetailFromRaw({
			raw,
			row: findMergedTableRowForBookingRaw(raw, tables)
		});
		return true;
	}, [openBookingDetailFromRaw, tables]);
	const reservationCalendarPersist = useMemo(() => {
		return { beforePersist: () => {
			message.warning(locales.getText(I18N_CALENDAR_WRITE_NOT_AVAILABLE));
			return false;
		} };
	}, []);
	const renderReservationCalendarBooking = useCallback((args) => /* @__PURE__ */ React.createElement(ReservationCalendarBookingNode, {
		args,
		tables,
		calendarDragSuppressDetailRef
	}), [tables]);
	const handleBlockedTimePanelRequest = useMemoizedFn(function() {
		var _ref2 = _asyncToGenerator(function* (payload) {
			const { mergedRange, slotStepMinutes } = payload;
			try {
				yield blockTimeModal.open({
					resources: calendarResources,
					initialResourceId: mergedRange.courtId,
					initialTimeRange: [dayjsFromCalendarHour(mergedRange.date, mergedRange.startHour), dayjsFromCalendarHour(mergedRange.date, mergedRange.endHour)],
					minuteStep: slotStepMinutes,
					blockedSalesChannels: ["online_store"],
					onSubmit: function() {
						var _ref = _asyncToGenerator(function* ({ submitPayload }) {
							yield request.getRequest().post("/shop/schedule/blocked-time", submitPayload);
							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 = useMemoizedFn(function() {
		var _ref4 = _asyncToGenerator(function* (payload) {
			return openBookingChangeModalAfterCalendarDrag({
				calendarItem: payload.item,
				draft: payload.draft,
				calendarResources,
				calendarBookings,
				effectiveTimelineRange,
				anchorDate: schedule.date.toDate(),
				slotStepMinutes: 30,
				onSuccessRefresh: function() {
					var _ref3 = _asyncToGenerator(function* () {
						yield runtimeContext.refreshAsync();
					});
					return function onSuccessRefresh() {
						return _ref3.apply(this, arguments);
					};
				}()
			});
		});
		return function(_x3) {
			return _ref4.apply(this, arguments);
		};
	}());
	const calendarLoadKey = useMemo(() => `${calendarGranularity}_${dayjs(schedule.date).startOf("day").valueOf()}_${dayjs(schedule.at).valueOf()}`, [
		calendarGranularity,
		schedule.date,
		schedule.at
	]);
	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]);
	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 = 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: 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
export { useReservationCalendarSlot };
