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_SalesSdkContext = require("./SalesSdkContext.js");
const require_SalesSdkSummaryContext = require("./SalesSdkSummaryContext.js");
const require_SalesSdkUIHostsContext = require("./SalesSdkUIHostsContext.js");
const require_resolveCacheItemForResourceCheck = require("../bookingEditService/resolveCacheItemForResourceCheck.js");
const require_buildBookingEditDrawerState = require("../bookingEditService/buildBookingEditDrawerState.js");
const require_enrichCacheItemBeforeAdd = require("../utils/enrichCacheItemBeforeAdd.js");
const require_patchCacheItemDateRange = require("../utils/patchCacheItemDateRange.js");
const require_mergeCatalogDurationIntoCacheItem = require("../utils/mergeCatalogDurationIntoCacheItem.js");
const require_resolveConfirmDetailQuantity = require("../utils/resolveConfirmDetailQuantity.js");
const require_runAddProductFlow = require("../utils/runAddProductFlow.js");
const require_addProductWithFlowDebounced = require("../utils/addProductWithFlowDebounced.js");
const require_applyExplicitAddQuantityToCacheItem = require("../utils/applyExplicitAddQuantityToCacheItem.js");
const require_bookingDate = require("../utils/bookingDate.js");
const require_locales = require("../../../components/ticketBooking/locales.js");
const require_editCartLine = require("../utils/editCartLine.js");
const require_editCartLineBooking = require("../utils/editCartLineBooking.js");
const require_editCartLineProduct = require("../utils/editCartLineProduct.js");
const require_buildCustomOrderProductFromCustomiseItem = require("../utils/buildCustomOrderProductFromCustomiseItem.js");
const require_enrich = require("../utils/enrich.js");
const require_SalesSdkProvider = require("./SalesSdkProvider.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
//#region src/plus/salesSdk/context/SalesSdkCartContext.tsx
const SalesSdkCartContext = (0, react.createContext)(null);
SalesSdkCartContext.displayName = "SalesSdkCartContext";
const EMPTY_DISCOUNT_LIST = [];
const EMPTY_ITEMS = [];
const EMPTY_SNAPSHOT = {
	tempOrder: null,
	salesDetail: null,
	bookings: [],
	items: EMPTY_ITEMS,
	discountList: EMPTY_DISCOUNT_LIST
};
function cloneArray(value, fallback) {
	return Array.isArray(value) ? [...value] : fallback;
}
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 indexBookingsByProductUid(bookings) {
	if (!Array.isArray(bookings) || bookings.length === 0) return {};
	return bookings.reduce((acc, booking) => {
		const uid = booking === null || booking === void 0 ? void 0 : booking.product_uid;
		if (uid === void 0 || uid === null || uid === "") return acc;
		const key = String(uid);
		if (!acc[key]) acc[key] = [];
		acc[key].push(booking);
		return acc;
	}, {});
}
function readSnapshot(bookingTicket) {
	if (!bookingTicket) return EMPTY_SNAPSHOT;
	try {
		var _bookingTicket$getTem, _bookingTicket$getTem2, _bookingTicket$getSal, _bookingTicket$getSal2, _bookingTicket$getPro, _bookingTicket$getPro2, _ref, _salesDetail$bookings, _extend, _bookingTicket$getCar, _bookingTicket$getCar2, _tempOrder$products, _bookingTicket$getDis;
		const 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);
		const 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;
		const catalog = (_bookingTicket$getPro = (_bookingTicket$getPro2 = bookingTicket.getProductCatalog) === null || _bookingTicket$getPro2 === void 0 || (_bookingTicket$getPro2 = _bookingTicket$getPro2.call(bookingTicket)) === null || _bookingTicket$getPro2 === void 0 ? void 0 : _bookingTicket$getPro2.products) !== null && _bookingTicket$getPro !== void 0 ? _bookingTicket$getPro : [];
		const enrichCtx = {
			bookingDetailMap: indexBookingsByProductUid((_ref = (_salesDetail$bookings = salesDetail === null || salesDetail === void 0 ? void 0 : salesDetail.bookings) !== null && _salesDetail$bookings !== void 0 ? _salesDetail$bookings : tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.bookings) !== null && _ref !== void 0 ? _ref : []),
			productsCatalog: catalog,
			productsByUid: tempOrder === null || tempOrder === void 0 || (_extend = tempOrder._extend) === null || _extend === void 0 ? void 0 : _extend.productsByUid
		};
		const cartView = (_bookingTicket$getCar = (_bookingTicket$getCar2 = bookingTicket.getCart) === null || _bookingTicket$getCar2 === void 0 ? void 0 : _bookingTicket$getCar2.call(bookingTicket)) !== null && _bookingTicket$getCar !== void 0 ? _bookingTicket$getCar : {
			bookings: [],
			items: (_tempOrder$products = tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.products) !== null && _tempOrder$products !== void 0 ? _tempOrder$products : []
		};
		const items = require_enrich.enrichCartItems(cartView.items, enrichCtx);
		return {
			tempOrder,
			salesDetail,
			bookings: cartView.bookings.map((booking) => {
				var _booking$_extend;
				return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, booking), {}, { _extend: { product: ((_booking$_extend = booking._extend) === null || _booking$_extend === void 0 ? void 0 : _booking$_extend.product) ? require_enrich.enrichCartItem(booking._extend.product, enrichCtx) : null } });
			}),
			items,
			discountList: cloneArray((_bookingTicket$getDis = bookingTicket.getDiscountList) === null || _bookingTicket$getDis === void 0 ? void 0 : _bookingTicket$getDis.call(bookingTicket), EMPTY_DISCOUNT_LIST)
		};
	} catch (e) {
		console.warn("[SalesSdk] CartProvider readSnapshot 失败", e);
		return EMPTY_SNAPSHOT;
	}
}
/**
* 购物车 Provider。
*
* 职责：仅维护购物车域的 UI 视图（`bookings` / `items` enriched + `discountList`）。
* `tempOrder` / `salesDetail` 是 SDK 顶层 Provider 的单一真源，通过 `useSalesSdk()` 直接读取，
* 本 Provider 不再持有镜像。
*/
const SalesSdkCartProvider = ({ children }) => {
	var _sales$bookingTicket;
	const sales = (0, react.useContext)(require_SalesSdkContext.SalesSdkContext);
	const bookingTicket = (_sales$bookingTicket = sales === null || sales === void 0 ? void 0 : sales.bookingTicket) !== null && _sales$bookingTicket !== void 0 ? _sales$bookingTicket : null;
	const uiHosts = (0, react.useContext)(require_SalesSdkUIHostsContext.SalesSdkUIHostsContext);
	const refreshSummary = (0, react.useContext)(require_SalesSdkSummaryContext.SalesSdkSummaryRefreshContext);
	const refreshRoot = (0, react.useContext)(require_SalesSdkProvider.SalesSdkRootRefreshContext);
	const Toast = (0, _pisell_materials.useToast)();
	const [snapshot, setSnapshot] = (0, react.useState)(EMPTY_SNAPSHOT);
	const cartItemsRef = (0, react.useRef)(EMPTY_ITEMS);
	cartItemsRef.current = snapshot.items;
	(0, react.useEffect)(() => {
		_pisell_utils.locales.init(require_locales.default, _pisell_utils.locales.locale || "en");
	}, []);
	(0, react.useEffect)(() => {
		setSnapshot(readSnapshot(bookingTicket));
	}, [bookingTicket]);
	(0, react.useEffect)(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
			setSnapshot(readSnapshot(bookingTicket));
		});
		return () => {
			try {
				off();
			} catch (_unused) {}
		};
	}, [bookingTicket]);
	(0, react.useEffect)(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onTempOrderReplaced", () => {
			setSnapshot(readSnapshot(bookingTicket));
		});
		return () => {
			try {
				off();
			} catch (_unused2) {}
		};
	}, [bookingTicket]);
	(0, react.useEffect)(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onOrderCustomerChange", () => {
			setSnapshot(readSnapshot(bookingTicket));
		});
		return () => {
			try {
				off();
			} catch (_unused3) {}
		};
	}, [bookingTicket]);
	(0, react.useEffect)(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onDiscountApplied", () => {
			setSnapshot(readSnapshot(bookingTicket));
		});
		return () => {
			try {
				off();
			} catch (_unused4) {}
		};
	}, [bookingTicket]);
	const syncSummary = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!refreshSummary) return null;
		try {
			return yield refreshSummary();
		} catch (e) {
			console.warn("[SalesSdk] CartProvider 同步 summary 失败", e);
			return null;
		}
	}));
	const refreshAfterMutation = (0, ahooks.useMemoizedFn)(() => {
		setSnapshot(readSnapshot(bookingTicket));
		refreshRoot === null || refreshRoot === void 0 || refreshRoot();
	});
	/**
	* 加购链路共享上下文：date 为完整 `YYYY-MM-DD HH:mm:ss`，与 BookingContext / TimeBar 对齐。
	*
	* @example
	* const { date, customerId } = getAddFlowContext();
	* bookingTicket.decideAddProduct(product, { date, customerId });
	*/
	const getAddFlowContext = (0, ahooks.useMemoizedFn)(() => {
		var _bookingTicket$getBoo, _cloneTempOrder, _bookingTicket$getTem3, _bookingTicket$getTem4, _bookingTicket$getOrd, _bookingTicket$getBoo2, _bookingTicket$getBoo3;
		const date = require_bookingDate.formatBookingDateTime(bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getBoo = bookingTicket.getBookingDate) === null || _bookingTicket$getBoo === void 0 ? void 0 : _bookingTicket$getBoo.call(bookingTicket));
		const liveTempOrder = (_cloneTempOrder = cloneTempOrder((_bookingTicket$getTem3 = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getTem4 = bookingTicket.getTempOrder) === null || _bookingTicket$getTem4 === void 0 ? void 0 : _bookingTicket$getTem4.call(bookingTicket)) !== null && _bookingTicket$getTem3 !== void 0 ? _bookingTicket$getTem3 : null)) !== null && _cloneTempOrder !== void 0 ? _cloneTempOrder : snapshot.tempOrder;
		const customerId = require_buildBookingEditDrawerState.resolveAddFlowCustomerId(liveTempOrder, void 0, bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getOrd = bookingTicket.getOrderCustomerSnapshot) === null || _bookingTicket$getOrd === void 0 || (_bookingTicket$getOrd = _bookingTicket$getOrd.call(bookingTicket)) === null || _bookingTicket$getOrd === void 0 ? void 0 : _bookingTicket$getOrd.id);
		return {
			bookingConfig: (_bookingTicket$getBoo2 = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getBoo3 = bookingTicket.getBookingConfig) === null || _bookingTicket$getBoo3 === void 0 ? void 0 : _bookingTicket$getBoo3.call(bookingTicket)) !== null && _bookingTicket$getBoo2 !== void 0 ? _bookingTicket$getBoo2 : null,
			customerId,
			tempOrder: liveTempOrder,
			locale: _pisell_utils.locales.locale,
			date
		};
	});
	const addCustomProduct = (0, ahooks.useMemoizedFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (input) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const orderLine = require_buildCustomOrderProductFromCustomiseItem.buildCustomOrderProductFromCustomiseItem(input);
			const products = yield bookingTicket.addProductToOrder(orderLine);
			refreshAfterMutation();
			yield syncSummary();
			return products;
		});
		return function(_x) {
			return _ref2.apply(this, arguments);
		};
	}());
	const addProductToOrderFromCache = (0, ahooks.useMemoizedFn)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (item, cacheItem, options) {
			var _flowCtx$date;
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			if (typeof bookingTicket.transformDetailToProductAndBooking !== "function") throw new Error("[SalesSdk] Cart: bookingTicket.transformDetailToProductAndBooking 不可用");
			const flowCtx = getAddFlowContext();
			const { product: orderLine, booking } = bookingTicket.transformDetailToProductAndBooking({
				item,
				cacheItem: require_resolveCacheItemForResourceCheck.resolveCacheItemForResourceCheck(cacheItem),
				options: {
					quantity: options === null || options === void 0 ? void 0 : options.quantity,
					date: (_flowCtx$date = flowCtx.date) !== null && _flowCtx$date !== void 0 ? _flowCtx$date : void 0
				}
			});
			const products = yield bookingTicket.addProductToOrder(orderLine, booking);
			refreshAfterMutation();
			yield syncSummary();
			return products;
		});
		return function(_x2, _x3, _x4) {
			return _ref3.apply(this, arguments);
		};
	}());
	/**
	* 加车：走 OS `decideAddProduct` 两阶段决策。
	*/
	const addProduct = (0, ahooks.useMemoizedFn)(function() {
		var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (product, options) {
			var _flowCtx$date2;
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			if (typeof bookingTicket.decideAddProduct !== "function") throw new Error("[SalesSdk] Cart: bookingTicket.decideAddProduct 不可用，请升级 pisellos");
			const flowCtx = getAddFlowContext();
			const decision = bookingTicket.decideAddProduct(product, {
				type: (options === null || options === void 0 ? void 0 : options.type) || "select",
				quantity: options === null || options === void 0 ? void 0 : options.quantity,
				date: (_flowCtx$date2 = flowCtx.date) !== null && _flowCtx$date2 !== void 0 ? _flowCtx$date2 : void 0,
				customerId: flowCtx.customerId
			});
			if (decision.action === "requiresDetail") {
				var _decision$payload, _bookingTicket$buildR, _flowCtx$date3;
				return {
					status: "requiresDetail",
					payload: (_decision$payload = decision.payload) !== null && _decision$payload !== void 0 ? _decision$payload : (_bookingTicket$buildR = bookingTicket.buildRequiresDetailPayload) === null || _bookingTicket$buildR === void 0 ? void 0 : _bookingTicket$buildR.call(bookingTicket, product, {
						type: (options === null || options === void 0 ? void 0 : options.type) || "select",
						quantity: options === null || options === void 0 ? void 0 : options.quantity,
						date: (_flowCtx$date3 = flowCtx.date) !== null && _flowCtx$date3 !== void 0 ? _flowCtx$date3 : void 0,
						customerId: flowCtx.customerId
					})
				};
			}
			if (decision.action === "requiresBookingEdit") {
				var _decision$payload2, _flowCtx$date4, _ref4, _flowCtx$date5, _decision$payload3, _flowCtx$customerId, _decision$payload4;
				return {
					status: "requiresBookingEdit",
					payload: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (_decision$payload2 = decision.payload) !== null && _decision$payload2 !== void 0 ? _decision$payload2 : { date: (_flowCtx$date4 = flowCtx.date) !== null && _flowCtx$date4 !== void 0 ? _flowCtx$date4 : null }), {}, {
						cacheItem: decision.cacheItem,
						date: (_ref4 = (_flowCtx$date5 = flowCtx.date) !== null && _flowCtx$date5 !== void 0 ? _flowCtx$date5 : (_decision$payload3 = decision.payload) === null || _decision$payload3 === void 0 ? void 0 : _decision$payload3.date) !== null && _ref4 !== void 0 ? _ref4 : null,
						customerId: (_flowCtx$customerId = flowCtx.customerId) !== null && _flowCtx$customerId !== void 0 ? _flowCtx$customerId : (_decision$payload4 = decision.payload) === null || _decision$payload4 === void 0 ? void 0 : _decision$payload4.customerId
					})
				};
			}
			const addQty = (options === null || options === void 0 ? void 0 : options.quantity) != null && options.quantity > 0 ? options.quantity : 1;
			const enriched = yield require_enrichCacheItemBeforeAdd.enrichCacheItemBeforeAdd(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
				cacheItem: require_applyExplicitAddQuantityToCacheItem.applyExplicitAddQuantityToCacheItem(decision.cacheItem, addQty),
				uiHosts
			}, flowCtx), {}, { mode: "direct" }));
			if (enriched.status !== "ok") throw new Error("[SalesSdk] addProduct: 加车前校验未通过（Holder / 跨日 Host 未配置或用户取消）");
			return {
				status: "added",
				products: yield addProductToOrderFromCache(product, enriched.cacheItem, { quantity: addQty })
			};
		});
		return function(_x5, _x6) {
			return _ref5.apply(this, arguments);
		};
	}());
	/**
	* 规格弹窗 callback 完成后：先跑第二段 `decideAfterDetail`，再决定加车或开资源抽屉。
	*/
	const confirmDetail = (0, ahooks.useMemoizedFn)(function() {
		var _ref7 = require_asyncToGenerator._asyncToGenerator(function* (input) {
			var _flowCtx$date6, _input$options;
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			if (typeof bookingTicket.transformDetailToProductAndBooking !== "function") throw new Error("[SalesSdk] Cart: bookingTicket.transformDetailToProductAndBooking 不可用");
			const confirmQuantity = require_resolveConfirmDetailQuantity.resolveConfirmDetailQuantity(input);
			const flowCtx = getAddFlowContext();
			const draft = bookingTicket.transformDetailToProductAndBooking({
				item: input.item,
				detailResult: input.detailResult,
				options: {
					quantity: confirmQuantity,
					date: (_flowCtx$date6 = flowCtx.date) !== null && _flowCtx$date6 !== void 0 ? _flowCtx$date6 : void 0,
					customerId: flowCtx.customerId
				}
			});
			const catalogItem = input.item;
			let cacheItem = require_mergeCatalogDurationIntoCacheItem.mergeCatalogDurationIntoCacheItem(draft.cacheItem, catalogItem);
			if ((_input$options = input.options) === null || _input$options === void 0 ? void 0 : _input$options.multiDayRange) cacheItem = require_patchCacheItemDateRange.patchCacheItemDateRange(cacheItem, input.options.multiDayRange);
			else cacheItem = require_patchCacheItemDateRange.applyDefaultMultiDayRangeIfNeeded(cacheItem, catalogItem, flowCtx.date);
			if (typeof bookingTicket.decideAfterDetail === "function") {
				var _flowCtx$date7, _flowCtx$bookingConfi;
				const decision = bookingTicket.decideAfterDetail(cacheItem, {
					quantity: confirmQuantity,
					customerId: flowCtx.customerId,
					date: (_flowCtx$date7 = flowCtx.date) !== null && _flowCtx$date7 !== void 0 ? _flowCtx$date7 : void 0,
					bookingConfig: (_flowCtx$bookingConfi = flowCtx.bookingConfig) !== null && _flowCtx$bookingConfi !== void 0 ? _flowCtx$bookingConfi : void 0
				});
				if (decision.action === "requiresBookingEdit") {
					var _decision$payload5, _ref6, _flowCtx$date8, _decision$payload6, _flowCtx$customerId2, _decision$payload7;
					return {
						status: "requiresBookingEdit",
						payload: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (_decision$payload5 = decision.payload) !== null && _decision$payload5 !== void 0 ? _decision$payload5 : {
							cacheItem: decision.cacheItem,
							date: flowCtx.date
						}), {}, {
							cacheItem: decision.cacheItem,
							date: (_ref6 = (_flowCtx$date8 = flowCtx.date) !== null && _flowCtx$date8 !== void 0 ? _flowCtx$date8 : (_decision$payload6 = decision.payload) === null || _decision$payload6 === void 0 ? void 0 : _decision$payload6.date) !== null && _ref6 !== void 0 ? _ref6 : null,
							customerId: (_flowCtx$customerId2 = flowCtx.customerId) !== null && _flowCtx$customerId2 !== void 0 ? _flowCtx$customerId2 : (_decision$payload7 = decision.payload) === null || _decision$payload7 === void 0 ? void 0 : _decision$payload7.customerId
						})
					};
				}
				const enriched = yield require_enrichCacheItemBeforeAdd.enrichCacheItemBeforeAdd(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
					cacheItem: decision.cacheItem,
					uiHosts
				}, flowCtx), {}, { mode: "direct" }));
				if (enriched.status !== "ok") throw new Error("[SalesSdk] confirmDetail: 加车前校验未通过（Holder / 跨日 Host 未配置或用户取消）");
				return {
					status: "added",
					products: yield addProductToOrderFromCache(input.item, enriched.cacheItem, { quantity: require_resolveConfirmDetailQuantity.resolveAddQuantityFromCacheItem(enriched.cacheItem, confirmQuantity) })
				};
			}
			const enriched = yield require_enrichCacheItemBeforeAdd.enrichCacheItemBeforeAdd(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
				cacheItem,
				uiHosts
			}, flowCtx), {}, { mode: "direct" }));
			if (enriched.status !== "ok") throw new Error("[SalesSdk] confirmDetail: 加车前校验未通过（Holder / 跨日 Host 未配置或用户取消）");
			return {
				status: "added",
				products: yield addProductToOrderFromCache(input.item, enriched.cacheItem, { quantity: require_resolveConfirmDetailQuantity.resolveAddQuantityFromCacheItem(enriched.cacheItem, confirmQuantity) })
			};
		});
		return function(_x7) {
			return _ref7.apply(this, arguments);
		};
	}());
	/** 资源 / 时间抽屉确认后加车。 */
	const confirmBookingEdit = (0, ahooks.useMemoizedFn)(function() {
		var _ref8 = require_asyncToGenerator._asyncToGenerator(function* (input) {
			var _input$options2;
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			return { products: yield addProductToOrderFromCache(input.cacheItem, input.cacheItem, { quantity: require_resolveConfirmDetailQuantity.resolveAddQuantityFromCacheItem(input.cacheItem, (_input$options2 = input.options) === null || _input$options2 === void 0 ? void 0 : _input$options2.quantity) }) };
		});
		return function(_x8) {
			return _ref8.apply(this, arguments);
		};
	}());
	/** 无防抖的加车编排（规格 / 资源弹窗链）。 */
	const runAddProductFlowBase = (0, ahooks.useMemoizedFn)(function() {
		var _ref9 = require_asyncToGenerator._asyncToGenerator(function* (product, options) {
			return require_runAddProductFlow.runAddProductFlow({
				addProduct,
				confirmDetail,
				confirmBookingEdit
			}, uiHosts, product, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, options), getAddFlowContext()));
		});
		return function(_x9, _x10) {
			return _ref9.apply(this, arguments);
		};
	}());
	const addProductRef = (0, react.useRef)(addProduct);
	addProductRef.current = addProduct;
	const runFlowRef = (0, react.useRef)(runAddProductFlowBase);
	runFlowRef.current = runAddProductFlowBase;
	const bookingTicketRef = (0, react.useRef)(bookingTicket);
	bookingTicketRef.current = bookingTicket;
	const getAddFlowContextRef = (0, react.useRef)(getAddFlowContext);
	getAddFlowContextRef.current = getAddFlowContext;
	const debouncedAddRef = (0, react.useRef)(require_addProductWithFlowDebounced.createAddProductWithFlowDebounced({
		decideAddProduct: (product, opts) => {
			var _flowCtx$date9;
			const ticket = bookingTicketRef.current;
			if (!ticket || typeof ticket.decideAddProduct !== "function") return { action: "requiresDetail" };
			const flowCtx = getAddFlowContextRef.current();
			return ticket.decideAddProduct(product, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, opts), {}, {
				date: (_flowCtx$date9 = flowCtx.date) !== null && _flowCtx$date9 !== void 0 ? _flowCtx$date9 : void 0,
				customerId: flowCtx.customerId
			}));
		},
		runAddProductFlow: (product, opts) => runFlowRef.current(product, opts),
		addProductDirect: (product, opts) => addProductRef.current(product, opts),
		getCartItems: () => cartItemsRef.current,
		Toast
	}));
	/**
	* 加车编排：OS 决策 requiresDetail / requiresBookingEdit 立即弹窗；
	* 仅 action=add 时 100ms 防抖合并数量；Toast 在加车成功后展示。
	*/
	const addProductWithFlow = (0, ahooks.useMemoizedFn)(function() {
		var _ref10 = require_asyncToGenerator._asyncToGenerator(function* (product, options) {
			if (!bookingTicketRef.current) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			return debouncedAddRef.current.addProductWithFlow(product, options);
		});
		return function(_x11, _x12) {
			return _ref10.apply(this, arguments);
		};
	}());
	const removeItem = (0, ahooks.useMemoizedFn)(function() {
		var _ref11 = require_asyncToGenerator._asyncToGenerator(function* (item) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const identity = {
				product_id: item.product_id,
				product_variant_id: item.product_variant_id,
				unique_identification_number: item.metadata.unique_identification_number,
				product_option_item: item.product_option_item,
				product_bundle: item.product_bundle
			};
			const result = yield bookingTicket.removeProductFromOrder(identity);
			refreshAfterMutation();
			yield syncSummary();
			return result;
		});
		return function(_x13) {
			return _ref11.apply(this, arguments);
		};
	}());
	const updateItem = (0, ahooks.useMemoizedFn)(function() {
		var _ref12 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			if (typeof bookingTicket.updateOrderProduct !== "function") throw new Error("[SalesSdk] Cart: updateOrderProduct 不可用");
			const result = yield bookingTicket.updateOrderProduct(params);
			refreshAfterMutation();
			yield syncSummary();
			return result;
		});
		return function(_x14) {
			return _ref12.apply(this, arguments);
		};
	}());
	const updateItemQuantity = (0, ahooks.useMemoizedFn)(function() {
		var _ref13 = require_asyncToGenerator._asyncToGenerator(function* (item, num) {
			var _extend$product, _extend2, _productItem$metadata;
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			if (typeof bookingTicket.updateOrderProductQuantity !== "function") throw new Error("[SalesSdk] Cart: updateOrderProductQuantity 不可用");
			const productItem = (_extend$product = item === null || item === void 0 || (_extend2 = item._extend) === null || _extend2 === void 0 ? void 0 : _extend2.product) !== null && _extend$product !== void 0 ? _extend$product : item;
			if (!productItem) throw new Error("[SalesSdk] Cart: 无法解析商品行，无法更新数量");
			const result = yield bookingTicket.updateOrderProductQuantity({
				product_id: productItem.product_id,
				product_variant_id: productItem.product_variant_id,
				unique_identification_number: (_productItem$metadata = productItem.metadata) === null || _productItem$metadata === void 0 ? void 0 : _productItem$metadata.unique_identification_number,
				product_option_item: productItem.product_option_item,
				product_bundle: productItem.product_bundle,
				num
			});
			refreshAfterMutation();
			yield syncSummary();
			return result;
		});
		return function(_x15, _x16) {
			return _ref13.apply(this, arguments);
		};
	}());
	const editCartLineBooking$1 = (0, ahooks.useMemoizedFn)(function() {
		var _ref14 = require_asyncToGenerator._asyncToGenerator(function* (item) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			return require_editCartLineBooking.editCartLineBooking({
				item,
				bookingTicket,
				tempOrder: snapshot.tempOrder,
				uiHosts,
				updateItem
			});
		});
		return function(_x17) {
			return _ref14.apply(this, arguments);
		};
	}());
	const editCartLineProduct$1 = (0, ahooks.useMemoizedFn)(function() {
		var _ref15 = require_asyncToGenerator._asyncToGenerator(function* (item) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			return require_editCartLineProduct.editCartLineProduct({
				item,
				bookingTicket,
				tempOrder: snapshot.tempOrder,
				updateItem
			});
		});
		return function(_x18) {
			return _ref15.apply(this, arguments);
		};
	}());
	const editCartLine = (0, ahooks.useMemoizedFn)(function() {
		var _ref16 = require_asyncToGenerator._asyncToGenerator(function* (target) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const item = require_editCartLine.resolveEditCartLineTarget(target, snapshot.items);
			if (require_editCartLine.shouldEditCartLineAsBooking(item)) return editCartLineBooking$1(item);
			return editCartLineProduct$1(item);
		});
		return function(_x19) {
			return _ref16.apply(this, arguments);
		};
	}());
	const setOrderNote = (0, ahooks.useMemoizedFn)((note) => {
		if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
		const result = bookingTicket.updateTempOrderNote(note);
		setSnapshot(readSnapshot(bookingTicket));
		return result;
	});
	const setLineNote = (0, ahooks.useMemoizedFn)(function() {
		var _ref17 = require_asyncToGenerator._asyncToGenerator(function* (identity, note) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const result = yield bookingTicket.setOrderProductLineNote(identity, note);
			refreshAfterMutation();
			return result;
		});
		return function(_x20, _x21) {
			return _ref17.apply(this, arguments);
		};
	}());
	const setDiscount = (0, ahooks.useMemoizedFn)(function() {
		var _ref18 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			yield bookingTicket.setDiscountSelected(params);
			refreshAfterMutation();
			yield syncSummary();
		});
		return function(_x22) {
			return _ref18.apply(this, arguments);
		};
	}());
	const scanCode = (0, ahooks.useMemoizedFn)(function() {
		var _ref19 = require_asyncToGenerator._asyncToGenerator(function* (code, customerId) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const result = yield bookingTicket.scanPromotionCode(code, customerId);
			if (result === null || result === void 0 ? void 0 : result.isAvailable) refreshAfterMutation();
			yield syncSummary();
			return result;
		});
		return function(_x23, _x24) {
			return _ref19.apply(this, arguments);
		};
	}());
	const submit = (0, ahooks.useMemoizedFn)(function() {
		var _ref20 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			return bookingTicket.submitSalesOrder(params);
		});
		return function(_x25) {
			return _ref20.apply(this, arguments);
		};
	}());
	const recalcSummary = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
		const summary = yield syncSummary();
		refreshAfterMutation();
		return summary !== null && summary !== void 0 ? summary : null;
	}));
	const value = (0, react.useMemo)(() => ({
		tempOrder: snapshot.tempOrder,
		salesDetail: snapshot.salesDetail,
		discountList: snapshot.discountList,
		bookings: snapshot.bookings,
		items: snapshot.items,
		addProduct,
		addProductWithFlow,
		addCustomProduct,
		confirmDetail,
		confirmBookingEdit,
		removeItem,
		updateItem,
		updateItemQuantity,
		setOrderNote,
		setLineNote,
		setDiscount,
		scanCode,
		submit,
		recalcSummary,
		editCartLineBooking: editCartLineBooking$1,
		editCartLineProduct: editCartLineProduct$1,
		editCartLine
	}), [
		snapshot,
		addProduct,
		addProductWithFlow,
		addCustomProduct,
		confirmDetail,
		confirmBookingEdit,
		removeItem,
		updateItem,
		updateItemQuantity,
		editCartLineBooking$1,
		editCartLineProduct$1,
		editCartLine,
		setOrderNote,
		setLineNote,
		setDiscount,
		scanCode,
		submit,
		recalcSummary
	]);
	return /* @__PURE__ */ react.default.createElement(SalesSdkCartContext.Provider, { value }, children);
};
//#endregion
exports.SalesSdkCartContext = SalesSdkCartContext;
exports.SalesSdkCartProvider = SalesSdkCartProvider;
