import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { SalesSdkContext } from "./SalesSdkContext.js";
import { SalesSdkSummaryRefreshContext } from "./SalesSdkSummaryContext.js";
import { SalesSdkRootRefreshContext } from "./SalesSdkProvider.js";
import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/plus/salesSdk/context/SalesSdkCartContext.tsx
const SalesSdkCartContext = createContext(null);
SalesSdkCartContext.displayName = "SalesSdkCartContext";
const EMPTY_DISCOUNT_LIST = [];
const EMPTY_ITEMS = [];
const EMPTY_BOOKINGS = [];
const EMPTY_SNAPSHOT = {
	bookings: EMPTY_BOOKINGS,
	items: EMPTY_ITEMS,
	discountList: EMPTY_DISCOUNT_LIST
};
function cloneArray(value, fallback) {
	return Array.isArray(value) ? [...value] : fallback;
}
function readSnapshot(bookingTicket) {
	if (!bookingTicket) return EMPTY_SNAPSHOT;
	try {
		var _bookingTicket$getCar, _bookingTicket$getDis;
		const cart = (_bookingTicket$getCar = bookingTicket.getCart) === null || _bookingTicket$getCar === void 0 ? void 0 : _bookingTicket$getCar.call(bookingTicket);
		return {
			bookings: cloneArray(cart === null || cart === void 0 ? void 0 : cart.bookings, EMPTY_BOOKINGS),
			items: cloneArray(cart === null || cart === void 0 ? void 0 : cart.items, EMPTY_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 不再持有镜像。
*
* Phase 1 订阅源：
*  - `${bookingTicket.name}:onSalesOrderLoaded`（编辑态详情拉到后 emit；payload = { sales }）
*
* Phase 2 扩展：OS OrderModule 增加 `${name}:onTempOrderChanged` emit 后，本 Provider 仅需把
*               事件名加进订阅数组即可实时刷新 items（无需改消费方）。
*
* 写动作时序：每个 action 内部按「OS mutate → 刷 items 快照 → `refreshRoot()` 同步顶层 tempOrder」
* 顺序执行，保证下游同一次渲染里 items 与 tempOrder 来自同一 OS 状态。
*
* getCart 由 OS 拆分 bookings/items；商品行透传 tempOrder.products，enrichment 由 UI 按需处理。
*
* Action 引用纪律：每个 action 用 `useMemoizedFn` 单独包装；详见 docs.md。
*/
const SalesSdkCartProvider = ({ children }) => {
	var _sales$bookingTicket;
	const sales = useContext(SalesSdkContext);
	const bookingTicket = (_sales$bookingTicket = sales === null || sales === void 0 ? void 0 : sales.bookingTicket) !== null && _sales$bookingTicket !== void 0 ? _sales$bookingTicket : null;
	const refreshSummary = useContext(SalesSdkSummaryRefreshContext);
	const refreshRoot = useContext(SalesSdkRootRefreshContext);
	const [snapshot, setSnapshot] = useState(EMPTY_SNAPSHOT);
	useEffect(() => {
		setSnapshot(readSnapshot(bookingTicket));
	}, [bookingTicket]);
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
			setSnapshot(readSnapshot(bookingTicket));
		});
		return () => {
			try {
				off();
			} catch (_unused) {}
		};
	}, [bookingTicket]);
	const syncSummary = useMemoizedFn(_asyncToGenerator(function* () {
		if (!refreshSummary) return null;
		try {
			return yield refreshSummary();
		} catch (e) {
			console.warn("[SalesSdk] CartProvider 同步 summary 失败", e);
			return null;
		}
	}));
	/**
	* 统一收口：cart action 写完 OS 后，同时刷新 items 快照与顶层 tempOrder / salesDetail。
	* 顺序固定：先 items（本地 enrich 数据），再 root（顶层单一真源），避免下游同一渲染里
	* 看到 items 已更新但 tempOrder 还是旧值。
	*/
	const refreshAfterMutation = useMemoizedFn(() => {
		setSnapshot(readSnapshot(bookingTicket));
		refreshRoot === null || refreshRoot === void 0 || refreshRoot();
	});
	const addProduct = useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (input) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const result = yield bookingTicket.addProductToOrder(input);
			refreshAfterMutation();
			yield syncSummary();
			return result;
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	const removeItem = useMemoizedFn(function() {
		var _ref2 = _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(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	const updateItem = useMemoizedFn(function() {
		var _ref3 = _asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const result = yield bookingTicket.updateProductInOrder(params);
			refreshAfterMutation();
			yield syncSummary();
			return result;
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}());
	const setLineNote = useMemoizedFn(function() {
		var _ref4 = _asyncToGenerator(function* (identity, note) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			const result = yield bookingTicket.setOrderProductLineNote(identity, note);
			refreshAfterMutation();
			return result;
		});
		return function(_x4, _x5) {
			return _ref4.apply(this, arguments);
		};
	}());
	const setDiscount = useMemoizedFn(function() {
		var _ref5 = _asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
			yield bookingTicket.setDiscountSelected(params);
			refreshAfterMutation();
			yield syncSummary();
		});
		return function(_x6) {
			return _ref5.apply(this, arguments);
		};
	}());
	const scanCode = useMemoizedFn(function() {
		var _ref6 = _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(_x7, _x8) {
			return _ref6.apply(this, arguments);
		};
	}());
	const submit = useMemoizedFn(_asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] Cart: bookingTicket 未初始化");
		return bookingTicket.submitScanOrder();
	}));
	const recalcSummary = useMemoizedFn(_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 = useMemo(() => ({
		discountList: snapshot.discountList,
		bookings: snapshot.bookings,
		items: snapshot.items,
		addProduct,
		removeItem,
		updateItem,
		setLineNote,
		setDiscount,
		scanCode,
		submit,
		recalcSummary
	}), [
		snapshot,
		addProduct,
		removeItem,
		updateItem,
		setLineNote,
		setDiscount,
		scanCode,
		submit,
		recalcSummary
	]);
	return /* @__PURE__ */ React.createElement(SalesSdkCartContext.Provider, { value }, children);
};
//#endregion
export { SalesSdkCartContext, SalesSdkCartProvider };
