const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_reservationConstants = require("../reservationConstants.js");
const require_reservationDensity = require("../data/reservationDensity.js");
const require_reservationTablesMerge = require("../data/reservationTablesMerge.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
//#region src/plus/pisellReservation/hooks/useReservationSalesHostData.ts
/**
* 内置列表且资源台 + floorDayBooking 均就绪后，向宿主 sales 拉两套数据：
* - `getResourceBookingList`：游标时刻下的预约子集，参与合并进平面图 dataSources；
* - `getTimelineHighlights`：时间轴密度折线（无则退回 PisellReservation 内本地计算）。
*/
function useReservationSalesHostData(options) {
	var _timeNavigatorPropsPr2, _timeNavigatorPropsPr3;
	const { isInternalListData, pisellosRef, hasPisellosGetModule, debouncedSchedule, resourceBoardLoading, floorDayBookingLoading, floorDayBookingData, scheduleDate, timeNavigatorPropsProp } = options;
	const [salesResourceBookings, setSalesResourceBookings] = (0, react.useState)(null);
	const salesBookingRequestRef = (0, react.useRef)(0);
	/** 非宿主 / sales 子模块拒绝时避免同一「日程 + 列表快照」下反复打接口与刷 console */
	const resourceListHostSkipRef = (0, react.useRef)(false);
	const resourceListRetryGateRef = (0, react.useRef)("");
	const debouncedAtMs = (debouncedSchedule === null || debouncedSchedule === void 0 ? void 0 : debouncedSchedule.at) != null && (0, dayjs.default)(debouncedSchedule.at).isValid() ? (0, dayjs.default)(debouncedSchedule.at).valueOf() : null;
	/**
	* 勿把 `floorDayBookingData` 数组引用放进 effect：useRequest 常给新的 `[]`，会触发死循环。
	*/
	const floorDayBookingDepKey = (0, react.useMemo)(() => {
		const d = floorDayBookingData;
		if (!Array.isArray(d) || d.length === 0) return "__empty__";
		const parts = d.slice(0, 24).map((row) => {
			var _ref, _ref2, _r$booking_id;
			const r = row;
			return String((_ref = (_ref2 = (_r$booking_id = r === null || r === void 0 ? void 0 : r.booking_id) !== null && _r$booking_id !== void 0 ? _r$booking_id : r === null || r === void 0 ? void 0 : r.id) !== null && _ref2 !== void 0 ? _ref2 : r === null || r === void 0 ? void 0 : r.bookingId) !== null && _ref !== void 0 ? _ref : "");
		});
		return `${d.length}:${parts.join("|")}`;
	}, [floorDayBookingData]);
	const floorDayBookingDataRef = (0, react.useRef)(floorDayBookingData);
	floorDayBookingDataRef.current = floorDayBookingData;
	(0, react.useEffect)(() => {
		const pisellosNow = pisellosRef.current;
		if (!isInternalListData) {
			setSalesResourceBookings((p) => p == null ? p : null);
			return;
		}
		if (!(pisellosNow === null || pisellosNow === void 0 ? void 0 : pisellosNow.getModule)) {
			setSalesResourceBookings((p) => p == null ? p : null);
			return;
		}
		if (!(debouncedSchedule === null || debouncedSchedule === void 0 ? void 0 : debouncedSchedule.at) || !(0, dayjs.default)(debouncedSchedule.at).isValid()) return;
		if (resourceBoardLoading || floorDayBookingLoading) return;
		const list = floorDayBookingDataRef.current;
		if (!Array.isArray(list)) return;
		const retryGateKey = `${debouncedAtMs !== null && debouncedAtMs !== void 0 ? debouncedAtMs : "na"}|${floorDayBookingDepKey}|${hasPisellosGetModule ? 1 : 0}`;
		if (retryGateKey !== resourceListRetryGateRef.current) {
			resourceListRetryGateRef.current = retryGateKey;
			resourceListHostSkipRef.current = false;
		}
		if (resourceListHostSkipRef.current) return;
		let salesModule;
		try {
			salesModule = pisellosNow.getModule("sales");
		} catch (_unused) {
			setSalesResourceBookings((p) => p == null ? p : null);
			return;
		}
		const fn = salesModule === null || salesModule === void 0 ? void 0 : salesModule.getResourceBookingList;
		if (typeof fn !== "function") {
			setSalesResourceBookings((p) => p == null ? p : null);
			return;
		}
		const reqId = ++salesBookingRequestRef.current;
		setSalesResourceBookings(null);
		const resourceBookingListTimeFormat = "YYYY-MM-DD HH:mm";
		const timeStr = (0, dayjs.default)(debouncedSchedule.at).format(resourceBookingListTimeFormat);
		const currentTimeStr = (0, dayjs.default)().format(resourceBookingListTimeFormat);
		const applyHostList = (raw) => {
			if (salesBookingRequestRef.current !== reqId) return;
			setSalesResourceBookings(require_reservationTablesMerge.normalizeSalesResourceBookingListResult(raw));
			resourceListHostSkipRef.current = false;
		};
		const revertToLocalFilter = () => {
			if (salesBookingRequestRef.current !== reqId) return;
			setSalesResourceBookings(null);
		};
		try {
			const result = fn.call(salesModule, timeStr, list, currentTimeStr);
			if (result != null && typeof result.then === "function") result.then(applyHostList).catch((e) => {
				resourceListHostSkipRef.current = true;
				if (process.env.NODE_ENV !== "production") console.warn("[PisellReservation] sales.getResourceBookingList rejected（非宿主或 sales 未就绪时将不再重试，直至日程或列表数据变化）", e);
				revertToLocalFilter();
			});
			else applyHostList(result);
		} catch (e) {
			resourceListHostSkipRef.current = true;
			if (process.env.NODE_ENV !== "production") console.warn("[PisellReservation] sales.getResourceBookingList error", e);
			revertToLocalFilter();
		}
	}, [
		isInternalListData,
		hasPisellosGetModule,
		resourceBoardLoading,
		floorDayBookingLoading,
		floorDayBookingDepKey,
		debouncedAtMs,
		pisellosRef
	]);
	const [salesTimelineHighlights, setSalesTimelineHighlights] = (0, react.useState)(null);
	const timelineHighlightsReqRef = (0, react.useRef)(0);
	const timelineHighlightsMissingLoggedRef = (0, react.useRef)(false);
	const scheduleDayMs = (0, dayjs.default)(scheduleDate).startOf("day").valueOf();
	(0, react.useEffect)(() => {
		if (!isInternalListData) setSalesTimelineHighlights(null);
	}, [isInternalListData]);
	(0, react.useEffect)(() => {
		var _timeNavigatorPropsPr;
		if (!isInternalListData) return;
		const pisellosNow = pisellosRef.current;
		if (!(pisellosNow === null || pisellosNow === void 0 ? void 0 : pisellosNow.getModule)) return;
		if (resourceBoardLoading || floorDayBookingLoading) return;
		const bookingList = floorDayBookingDataRef.current;
		if (!Array.isArray(bookingList)) return;
		let salesModule;
		try {
			salesModule = pisellosNow.getModule("sales");
		} catch (_unused2) {
			return;
		}
		const highlightsFn = salesModule === null || salesModule === void 0 ? void 0 : salesModule.getTimelineHighlights;
		if (typeof highlightsFn !== "function") {
			setSalesTimelineHighlights(null);
			if (!timelineHighlightsMissingLoggedRef.current) {
				timelineHighlightsMissingLoggedRef.current = true;
				console.warn("[PisellReservation] sales.getTimelineHighlights 未注册或非函数；时间轴密度退回本地计算");
			}
			return;
		}
		const reqId = ++timelineHighlightsReqRef.current;
		const { startStr, endStr } = require_reservationDensity.reservationTimelineRangeStrings(scheduleDate, (_timeNavigatorPropsPr = timeNavigatorPropsProp === null || timeNavigatorPropsProp === void 0 ? void 0 : timeNavigatorPropsProp.range) !== null && _timeNavigatorPropsPr !== void 0 ? _timeNavigatorPropsPr : require_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE);
		const applyHighlights = (raw) => {
			if (timelineHighlightsReqRef.current !== reqId) return;
			setSalesTimelineHighlights(require_reservationDensity.normalizeSalesTimelineHighlightsRaw(raw));
		};
		try {
			const out = highlightsFn.call(salesModule, bookingList, startStr, endStr);
			if (out != null && typeof out.then === "function") out.then(applyHighlights).catch((e) => {
				if (process.env.NODE_ENV !== "production") console.warn("[PisellReservation] sales.getTimelineHighlights Promise 失败", e);
			});
			else applyHighlights(out);
		} catch (e) {
			if (process.env.NODE_ENV !== "production") console.warn("[PisellReservation] sales.getTimelineHighlights 同步调用异常", e);
		}
	}, [
		isInternalListData,
		hasPisellosGetModule,
		resourceBoardLoading,
		floorDayBookingLoading,
		floorDayBookingDepKey,
		scheduleDayMs,
		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,
		pisellosRef
	]);
	return {
		salesResourceBookings,
		salesTimelineHighlights
	};
}
//#endregion
exports.useReservationSalesHostData = useReservationSalesHostData;
