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 useEngineContext, { usePlatform } from "../../../../hooks/useEngineContext.js";
import { useBookingTicket } from "./bookingTicket.js";
import useLogger from "../../../../hooks/useLogger.js";
import usePromotion from "../../../booking/hooks/usePromotion.js";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { getUniqueId } from "@pisell/utils";
import { useMemoizedFn } from "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 = useBookingTicket();
	const context = useEngineContext();
	const platform = usePlatform();
	const [products, setProducts] = useState([]);
	const [loading, setLoading] = useState(true);
	const isFirstLoadRef = useRef(true);
	useRef(true);
	const { getApp } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const logger = useLogger();
	const { formatProductList } = usePromotion();
	const useCurrentId = useRef(getUniqueId());
	/** 暂存 WebSocket 推送的最新数据，等待空闲后再消费 */
	const pendingWsDataRef = useRef(null);
	/** 空闲定时器 ID */
	const idleTimerRef = useRef(null);
	getApp();
	const [scheduleTimePoints, setScheduleTimePoints] = useState([]);
	const scheduledTaskQueueIdRef = useRef("booking-schedule-products");
	const paramsRef = useRef(void 0);
	/** 从 localStorage 读取是否启用延迟更新 */
	const isDeferEnabled = useMemoizedFn(() => {
		var _localStorage;
		return ((_localStorage = localStorage) === null || _localStorage === void 0 ? void 0 : _localStorage.getItem("__PISELL_DEFER_WS_UPDATE__")) === "true";
	});
	/** 从 localStorage 读取超时时间，取不到则使用默认值 */
	const getDeferTimeout = 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 = useMemoizedFn(() => {
		if (pendingWsDataRef.current) {
			setProducts(formatProductList(pendingWsDataRef.current));
			pendingWsDataRef.current = null;
		}
	});
	/** 重置空闲计时器：每次用户交互时调用，到期后执行 flushPendingData */
	const resetIdleTimer = useMemoizedFn(() => {
		if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
		idleTimerRef.current = setTimeout(() => {
			flushPendingData();
		}, getDeferTimeout());
	});
	/**
	* 确保有一个空闲定时器在运行（仅在还没有定时器时启动）。
	* WebSocket 推送时调用，避免反复重置定时器导致数据永远刷不进去。
	*/
	const ensureIdleTimer = useMemoizedFn(() => {
		if (!idleTimerRef.current) idleTimerRef.current = setTimeout(() => {
			flushPendingData();
		}, getDeferTimeout());
	});
	/**
	* 监听用户交互事件（click / touchstart / keydown）
	* 仅在 __PISELL_DEFER_WS_UPDATE__ 为 'true' 时生效
	*/
	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 = useMemoizedFn(function() {
		var _ref = _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);
		};
	}());
	useEffect(() => {
		return () => {
			bookingTicket.unsubscribeProductQuery(useCurrentId);
		};
	}, []);
	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 = _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 = dayjs().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: _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: useMemoizedFn(function() {
			var _ref3 = _asyncToGenerator(function* (params) {
				if (platform === "shop") return;
				setScheduleTimePoints(yield bookingTicket.getScheduleTimePoints(params));
			});
			return function(_x3) {
				return _ref3.apply(this, arguments);
			};
		}()),
		getProducts,
		products,
		loading
	};
};
//#endregion
export { useProducts };
