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 { getProductCache, setProductCache } from "../../utils/productCache.js";
import useEngineContext, { usePlatform } from "../../../../hooks/useEngineContext.js";
import { useOsKey } from "../../context/OsKeyContext.js";
import { useBookingTicket } from "./bookingTicket.js";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/components/ticketBooking/hooks/pisellos/useProducts.ts
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const useProducts = (notAvailableRef) => {
	var _context$appHelper;
	const bookingTicket = useBookingTicket();
	const osKey = useOsKey();
	const context = useEngineContext();
	const platform = usePlatform();
	const [products, setProducts] = useState([]);
	const [loading, setLoading] = useState(true);
	const isFirstLoadRef = useRef(true);
	const isFirstLoadDataRef = useRef(true);
	const { getApp } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const [scheduleTimePoints, setScheduleTimePoints] = useState([]);
	const scheduledTaskQueueIdRef = useRef("booking-schedule-products");
	const paramsRef = useRef(void 0);
	const app = getApp();
	const getProducts = useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (params) {
			if (isFirstLoadRef.current && osKey) {
				const cachedProducts = getProductCache(osKey);
				if (cachedProducts && cachedProducts.length > 0) {
					setProducts(cachedProducts);
					setLoading(false);
				}
				isFirstLoadRef.current = false;
			} else setLoading(true);
			const maxRetries = 3;
			let lastError = null;
			let freshProducts = [];
			for (let attempt = 1; attempt <= maxRetries; attempt++) try {
				console.log(`[ProductCache] 尝试加载数据，第 ${attempt}/${maxRetries} 次`);
				freshProducts = yield bookingTicket.loadProducts(params);
				if (freshProducts && freshProducts.length > 0) {
					console.log(`[ProductCache] 第 ${attempt} 次尝试成功，获取到 ${freshProducts.length} 条数据`);
					break;
				}
				console.log(`[ProductCache] 第 ${attempt} 次尝试返回空数据`);
				if (attempt < maxRetries) {
					console.log(`[ProductCache] 等待 1 秒后重试...`);
					yield sleep(1e3);
				}
			} catch (error) {
				var _app$logger, _app$logger$addLog;
				lastError = error;
				console.log(`[ProductCache] 第 ${attempt} 次尝试失败:`, error);
				app === null || app === void 0 || (_app$logger = app.logger) === null || _app$logger === void 0 || (_app$logger$addLog = _app$logger.addLog) === null || _app$logger$addLog === void 0 || _app$logger$addLog.call(_app$logger, {
					type: "info",
					title: `[getProduct] bookingTicket.loadProducts error (attempt ${attempt}/${maxRetries})`,
					metadata: {
						error,
						attempt
					}
				});
				if (attempt < maxRetries) {
					console.log(`[ProductCache] 等待 1 秒后重试...`);
					yield sleep(1e3);
				}
			}
			if (freshProducts && freshProducts.length > 0) {
				isFirstLoadDataRef.current = false;
				setProducts(freshProducts);
				if (osKey) {
					setProductCache(osKey, freshProducts);
					console.log("[ProductCache] 已更新缓存");
				}
				setLoading(false);
			} else {
				var _app$logger2, _app$logger2$addLog;
				console.log("[ProductCache] 3次尝试后仍未获取到数据");
				app === null || app === void 0 || (_app$logger2 = app.logger) === null || _app$logger2 === void 0 || (_app$logger2$addLog = _app$logger2.addLog) === null || _app$logger2$addLog === void 0 || _app$logger2$addLog.call(_app$logger2, {
					type: "error",
					title: "[getProduct] 3次尝试后仍未获取到数据",
					metadata: { error: lastError }
				});
				if ((lastError === null || lastError === void 0 ? void 0 : lastError.code) === 607100 && (isFirstLoadDataRef.current || products.length > 0)) {
					var _notAvailableRef$curr;
					(_notAvailableRef$curr = notAvailableRef.current) === null || _notAvailableRef$curr === void 0 || _notAvailableRef$curr.open();
				}
				setLoading(false);
				setProducts([]);
				isFirstLoadDataRef.current = false;
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	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);
					yield getProducts(task.payload);
					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
				});
				console.log(`已为 ${tasks.length} 个时间点创建定时任务`);
			}
		} catch (error) {
			console.error("创建定时任务失败：", error);
		}
		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) app.tasksManager.clearTasks({
					module: "scheduledTasks",
					queueId: scheduledTaskQueueIdRef.current
				});
			} catch (error) {
				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 };
