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_index = require("../../../components/ticketBooking/utils/index.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_SalesSdkContext = require("./SalesSdkContext.js");
const require_SalesSdkProductContext = require("./SalesSdkProductContext.js");
const require_SalesSdkSummaryContext = require("./SalesSdkSummaryContext.js");
const require_SalesSdkCartContext = require("./SalesSdkCartContext.js");
const require_SalesSdkCustomerContext = require("./SalesSdkCustomerContext.js");
let react = require("react");
react = require_runtime.__toESM(react);
let ahooks = require("ahooks");
//#region src/plus/salesSdk/context/SalesSdkProvider.tsx
const EMPTY_ROOT_SNAPSHOT = {
	tempOrder: null,
	salesDetail: null
};
function cloneArray(value, fallback) {
	return Array.isArray(value) ? [...value] : fallback;
}
/**
* 浅克隆 tempOrder，并把 React 频繁读写的数组字段重新装一份，避免 OS 内部就地 mutate
* 后 React 在引用比较里漏掉变更。
*/
function cloneTempOrder(tempOrder) {
	if (!tempOrder) return null;
	return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, tempOrder), {}, {
		products: cloneArray(tempOrder.products, []),
		bookings: cloneArray(tempOrder.bookings, []),
		payments: cloneArray(tempOrder.payments, []),
		surcharges: cloneArray(tempOrder.surcharges, []),
		discount_list: cloneArray(tempOrder.discount_list, []),
		relation_forms: cloneArray(tempOrder.relation_forms, []),
		contacts: cloneArray(tempOrder.contacts, []),
		contacts_info: tempOrder.contacts_info,
		summary: tempOrder.summary ? require_objectSpread2._objectSpread2({}, tempOrder.summary) : tempOrder.summary
	});
}
function readRootSnapshot(bookingTicket) {
	if (!bookingTicket) return EMPTY_ROOT_SNAPSHOT;
	try {
		var _bookingTicket$getTem, _bookingTicket$getTem2, _bookingTicket$getSal, _bookingTicket$getSal2;
		return {
			tempOrder: cloneTempOrder((_bookingTicket$getTem = (_bookingTicket$getTem2 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem2 === void 0 ? void 0 : _bookingTicket$getTem2.call(bookingTicket)) !== null && _bookingTicket$getTem !== void 0 ? _bookingTicket$getTem : null),
			salesDetail: (_bookingTicket$getSal = (_bookingTicket$getSal2 = bookingTicket.getSalesOrder) === null || _bookingTicket$getSal2 === void 0 ? void 0 : _bookingTicket$getSal2.call(bookingTicket)) !== null && _bookingTicket$getSal !== void 0 ? _bookingTicket$getSal : null
		};
	} catch (e) {
		console.warn("[SalesSdk] readRootSnapshot 失败", e);
		return EMPTY_ROOT_SNAPSHOT;
	}
}
/**
* 仅供 SDK 内部 Provider/action 调用：在 OS tempOrder/salesDetail 发生变化但未通过
* 事件 emit 时（如 cart action 写完 OS），由子 Provider 显式触发顶层重新读快照。
* 不对外暴露。
*/
const SalesSdkRootRefreshContext = (0, react.createContext)(null);
SalesSdkRootRefreshContext.displayName = "SalesSdkRootRefreshContext";
/**
* Sales SDK 顶层 Provider。
*
* 关键点：
*  - 与 ticketBooking 共享同 osKey 时，`pisellos.getModule(getBookingTicketKey(osKey))` 直接命中
*    ticketBooking 已注册的 BookingTicket 实例（详见 ticketBooking/index.tsx 的 has-check 注册），
*    Sales SDK 与 ticketBooking 双方共享 `tempOrder` / `currentSalesDetail` 等核心状态。
*  - 仅当 `pisellos.getModule(...)` 未命中时才注册新模块，避免重复实例化。
*  - 不引入 miniRedux；不直接持有 React state 镜像 OS 数据，订阅工作交给子 Provider 内部完成。
*  - bootstrap actions（loadDetail / createNew / restore / destroy）通过 `useMemoizedFn` 单独包装，
*    保证单 action 引用稳定（详见 docs.md "Action 引用稳定性纪律"）。
*  - autoBootstrap：仅当 `orderId` 存在时挂载后自动 loadSalesDetail；不传 orderId 则不会自动
*    createNew，避免空 osKey 误建 tempOrder（消费方需要时显式调 useSalesSdk().createNew()）。
*/
const SalesSdkProvider = ({ osKey, businessCode, otherParams, rulesHooks, orderId, autoBootstrap = true, children }) => {
	var _context$appHelper;
	const context = require_useEngineContext.default();
	const { pisellos, pisellosAllModule, businessUtils, action } = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const { BookingTicket } = pisellosAllModule || {};
	const bookingTicket = (0, react.useMemo)(() => {
		if (!pisellos || !BookingTicket) return null;
		const moduleKey = require_index.getBookingTicketKey(osKey);
		let mod = pisellos.getModule(moduleKey);
		if (!mod) {
			var _businessUtils$getApp;
			mod = new BookingTicket(moduleKey);
			pisellos.registerModule(mod, { otherParams: require_objectSpread2._objectSpread2({
				cacheId: moduleKey,
				platform: (otherParams === null || otherParams === void 0 ? void 0 : otherParams.platform) || "shop",
				businessCode,
				isFranchisee: businessUtils === null || businessUtils === void 0 || (_businessUtils$getApp = businessUtils.getAppByModal) === null || _businessUtils$getApp === void 0 ? void 0 : _businessUtils$getApp.call(businessUtils, "franchisee"),
				rules: rulesHooks ? { hooks: rulesHooks } : void 0
			}, otherParams || {}) });
		}
		return mod;
	}, [
		pisellos,
		BookingTicket,
		osKey
	]);
	const [status, setStatus] = (0, react.useState)("idle");
	const [error, setError] = (0, react.useState)(null);
	const [rootSnapshot, setRootSnapshot] = (0, react.useState)(EMPTY_ROOT_SNAPSHOT);
	/**
	* 内部 refresh：所有改 OS 的入口在动作完成后调一次，把 tempOrder / salesDetail 同步到顶层 state。
	* 子 Provider 通过 `SalesSdkRootRefreshContext` 拿到此函数。
	*/
	const refreshRootSnapshot = (0, ahooks.useMemoizedFn)(() => {
		setRootSnapshot(readRootSnapshot(bookingTicket));
	});
	(0, react.useEffect)(() => {
		setRootSnapshot(readRootSnapshot(bookingTicket));
	}, [bookingTicket]);
	(0, react.useEffect)(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
			refreshRootSnapshot();
		});
		return () => {
			try {
				off();
			} catch (_unused) {}
		};
	}, [bookingTicket, refreshRootSnapshot]);
	const loadDetail = (0, ahooks.useMemoizedFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (id) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			setStatus("loading");
			setError(null);
			try {
				const sales = yield bookingTicket.loadSalesDetail(id);
				refreshRootSnapshot();
				setStatus("ready");
				return sales;
			} catch (e) {
				var _e$message;
				const err = e instanceof Error ? e : new Error(String((_e$message = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message !== void 0 ? _e$message : e));
				setError(err);
				setStatus("error");
				throw err;
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	/** 跳过本地缓存，以 `{ orderId, forceRemote: true }` 形态调用 OS loadSalesDetail */
	const loadDetailByRemote = (0, ahooks.useMemoizedFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (id) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			setStatus("loading");
			setError(null);
			try {
				const sales = yield bookingTicket.loadSalesDetail({
					orderId: id,
					forceRemote: true
				});
				refreshRootSnapshot();
				setStatus("ready");
				return sales;
			} catch (e) {
				var _e$message2;
				const err = e instanceof Error ? e : new Error(String((_e$message2 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message2 !== void 0 ? _e$message2 : e));
				setError(err);
				setStatus("error");
				throw err;
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	/**
	* 基于当前 tempOrder.order_id 强制从远端刷新销售详情（转发 OS refreshSalesDetail）。
	* 不写 loading 态，避免编辑中后台刷新导致 UI 闪烁；成功后同步顶层 tempOrder / salesDetail。
	*/
	const refreshSalesDetail = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		setError(null);
		try {
			const sales = yield bookingTicket.refreshSalesDetail();
			refreshRootSnapshot();
			return sales;
		} catch (e) {
			var _e$message3;
			const err = e instanceof Error ? e : new Error(String((_e$message3 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message3 !== void 0 ? _e$message3 : e));
			setError(err);
			throw err;
		}
	}));
	const createNew = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		try {
			const tempOrder = yield bookingTicket.addNewOrder();
			refreshRootSnapshot();
			setStatus("ready");
			setError(null);
			return tempOrder;
		} catch (e) {
			var _e$message4;
			const err = e instanceof Error ? e : new Error(String((_e$message4 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message4 !== void 0 ? _e$message4 : e));
			setError(err);
			setStatus("error");
			throw err;
		}
	}));
	const restore = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		try {
			const tempOrder = yield bookingTicket.restoreOrder();
			refreshRootSnapshot();
			setStatus("ready");
			setError(null);
			return tempOrder;
		} catch (e) {
			var _e$message5;
			const err = e instanceof Error ? e : new Error(String((_e$message5 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message5 !== void 0 ? _e$message5 : e));
			setError(err);
			setStatus("error");
			throw err;
		}
	}));
	const destroy = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!bookingTicket) return;
		yield bookingTicket.destroy();
		setRootSnapshot(EMPTY_ROOT_SNAPSHOT);
		setStatus("idle");
		setError(null);
	}));
	/**
	* 打开结账面板。
	*
	* 通过 `appHelper.utils.action` 派发 `pisell1.handleOpenPayment`，
	* 订单 id 自动取自当前 BookingTicket 的 `tempOrder.order_id`，
	* 消费方无需再传 orderId（与 SDK 其它写操作保持一致：以 tempOrder 为单一真源）。
	*
	* 行为：
	*  - 缺少 `appHelper.utils.action`、`bookingTicket`、`tempOrder.order_id` 时直接抛错
	*  - 底层 action 在「结账完成」与「toast 关闭」时各回调一次，这里过滤掉
	*    `isCallbackFromToast` 的二次回调，保证 Promise 只在真正完成时 resolve
	*/
	const openCheckout = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		var _bookingTicket$getTem3;
		if (typeof action !== "function") throw new Error("[SalesSdk] appHelper.utils.action is not available.");
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		const tempOrder = (_bookingTicket$getTem3 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem3 === void 0 ? void 0 : _bookingTicket$getTem3.call(bookingTicket);
		const orderIdFromTemp = tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id;
		if (orderIdFromTemp === void 0 || orderIdFromTemp === null) throw new Error("[SalesSdk] openCheckout: tempOrder.order_id 缺失（请先 loadDetail 或提交订单）");
		return new Promise((resolve) => {
			let settled = false;
			action({
				type: "pisell1.handleOpenPayment",
				data: { order: { id: orderIdFromTemp } },
				callback: (res = {}) => {
					var _res$data;
					if (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.isCallbackFromToast) return;
					if (typeof res.reset === "boolean" && res.reset) refreshSalesDetail().then(() => {
						action({
							type: "webpos.updateLocalOrderApi",
							data: { order_id: orderIdFromTemp }
						});
					});
					if (settled) return;
					settled = true;
					resolve(res);
				}
			});
		});
	}));
	/**
	* 变更预约状态：直接转发到 BookingTicket.setBookingStatus。
	* OS 内部已经做了乐观更新 + 失败回滚 + 强制刷新详情，这里仅同步 SDK 的 error 状态。
	*/
	const setBookingStatus = (0, ahooks.useMemoizedFn)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (status) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			try {
				var _bookingTicket$getTem4;
				const data = yield bookingTicket.setBookingStatus(status);
				const tempOrder = (_bookingTicket$getTem4 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem4 === void 0 ? void 0 : _bookingTicket$getTem4.call(bookingTicket);
				action({
					type: "webpos.updateLocalOrderApi",
					data: { order_id: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id }
				});
				setError(null);
				return data;
			} catch (e) {
				var _e$message6;
				const err = e instanceof Error ? e : new Error(String((_e$message6 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message6 !== void 0 ? _e$message6 : e));
				setError(err);
				throw err;
			}
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}());
	/**
	* 同步类 tempOrder 写入的公共骨架：检查 handle → 调 OS → refreshRootSnapshot → 错误归集到 error state。
	* 仅服务「同步 mutate + 立即刷新顶层」这一类 action（如 setOrderNote / setShopDiscount，
	* 以及后续可能新增的 setBuzzer / setContactsInfo 等）。
	*
	* 不覆盖 setBookingStatus —— 它是 async，且 OS 内部已强制刷新详情、外壳还要派发
	* `webpos.updateLocalOrderApi` 同步本地订单缓存，单独维护更直观。
	*
	* 该函数无需稳定引用：调用方（setOrderNote / setShopDiscount）已用 useMemoizedFn
	* 包装并通过 ref 拿最新闭包，因此每次渲染重建不会破坏对外引用稳定性。
	*/
	function runTempOrderMutation(exec) {
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		try {
			const result = exec(bookingTicket);
			refreshRootSnapshot();
			setError(null);
			return result;
		} catch (e) {
			var _e$message7;
			const err = e instanceof Error ? e : new Error(String((_e$message7 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message7 !== void 0 ? _e$message7 : e));
			setError(err);
			throw err;
		}
	}
	/** 写入订单备注（tempOrder.note，字符串）。 */
	const setOrderNote = (0, ahooks.useMemoizedFn)((note) => runTempOrderMutation((handle) => handle.updateTempOrderNote(note)));
	/**
	* 写入整单优惠金额（tempOrder.shop_discount）。
	* OS 内部 Decimal 标准化：负数归零、保留 2 位小数；返回标准化后的字符串。
	*/
	const setShopDiscount = (0, ahooks.useMemoizedFn)((amount) => runTempOrderMutation((handle) => handle.updateOrderShopDiscount(amount)));
	/**
	* 写入联系人信息（tempOrder.contacts_info）。
	* OS 内部防御：非对象/数组都归 null，只接对象或 null；返回最终写入的对象或 null。
	*/
	const setContactsInfo = (0, ahooks.useMemoizedFn)((contactsInfo) => runTempOrderMutation((handle) => handle.updateTempOrderContactsInfo(contactsInfo)));
	(0, react.useEffect)(() => {
		if (!autoBootstrap || !orderId || !bookingTicket) return;
		loadDetail(orderId).catch(() => {});
	}, [
		autoBootstrap,
		orderId,
		bookingTicket,
		loadDetail
	]);
	const value = (0, react.useMemo)(() => {
		var _rootSnapshot$tempOrd;
		return {
			bookingTicket,
			osKey,
			status,
			error,
			isReady: status === "ready",
			shop_full_order_number: ((_rootSnapshot$tempOrd = rootSnapshot.tempOrder) === null || _rootSnapshot$tempOrd === void 0 ? void 0 : _rootSnapshot$tempOrd.shop_full_order_number) || "",
			tempOrder: rootSnapshot.tempOrder,
			salesDetail: rootSnapshot.salesDetail,
			loadDetail,
			loadDetailByRemote,
			refreshSalesDetail,
			createNew,
			restore,
			destroy,
			setBookingStatus,
			setOrderNote,
			setShopDiscount,
			setContactsInfo,
			openCheckout
		};
	}, [
		bookingTicket,
		osKey,
		status,
		error,
		rootSnapshot,
		loadDetail,
		loadDetailByRemote,
		refreshSalesDetail,
		createNew,
		restore,
		destroy,
		setBookingStatus,
		setOrderNote,
		setShopDiscount,
		setContactsInfo,
		openCheckout
	]);
	return /* @__PURE__ */ react.default.createElement(require_SalesSdkContext.SalesSdkContext.Provider, { value }, /* @__PURE__ */ react.default.createElement(SalesSdkRootRefreshContext.Provider, { value: refreshRootSnapshot }, /* @__PURE__ */ react.default.createElement(require_SalesSdkProductContext.SalesSdkProductProvider, null, /* @__PURE__ */ react.default.createElement(require_SalesSdkSummaryContext.SalesSdkSummaryProvider, null, /* @__PURE__ */ react.default.createElement(require_SalesSdkCartContext.SalesSdkCartProvider, null, /* @__PURE__ */ react.default.createElement(require_SalesSdkCustomerContext.SalesSdkCustomerProvider, null, children))))));
};
//#endregion
exports.SalesSdkProvider = SalesSdkProvider;
exports.SalesSdkRootRefreshContext = SalesSdkRootRefreshContext;
