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_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_bookingTicket = require("./bookingTicket.js");
const require_useLogger = require("../../../../hooks/useLogger.js");
const require_usePromotion = require("../../../booking/hooks/usePromotion.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
let _pisell_utils = require("@pisell/utils");
let ahooks = require("ahooks");
//#region src/components/ticketBooking/hooks/pisellos/useProducts.ts
/**
* 通过 localStorage（storage API）控制 WebSocket 延迟更新行为：
*
* __PISELL_DEFER_WS_UPDATE__: 'true' | 其他
*   'true' -> WebSocket 推送数据时延迟更新，等待用户空闲后再刷新
*   其他值 / 不存在 -> 保持原有行为，收到数据立即更新
*
* __PISELL_DEFER_WS_UPDATE_TIMEOUT__: string (毫秒数)
*   自定义空闲超时时间，默认 10000ms（10 秒）
*/
const DEFAULT_IDLE_TIMEOUT = 1e4;
const USER_INTERACTION_EVENTS = [
	"click",
	"touchstart",
	"keydown"
];
const useProducts = (notAvailableRef) => {
	var _context$appHelper;
	const bookingTicket = require_bookingTicket.useBookingTicket();
	const context = require_useEngineContext.default();
	const platform = require_useEngineContext.usePlatform();
	const [products, setProducts] = (0, react.useState)([]);
	const [loading, setLoading] = (0, react.useState)(true);
	const isFirstLoadRef = (0, react.useRef)(true);
	(0, react.useRef)(true);
	const { getApp } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const logger = require_useLogger.default();
	const { formatProductList } = require_usePromotion.default();
	const useCurrentId = (0, react.useRef)((0, _pisell_utils.getUniqueId)());
	/** 暂存 WebSocket 推送的最新数据，等待空闲后再消费 */
	const pendingWsDataRef = (0, react.useRef)(null);
	/** 空闲定时器 ID */
	const idleTimerRef = (0, react.useRef)(null);
	getApp();
	const [scheduleTimePoints, setScheduleTimePoints] = (0, react.useState)([]);
	const scheduledTaskQueueIdRef = (0, react.useRef)("booking-schedule-products");
	const paramsRef = (0, react.useRef)(void 0);
	/** 从 localStorage 读取是否启用延迟更新 */
	const isDeferEnabled = (0, ahooks.useMemoizedFn)(() => {
		var _localStorage;
		return ((_localStorage = localStorage) === null || _localStorage === void 0 ? void 0 : _localStorage.getItem("__PISELL_DEFER_WS_UPDATE__")) === "true";
	});
	/** 从 localStorage 读取超时时间，取不到则使用默认值 */
	const getDeferTimeout = (0, ahooks.useMemoizedFn)(() => {
		var _localStorage2;
		const val = Number((_localStorage2 = localStorage) === null || _localStorage2 === void 0 ? void 0 : _localStorage2.getItem("__PISELL_DEFER_WS_UPDATE_TIMEOUT__"));
		return val > 0 ? val : DEFAULT_IDLE_TIMEOUT;
	});
	/** 将暂存的 WebSocket 数据刷入 state */
	const flushPendingData = (0, ahooks.useMemoizedFn)(() => {
		if (pendingWsDataRef.current) {
			setProducts(formatProductList(pendingWsDataRef.current));
			pendingWsDataRef.current = null;
		}
	});
	/** 重置空闲计时器：每次用户交互时调用，到期后执行 flushPendingData */
	const resetIdleTimer = (0, ahooks.useMemoizedFn)(() => {
		if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
		idleTimerRef.current = setTimeout(() => {
			flushPendingData();
		}, getDeferTimeout());
	});
	/**
	* 确保有一个空闲定时器在运行（仅在还没有定时器时启动）。
	* WebSocket 推送时调用，避免反复重置定时器导致数据永远刷不进去。
	*/
	const ensureIdleTimer = (0, ahooks.useMemoizedFn)(() => {
		if (!idleTimerRef.current) idleTimerRef.current = setTimeout(() => {
			flushPendingData();
		}, getDeferTimeout());
	});
	/**
	* 监听用户交互事件（click / touchstart / keydown）
	* 仅在 __PISELL_DEFER_WS_UPDATE__ 为 'true' 时生效
	*/
	(0, react.useEffect)(() => {
		const handler = () => {
			if (!isDeferEnabled()) return;
			resetIdleTimer();
		};
		USER_INTERACTION_EVENTS.forEach((evt) => {
			document.addEventListener(evt, handler, {
				capture: true,
				passive: true
			});
		});
		return () => {
			USER_INTERACTION_EVENTS.forEach((evt) => {
				document.removeEventListener(evt, handler, { capture: true });
			});
			if (idleTimerRef.current) {
				clearTimeout(idleTimerRef.current);
				idleTimerRef.current = null;
			}
		};
	}, []);
	const getProducts = (0, ahooks.useMemoizedFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (params) {
			setLoading(true);
			try {
				paramsRef.current = params;
				logger.addLog({
					title: "useProducts: getProducts 调用",
					metadata: { params }
				});
				const products = yield bookingTicket.loadProducts(params, {
					callback: (res) => {
						var _res$data;
						if (!(res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.list)) return;
						if (isDeferEnabled()) {
							pendingWsDataRef.current = res.data.list;
							ensureIdleTimer();
							return;
						}
						setProducts(formatProductList(res.data.list));
					},
					subscriberId: useCurrentId
				});
				logger.addLog({
					title: "useProducts: getProducts 返回",
					metadata: { products: (products === null || products === void 0 ? void 0 : products.length) || 0 }
				});
				setProducts(formatProductList(products));
				setLoading(false);
				isFirstLoadRef.current = false;
			} catch (error) {
				logger.addLog({
					title: "useProducts: getProducts 错误",
					metadata: { error: error === null || error === void 0 ? void 0 : error.message }
				});
				if ((error === null || error === void 0 ? void 0 : error.code) === 607100 && (isFirstLoadRef.current || products.length > 0)) {
					var _notAvailableRef$curr;
					(_notAvailableRef$curr = notAvailableRef.current) === null || _notAvailableRef$curr === void 0 || _notAvailableRef$curr.open();
				}
				setLoading(false);
				isFirstLoadRef.current = false;
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	(0, react.useEffect)(() => {
		return () => {
			bookingTicket.unsubscribeProductQuery(useCurrentId);
		};
	}, []);
	(0, react.useEffect)(() => {
		if (platform === "shop") return;
		try {
			var _context$appHelper2, _context$appHelper2$g;
			const app = context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getApp) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2);
			if (!app || !app.tasksManager) {
				console.warn("App 或 tasksManager 不可用");
				return;
			}
			app.tasksManager.addTaskFunction("getProducts", function() {
				var _ref2 = require_asyncToGenerator._asyncToGenerator(function* ({ task }) {
					console.log("定时执行 getProducts，参数：", task.payload);
					logger.addLog({
						title: "useProducts: 定时执行 getProducts",
						metadata: {
							payload: task.payload,
							task
						}
					});
					yield getProducts(task.payload);
					logger.addLog({
						title: "useProducts: 定时执行 getProducts 完成",
						metadata: {
							payload: task.payload,
							task
						}
					});
					return { status: "success" };
				});
				return function(_x2) {
					return _ref2.apply(this, arguments);
				};
			}());
			if (scheduleTimePoints && scheduleTimePoints.length > 0) {
				app.tasksManager.clearTasks({
					module: "scheduledTasks",
					queueId: scheduledTaskQueueIdRef.current
				});
				const tasks = scheduleTimePoints.map((timePoint) => {
					const [hours, minutes] = timePoint.split(":");
					const executeDayjs = (0, dayjs.default)().hour(parseInt(hours, 10)).minute(parseInt(minutes, 10)).second(4);
					const executeAt = executeDayjs.format("YYYY-MM-DD HH:mm:ss");
					const schedule_date = executeDayjs.format("YYYY-MM-DD");
					return {
						action: "getProducts",
						payload: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, paramsRef.current), {}, {
							schedule_date,
							schedule_datetime: executeAt
						}),
						scheduled: { executeAt }
					};
				});
				app.tasksManager.addTask({
					module: "scheduledTasks",
					queueId: scheduledTaskQueueIdRef.current,
					tasks
				});
				app.tasksManager.run({
					module: "scheduledTasks",
					queueId: scheduledTaskQueueIdRef.current
				});
				logger.addLog({
					title: "useProducts: 创建定时任务",
					metadata: {
						tasks: tasks.length,
						log: `已为 ${tasks.length} 个时间点创建定时任务`
					}
				});
				console.log(`已为 ${tasks.length} 个时间点创建定时任务`);
			}
		} catch (error) {
			console.error("创建定时任务失败：", error);
			logger.addLog({
				title: "useProducts: 创建定时任务失败",
				metadata: { error: error === null || error === void 0 ? void 0 : error.message }
			});
		}
		return () => {
			try {
				var _context$appHelper3, _context$appHelper3$g;
				const app = context === null || context === void 0 || (_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 || (_context$appHelper3 = _context$appHelper3.utils) === null || _context$appHelper3 === void 0 || (_context$appHelper3$g = _context$appHelper3.getApp) === null || _context$appHelper3$g === void 0 ? void 0 : _context$appHelper3$g.call(_context$appHelper3);
				if (app && app.tasksManager) {
					logger.addLog({
						title: "useProducts: 清理定时任务",
						metadata: { queueId: scheduledTaskQueueIdRef.current }
					});
					app.tasksManager.clearTasks({
						module: "scheduledTasks",
						queueId: scheduledTaskQueueIdRef.current
					});
				}
			} catch (error) {
				logger.addLog({
					title: "useProducts: 清理定时任务失败",
					metadata: { error: error === null || error === void 0 ? void 0 : error.message }
				});
				console.error("清理定时任务失败：", error);
			}
		};
	}, [scheduleTimePoints]);
	return {
		getScheduleTimePoints: (0, ahooks.useMemoizedFn)(function() {
			var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (params) {
				if (platform === "shop") return;
				setScheduleTimePoints(yield bookingTicket.getScheduleTimePoints(params));
			});
			return function(_x3) {
				return _ref3.apply(this, arguments);
			};
		}()),
		getProducts,
		products,
		loading
	};
};
//#endregion
exports.useProducts = useProducts;
