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 { getBookingTicketKey } from "../../../components/ticketBooking/utils/index.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { SalesSdkContext } from "./SalesSdkContext.js";
import { SalesSdkSummaryProvider } from "./SalesSdkSummaryContext.js";
import { SalesSdkUIHostsContext } from "./SalesSdkUIHostsContext.js";
import { SalesSdkCartProvider } from "./SalesSdkCartContext.js";
import { useSalesSdkCart } from "../hooks/useSalesSdkCart.js";
import { buildInitBookingContextParams, collectBookingIdsFromTempOrder, ensureBookingConfigForLoad } from "../utils/buildDefaultLoadProductsParams.js";
import { SalesSdkProductProvider } from "./SalesSdkProductContext.js";
import { SalesSdkCustomerProvider } from "./SalesSdkCustomerContext.js";
import { BookingEditHostRenderer } from "../hosts/BookingEditHostRenderer.js";
import { MultiDayHostRenderer } from "../hosts/MultiDayHostRenderer.js";
import { HolderHostRenderer } from "../hosts/HolderHostRenderer.js";
import { NormalProductDetailHostRenderer } from "../normalProductDetail/NormalProductDetailHostRenderer.js";
import { useSalesSdkTempOrderSync } from "../hooks/useSalesSdkTempOrderSync.js";
import dayjs from "dayjs";
import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/plus/salesSdk/context/SalesSdkProvider.tsx
const EMPTY_ROOT_SNAPSHOT = {
	tempOrder: null,
	salesDetail: null
};
const EMPTY_DISCOUNT_LIST = [];
function cloneArray(value, fallback) {
	return Array.isArray(value) ? [...value] : fallback;
}
/**
* 浅克隆 tempOrder，并把 React 频繁读写的数组字段重新装一份，避免 OS 内部就地 mutate
* 后 React 在引用比较里漏掉变更。
*/
function cloneTempOrder(tempOrder) {
	if (!tempOrder) return null;
	return _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 ? _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 = createContext(null);
SalesSdkRootRefreshContext.displayName = "SalesSdkRootRefreshContext";
/**
* 挂载后串行 bootstrap：restore → recalcSummary →（可选）loadDetail → initBookingContext。
* 须位于 SalesSdkCartProvider 内，以便调用 cart.recalcSummary。
*/
function SalesSdkBootstrap({ autoRestoreOnInit, autoBootstrap, autoInitBookingContext, orderId, initBookingContext }) {
	const sales = useContext(SalesSdkContext);
	const cart = useSalesSdkCart();
	useEffect(() => {
		if (!(sales === null || sales === void 0 ? void 0 : sales.bookingTicket)) return;
		let cancelled = false;
		_asyncToGenerator(function* () {
			try {
				var _sales$bookingTicket$, _sales$bookingTicket, _sales$bookingTicket$2;
				if (autoRestoreOnInit) {
					yield sales.restore();
					if (cancelled) return;
					yield cart.recalcSummary();
				}
				if (autoBootstrap && orderId) {
					if (cancelled) return;
					yield sales.loadDetail(orderId);
				}
				if (cancelled || !autoInitBookingContext) return;
				const bookingIds = collectBookingIdsFromTempOrder((_sales$bookingTicket$ = (_sales$bookingTicket = sales.bookingTicket) === null || _sales$bookingTicket === void 0 || (_sales$bookingTicket$2 = _sales$bookingTicket.getTempOrder) === null || _sales$bookingTicket$2 === void 0 ? void 0 : _sales$bookingTicket$2.call(_sales$bookingTicket)) !== null && _sales$bookingTicket$ !== void 0 ? _sales$bookingTicket$ : null);
				yield initBookingContext(bookingIds.length ? bookingIds : void 0);
			} catch (e) {
				if (!cancelled) console.warn("[SalesSdk] bootstrap 失败", e);
			}
		})();
		return () => {
			cancelled = true;
		};
	}, [
		sales === null || sales === void 0 ? void 0 : sales.bookingTicket,
		sales === null || sales === void 0 ? void 0 : sales.osKey,
		sales === null || sales === void 0 ? void 0 : sales.restore,
		sales === null || sales === void 0 ? void 0 : sales.loadDetail,
		cart.recalcSummary,
		autoRestoreOnInit,
		autoBootstrap,
		autoInitBookingContext,
		orderId,
		initBookingContext
	]);
	return null;
}
const SalesSdkProvider = ({ osKey, businessCode, bookingConfigParams, autoInitBookingContext = true, otherParams, rulesHooks, orderId, autoBootstrap = true, autoRestoreOnInit = true, uiHosts, enableTempOrderSync = false, isActive = true, children }) => {
	var _context$appHelper;
	const context = useEngineContext();
	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 = useMemo(() => {
		if (!pisellos || !BookingTicket) return null;
		const moduleKey = getBookingTicketKey(osKey);
		let mod = pisellos.getModule(moduleKey);
		if (!mod) {
			var _businessUtils$getApp;
			mod = new BookingTicket(moduleKey);
			pisellos.registerModule(mod, { otherParams: _objectSpread2({
				cacheId: moduleKey,
				platform: (otherParams === null || otherParams === void 0 ? void 0 : otherParams.platform) || "pos",
				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] = useState("idle");
	const [error, setError] = useState(null);
	const [rootSnapshot, setRootSnapshot] = useState(EMPTY_ROOT_SNAPSHOT);
	const publishTempOrderRef = useRef(() => {});
	/**
	* 内部 refresh：所有改 OS 的入口在动作完成后调一次，把 tempOrder / salesDetail 同步到顶层 state。
	* 子 Provider 通过 `SalesSdkRootRefreshContext` 拿到此函数。
	*/
	const refreshRootSnapshot = useMemoizedFn(() => {
		const nextSnapshot = readRootSnapshot(bookingTicket);
		setRootSnapshot(nextSnapshot);
		publishTempOrderRef.current(nextSnapshot.tempOrder);
	});
	const { publishTempOrder } = useSalesSdkTempOrderSync({
		enabled: enableTempOrderSync,
		isActive,
		osKey,
		bookingTicket,
		refreshRootSnapshot
	});
	publishTempOrderRef.current = publishTempOrder;
	useEffect(() => {
		refreshRootSnapshot();
	}, [bookingTicket, refreshRootSnapshot]);
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
			refreshRootSnapshot();
		});
		return () => {
			try {
				off();
			} catch (_unused) {}
		};
	}, [bookingTicket, refreshRootSnapshot]);
	console.log(bookingConfigParams, "bookingConfigParams123");
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onOrderCustomerChange", () => {
			refreshRootSnapshot();
		});
		return () => {
			try {
				off();
			} catch (_unused2) {}
		};
	}, [bookingTicket, refreshRootSnapshot]);
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onTempOrderReplaced", () => {
			refreshRootSnapshot();
		});
		return () => {
			try {
				off();
			} catch (_unused3) {}
		};
	}, [bookingTicket, refreshRootSnapshot]);
	console.log(bookingConfigParams, "bookingConfigParams1232");
	const initBookingContext = useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (bookingIds) {
			if (!(bookingTicket === null || bookingTicket === void 0 ? void 0 : bookingTicket.initBookingContext)) return;
			yield bookingTicket.initBookingContext(buildInitBookingContextParams(bookingConfigParams, { bookingIds }));
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	/** loadProducts 前补拉 boardConfig；与 bootstrap 同参，但不强制拉 resources。 */
	const ensureBookingConfigForLoad$1 = useMemoizedFn(_asyncToGenerator(function* () {
		var _bookingTicket$getTem3, _bookingTicket$getTem4;
		if (!bookingTicket) return;
		const bookingIds = collectBookingIdsFromTempOrder((_bookingTicket$getTem3 = (_bookingTicket$getTem4 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem4 === void 0 ? void 0 : _bookingTicket$getTem4.call(bookingTicket)) !== null && _bookingTicket$getTem3 !== void 0 ? _bookingTicket$getTem3 : null);
		yield ensureBookingConfigForLoad(bookingTicket, buildInitBookingContextParams(bookingConfigParams, {
			bookingIds: bookingIds.length ? bookingIds : void 0,
			loadResources: false
		}));
	}));
	const loadDetail = useMemoizedFn(function() {
		var _ref2 = _asyncToGenerator(function* (id) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			setStatus("loading");
			setError(null);
			try {
				const sales = yield bookingTicket.loadSalesDetail(id);
				refreshRootSnapshot();
				if (autoInitBookingContext && bookingTicket.loadBookingResources) {
					var _bookings;
					const bookingIds = sales === null || sales === void 0 || (_bookings = sales.bookings) === null || _bookings === void 0 ? void 0 : _bookings.map((b) => b === null || b === void 0 ? void 0 : b.id).filter((bid) => typeof bid === "number" && Number.isFinite(bid));
					yield bookingTicket.loadBookingResources({
						date: dayjs().format("YYYY-MM-DD"),
						bookingIds: (bookingIds === null || bookingIds === void 0 ? void 0 : bookingIds.length) ? bookingIds : void 0
					});
				}
				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(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	/** 跳过本地缓存，以 `{ orderId, forceRemote: true }` 形态调用 OS loadSalesDetail */
	const loadDetailByRemote = useMemoizedFn(function() {
		var _ref3 = _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(_x3) {
			return _ref3.apply(this, arguments);
		};
	}());
	useEffect(() => {
		var _bookingTicket$initPe;
		if (!bookingTicket || !isActive) return;
		(_bookingTicket$initPe = bookingTicket.initPeripheralsListener) === null || _bookingTicket$initPe === void 0 || _bookingTicket$initPe.call(bookingTicket);
	}, [bookingTicket, isActive]);
	/**
	* 基于当前 tempOrder.order_id 强制从远端刷新销售详情（转发 OS refreshSalesDetail）。
	* 不写 loading 态，避免编辑中后台刷新导致 UI 闪烁；成功后同步顶层 tempOrder / salesDetail。
	*/
	const refreshSalesDetail = useMemoizedFn(_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 = useMemoizedFn(_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 = useMemoizedFn(_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;
		}
	}));
	/** 仅清空 products / bookings / discount_list（OS clearOrderCartLines）。 */
	const clearCartItemsOnly = useMemoizedFn(_asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		if (typeof bookingTicket.clearOrderCartLines !== "function") throw new Error("[SalesSdk] bookingTicket.clearOrderCartLines 不可用，请升级 pisellos");
		try {
			const tempOrder = yield bookingTicket.clearOrderCartLines();
			refreshRootSnapshot();
			setError(null);
			return tempOrder;
		} 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;
		}
	}));
	/** 清空所有并重置（OS restoreOrder + 清客户）。 */
	const clearCartAndReset = useMemoizedFn(_asyncToGenerator(function* () {
		return restore();
	}));
	const destroy = useMemoizedFn(_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 = useMemoizedFn(_asyncToGenerator(function* () {
		var _bookingTicket$getTem5;
		if (typeof action !== "function") throw new Error("[SalesSdk] appHelper.utils.action is not available.");
		if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
		const tempOrder = (_bookingTicket$getTem5 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem5 === void 0 ? void 0 : _bookingTicket$getTem5.call(bookingTicket);
		const orderIdFromTemp = tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id;
		return new Promise((resolve) => {
			let settled = false;
			action({
				type: "pisell1.handleOpenPayment",
				data: {
					order: { id: orderIdFromTemp },
					baseSalesModuleName: getBookingTicketKey(osKey)
				},
				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 (settled) return;
					settled = true;
					resolve(res);
				}
			});
		});
	}));
	/**
	* 变更预约状态：直接转发到 BookingTicket.setBookingStatus。
	* OS 内部已经做了乐观更新 + 失败回滚 + 强制刷新详情，这里仅同步 SDK 的 error 状态。
	*/
	const setBookingStatus = useMemoizedFn(function() {
		var _ref4 = _asyncToGenerator(function* (status) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			try {
				var _bookingTicket$getTem6;
				const data = yield bookingTicket.setBookingStatus(status);
				const tempOrder = (_bookingTicket$getTem6 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem6 === void 0 ? void 0 : _bookingTicket$getTem6.call(bookingTicket);
				action({
					type: "webpos.updateLocalOrderApi",
					data: { order_id: tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id }
				});
				refreshRootSnapshot();
				setError(null);
				return data;
			} 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;
			}
		});
		return function(_x4) {
			return _ref4.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$message8;
			const err = e instanceof Error ? e : new Error(String((_e$message8 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message8 !== void 0 ? _e$message8 : e));
			setError(err);
			throw err;
		}
	}
	/** 写入订单备注（tempOrder.note，字符串）。 */
	const setOrderNote = useMemoizedFn((note) => runTempOrderMutation((handle) => handle.updateTempOrderNote(note)));
	/**
	* 写入整单优惠金额（tempOrder.shop_discount）。
	* OS 内部 Decimal 标准化：负数归零、保留 2 位小数；返回标准化后的字符串。
	*/
	const setShopDiscount = useMemoizedFn((amount) => runTempOrderMutation((handle) => handle.updateTempOrderShopDiscount(amount)));
	/**
	* 写入联系人信息（tempOrder.contacts_info）。
	* OS 内部防御：非对象/数组都归 null，只接对象或 null；返回最终写入的对象或 null。
	*/
	const setContactsInfo = useMemoizedFn((contactsInfo) => runTempOrderMutation((handle) => handle.updateTempOrderContactsInfo(contactsInfo)));
	const activateCamera = useMemoizedFn((data) => {
		bookingTicket === null || bookingTicket === void 0 || bookingTicket.activateCamera(data);
	});
	/** 读取当前折扣列表（克隆副本，与 OS BaseSales.getDiscountList 对齐）。 */
	const getDiscountList = useMemoizedFn(() => {
		var _bookingTicket$getDis;
		if (!bookingTicket) return [];
		return cloneArray((_bookingTicket$getDis = bookingTicket.getDiscountList) === null || _bookingTicket$getDis === void 0 ? void 0 : _bookingTicket$getDis.call(bookingTicket), EMPTY_DISCOUNT_LIST);
	});
	const scanPromotionCode = useMemoizedFn(function() {
		var _ref5 = _asyncToGenerator(function* (code, customerId) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			try {
				const result = yield bookingTicket.scanPromotionCode(code, customerId);
				if (result === null || result === void 0 ? void 0 : result.isAvailable) refreshRootSnapshot();
				setError(null);
				return result;
			} catch (e) {
				var _e$message9;
				const err = e instanceof Error ? e : new Error(String((_e$message9 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message9 !== void 0 ? _e$message9 : e));
				setError(err);
				throw err;
			}
		});
		return function(_x5, _x6) {
			return _ref5.apply(this, arguments);
		};
	}());
	const setDiscountSelected = useMemoizedFn(function() {
		var _ref6 = _asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
			try {
				yield bookingTicket.setDiscountSelected(params);
				refreshRootSnapshot();
				setError(null);
			} catch (e) {
				var _e$message10;
				const err = e instanceof Error ? e : new Error(String((_e$message10 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message10 !== void 0 ? _e$message10 : e));
				setError(err);
				throw err;
			}
		});
		return function(_x7) {
			return _ref6.apply(this, arguments);
		};
	}());
	const uiHostsValue = useMemo(() => uiHosts ? {
		openProductDetail: uiHosts.openProductDetail,
		openBookingEdit: uiHosts.openBookingEdit,
		openMultiDaySelect: uiHosts.openMultiDaySelect,
		openHolderSelect: uiHosts.openHolderSelect
	} : null, [
		uiHosts === null || uiHosts === void 0 ? void 0 : uiHosts.openProductDetail,
		uiHosts === null || uiHosts === void 0 ? void 0 : uiHosts.openBookingEdit,
		uiHosts === null || uiHosts === void 0 ? void 0 : uiHosts.openMultiDaySelect,
		uiHosts === null || uiHosts === void 0 ? void 0 : uiHosts.openHolderSelect
	]);
	const value = 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,
			clearCartItemsOnly,
			clearCartAndReset,
			destroy,
			setBookingStatus,
			setOrderNote,
			setShopDiscount,
			setContactsInfo,
			activateCamera,
			openCheckout,
			getDiscountList,
			scanPromotionCode,
			setDiscountSelected,
			ensureBookingConfigForLoad: ensureBookingConfigForLoad$1
		};
	}, [
		bookingTicket,
		osKey,
		status,
		error,
		rootSnapshot,
		loadDetail,
		loadDetailByRemote,
		refreshSalesDetail,
		createNew,
		restore,
		clearCartItemsOnly,
		clearCartAndReset,
		destroy,
		setBookingStatus,
		setOrderNote,
		setShopDiscount,
		setContactsInfo,
		activateCamera,
		openCheckout,
		getDiscountList,
		scanPromotionCode,
		setDiscountSelected,
		ensureBookingConfigForLoad$1
	]);
	return /* @__PURE__ */ React.createElement(SalesSdkContext.Provider, { value }, /* @__PURE__ */ React.createElement(SalesSdkUIHostsContext.Provider, { value: uiHostsValue }, /* @__PURE__ */ React.createElement(SalesSdkRootRefreshContext.Provider, { value: refreshRootSnapshot }, /* @__PURE__ */ React.createElement(SalesSdkProductProvider, null, /* @__PURE__ */ React.createElement(SalesSdkSummaryProvider, null, /* @__PURE__ */ React.createElement(SalesSdkCartProvider, null, /* @__PURE__ */ React.createElement(SalesSdkBootstrap, {
		autoRestoreOnInit,
		autoBootstrap,
		autoInitBookingContext,
		orderId,
		initBookingContext
	}), /* @__PURE__ */ React.createElement(SalesSdkCustomerProvider, null, (uiHostsValue === null || uiHostsValue === void 0 ? void 0 : uiHostsValue.openBookingEdit) ? /* @__PURE__ */ React.createElement(BookingEditHostRenderer, null) : null, (uiHostsValue === null || uiHostsValue === void 0 ? void 0 : uiHostsValue.openMultiDaySelect) ? /* @__PURE__ */ React.createElement(MultiDayHostRenderer, null) : null, (uiHostsValue === null || uiHostsValue === void 0 ? void 0 : uiHostsValue.openHolderSelect) ? /* @__PURE__ */ React.createElement(HolderHostRenderer, null) : null, /* @__PURE__ */ React.createElement(NormalProductDetailHostRenderer, null), children)))))));
};
//#endregion
export { SalesSdkProvider, SalesSdkRootRefreshContext };
