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 { getProductDetail } from "../info/service/serve.js";
import { getHandleAddService } from "../../ticketBooking/components/addServiceVariant/utils.js";
import { _objectWithoutProperties } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import { formatDiscountLists } from "../../shoppingCart/utils.js";
import { getProductTotalPrice } from "../utils.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import useCartChangeEffect from "../../ticketBooking/hooks/pisellos/useCartChangeEffect.js";
import { cloneDeep } from "lodash";
import { useMemoizedFn } from "ahooks";
//#region src/components/booking/hooks/usePromotion.ts
const _excluded = ["_promotionTags"];
/**
* 生成唯一的数字ID（用于 PromotionProduct.id）
*/
const generateNumericId = () => {
	return Math.floor(Math.random() * 1e9) + Date.now();
};
/**
* 生成唯一的字符串ID（用于拆分商品的 _id）
*/
const generateStringId = () => {
	return `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};
/**
* 获取商品的主价格（考虑变体）
*/
const getMainOriginalPrice = (item) => {
	var _item$_extend, _item$variant;
	let price = item === null || item === void 0 ? void 0 : item.price;
	if (((_item$_extend = item._extend) === null || _item$_extend === void 0 || (_item$_extend = _item$_extend.other) === null || _item$_extend === void 0 ? void 0 : _item$_extend.product_variant_id) > 0 && (item === null || item === void 0 || (_item$variant = item.variant) === null || _item$variant === void 0 ? void 0 : _item$variant.length) > 0) {
		const variant = item.variant.find((d) => {
			var _item$_extend2;
			return d.id === ((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 || (_item$_extend2 = _item$_extend2.other) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.product_variant_id);
		});
		if (variant) price = variant === null || variant === void 0 ? void 0 : variant.price;
	}
	return typeof price === "string" ? parseFloat(price) : price;
};
/**
* 将原商品转换为 PromotionProduct 格式
* 
* 注意：price 使用 getMainOriginalPrice 获取原始价格
* 这样即使商品价格被促销修改过，每次计算时都会用原始价格重新计算
* 
* @param item - 原商品
* @param index - 原始列表中的索引，用于保持顺序
*/
const convertToPromotionProduct = (item, index) => {
	var _ref, _other$product_id, _other$product_varian, _extend$quantity;
	const extend = item._extend || {};
	const other = extend.other || {};
	return {
		id: generateNumericId(),
		product_id: (_ref = (_other$product_id = other.product_id) !== null && _other$product_id !== void 0 ? _other$product_id : item.product_id) !== null && _ref !== void 0 ? _ref : item.id,
		product_variant_id: (_other$product_varian = other.product_variant_id) !== null && _other$product_varian !== void 0 ? _other$product_varian : 0,
		name: item.title || extend.product_name,
		price: getMainOriginalPrice(item),
		quantity: (_extend$quantity = extend.quantity) !== null && _extend$quantity !== void 0 ? _extend$quantity : 1,
		bundle: [],
		_originalItem: item,
		_originalId: item._id,
		_originalIndex: index
	};
};
/**
* 更新商品的 discount_list 字段
* 
* - 添加促销优惠时：保留已有数据，追加新的 promotion 项
* - 清除促销优惠时：只移除 type === "promotion" 的项，保留其他类型
* 
* @param item - 商品对象
* @param promotionDiscount - 促销优惠信息，为 null 时表示清除促销优惠
*/
const updateDiscountList = (item, promotionDiscount) => {
	let discountList = Array.isArray(item.discount_list) ? [...item.discount_list] : [];
	discountList = discountList.filter((d) => d.type !== "promotion");
	if (promotionDiscount) discountList.push({
		type: "promotion",
		amount: promotionDiscount.amount,
		discount: {
			original_amount: promotionDiscount.original_amount,
			fixed_amount: promotionDiscount.fixed_amount,
			title: promotionDiscount.title,
			resource_id: ""
		}
	});
	if (discountList.length > 0) item.discount_list = discountList;
	else delete item.discount_list;
};
/**
* 将 PricedProduct 映射回原商品格式
*
* @param pricedProduct - evaluator 返回的带定价商品
* @param originalItemMap - 原商品映射表（numericId -> { item, index }）
* @returns 更新后的商品（原格式），包含 _sortIndex 用于排序
*/
const mapPricedProductToOriginal = (pricedProduct, originalItemMap) => {
	var _pricedProduct$origin, _extend$_promotion, _extend$other;
	const sourceId = (_pricedProduct$origin = pricedProduct.originalId) !== null && _pricedProduct$origin !== void 0 ? _pricedProduct$origin : pricedProduct.id;
	const originalData = originalItemMap.get(sourceId);
	if (!originalData) {
		console.warn("Cannot find original item for pricedProduct:", pricedProduct);
		return null;
	}
	const { item: originalItem, index: originalIndex } = originalData;
	const newItem = cloneDeep(originalItem);
	const extend = newItem._extend || {};
	const wasInPromotion = ((_extend$_promotion = extend._promotion) === null || _extend$_promotion === void 0 ? void 0 : _extend$_promotion.inPromotion) === true;
	delete extend._promotion;
	delete extend._promotionInfo;
	delete extend._giftInfo;
	if (((_extend$other = extend.other) === null || _extend$other === void 0 ? void 0 : _extend$other.bundle) && Array.isArray(extend.other.bundle)) for (const bundleItem of extend.other.bundle) delete bundleItem._promotion;
	const originalPrice = getMainOriginalPrice(originalItem);
	if (pricedProduct.inPromotion || wasInPromotion) {
		extend.main_product_selling_price = pricedProduct.finalPrice;
		extend.price = pricedProduct.finalPrice;
		extend.total = pricedProduct.inPromotion ? getProductTotalPrice(newItem, { isUseExtendPrice: true }) : extend.origin_total;
	}
	extend.quantity = pricedProduct.quantity;
	if (pricedProduct.isSplit) newItem._id = generateStringId();
	if (pricedProduct.strategyId) {
		var _extend$other2;
		const promotionInfo = {
			strategyId: pricedProduct.strategyId,
			strategyMetadata: pricedProduct === null || pricedProduct === void 0 ? void 0 : pricedProduct.strategyMetadata,
			inPromotion: pricedProduct.inPromotion,
			originalPrice: getMainOriginalPrice(originalItem),
			finalPrice: pricedProduct.finalPrice
		};
		if (pricedProduct.matchedBundleIndex !== void 0 && ((_extend$other2 = extend.other) === null || _extend$other2 === void 0 ? void 0 : _extend$other2.bundle) && extend.other.bundle[pricedProduct.matchedBundleIndex]) extend.other.bundle[pricedProduct.matchedBundleIndex]._promotion = promotionInfo;
		else extend._promotion = promotionInfo;
	}
	newItem._extend = extend;
	if (pricedProduct.inPromotion && pricedProduct.strategyId && originalPrice !== pricedProduct.finalPrice) {
		var _pricedProduct$strate;
		const discountAmount = originalPrice - pricedProduct.finalPrice;
		updateDiscountList(newItem, {
			title: ((_pricedProduct$strate = pricedProduct.strategyMetadata) === null || _pricedProduct$strate === void 0 ? void 0 : _pricedProduct$strate.name) || "",
			amount: discountAmount.toFixed(2),
			original_amount: originalPrice.toFixed(2),
			fixed_amount: discountAmount.toFixed(2)
		});
	} else updateDiscountList(newItem, null);
	newItem._matchedBundleIndex = pricedProduct.matchedBundleIndex;
	newItem._originalProductId = originalItem._id;
	newItem._sortIndex = originalIndex;
	newItem._sortSubIndex = pricedProduct.inPromotion ? 0 : 1;
	return newItem;
};
/**
* 计算赠品操作（需要添加/减少/删除的赠品）
*
* @param gifts - 扩展的赠品信息（包含 sourceProductIds）
* @param existingGifts - 购物车中已存在的赠品
* @returns 赠品操作
*/
const calculateGiftActions = (gifts, existingGifts) => {
	const toAdd = [];
	const toReduce = [];
	const toRemove = [];
	const existingGiftMap = /* @__PURE__ */ new Map();
	for (const gift of existingGifts) {
		var _gift$_giftInfo;
		const strategyId = (_gift$_giftInfo = gift._giftInfo) === null || _gift$_giftInfo === void 0 ? void 0 : _gift$_giftInfo.strategyId;
		if (!strategyId) continue;
		const existing = existingGiftMap.get(strategyId);
		if (existing) {
			var _gift$_extend$quantit, _gift$_extend;
			existing.items.push(gift);
			existing.totalQuantity += (_gift$_extend$quantit = (_gift$_extend = gift._extend) === null || _gift$_extend === void 0 ? void 0 : _gift$_extend.quantity) !== null && _gift$_extend$quantit !== void 0 ? _gift$_extend$quantit : 1;
		} else {
			var _gift$_extend$quantit2, _gift$_extend2;
			existingGiftMap.set(strategyId, {
				items: [gift],
				totalQuantity: (_gift$_extend$quantit2 = (_gift$_extend2 = gift._extend) === null || _gift$_extend2 === void 0 ? void 0 : _gift$_extend2.quantity) !== null && _gift$_extend$quantit2 !== void 0 ? _gift$_extend$quantit2 : 1
			});
		}
	}
	const processedStrategyIds = /* @__PURE__ */ new Set();
	for (const giftInfo of gifts) {
		var _existing$totalQuanti;
		const { strategyId, strategyName, giftCount, giftOptions, sourceProductIds } = giftInfo;
		processedStrategyIds.add(strategyId);
		const existing = existingGiftMap.get(strategyId);
		const diff = giftCount - ((_existing$totalQuanti = existing === null || existing === void 0 ? void 0 : existing.totalQuantity) !== null && _existing$totalQuanti !== void 0 ? _existing$totalQuanti : 0);
		if (diff > 0) {
			var _existing$items;
			const lastEvaluatedGiftCount = existing === null || existing === void 0 || (_existing$items = existing.items) === null || _existing$items === void 0 || (_existing$items = _existing$items[0]) === null || _existing$items === void 0 || (_existing$items = _existing$items._giftInfo) === null || _existing$items === void 0 ? void 0 : _existing$items.lastEvaluatedGiftCount;
			if (lastEvaluatedGiftCount === void 0 || giftCount !== lastEvaluatedGiftCount) toAdd.push({
				strategyId,
				strategyName,
				giftCount: diff,
				giftOptions,
				sourceProductIds
			});
		} else if (diff < 0) {
			const reduceCount = Math.abs(diff);
			const reduceItems = [];
			const removeIds = [];
			if (existing === null || existing === void 0 ? void 0 : existing.items) {
				let remainingReduce = reduceCount;
				const reversedItems = [...existing.items].reverse();
				for (const giftItem of reversedItems) {
					var _giftItem$_extend$qua, _giftItem$_extend;
					if (remainingReduce <= 0) break;
					const itemId = giftItem._id;
					const itemQuantity = (_giftItem$_extend$qua = (_giftItem$_extend = giftItem._extend) === null || _giftItem$_extend === void 0 ? void 0 : _giftItem$_extend.quantity) !== null && _giftItem$_extend$qua !== void 0 ? _giftItem$_extend$qua : 1;
					if (itemQuantity <= remainingReduce) {
						removeIds.push(itemId);
						remainingReduce -= itemQuantity;
					} else {
						reduceItems.push({
							_id: itemId,
							currentQuantity: itemQuantity,
							newQuantity: itemQuantity - remainingReduce
						});
						remainingReduce = 0;
					}
				}
			}
			if (reduceItems.length > 0) toReduce.push({
				strategyId,
				items: reduceItems
			});
			toRemove.push(...removeIds);
		}
	}
	for (const [strategyId, existing] of existingGiftMap) if (!processedStrategyIds.has(strategyId)) for (const giftItem of existing.items) toRemove.push(giftItem._id);
	return {
		toAdd,
		toReduce,
		toRemove
	};
};
/**
* 计算未满足促销条件的信息
*
* @param processedProducts - 处理后的商品列表
* @param applicableStrategiesResult - 每个商品的适用策略结果
* @param mainProducts - 原始主商品列表
* @returns 未满足促销条件的信息数组
*/
const calculateUnfulfilledPromotions = (processedProducts, applicableStrategiesResult, mainProducts) => {
	const unfulfilledMap = /* @__PURE__ */ new Map();
	for (let i = 0; i < processedProducts.length; i++) {
		var _product$_extend, _product$_extend$quan, _product$_extend2;
		const product = processedProducts[i];
		const promotion = (_product$_extend = product._extend) === null || _product$_extend === void 0 ? void 0 : _product$_extend._promotion;
		if (!promotion || promotion.inPromotion !== false) continue;
		const strategyId = promotion.strategyId;
		if (!strategyId) continue;
		const lookupId = product._originalProductId || product._id;
		const originalIndex = mainProducts.findIndex((item) => item._id === lookupId);
		if (originalIndex === -1) continue;
		const strategyData = applicableStrategiesResult[originalIndex];
		if (!strategyData || !strategyData.hasApplicableStrategy) continue;
		const matchedStrategy = strategyData.applicableStrategies.find((s) => s.strategyId === strategyId);
		if (!matchedStrategy) continue;
		const quantity = (_product$_extend$quan = (_product$_extend2 = product._extend) === null || _product$_extend2 === void 0 ? void 0 : _product$_extend2.quantity) !== null && _product$_extend$quan !== void 0 ? _product$_extend$quan : 1;
		if (unfulfilledMap.has(strategyId)) {
			const existing = unfulfilledMap.get(strategyId);
			existing.currentQuantity += quantity;
		} else unfulfilledMap.set(strategyId, {
			strategyId,
			strategyName: matchedStrategy.strategyName,
			actionType: matchedStrategy.actionType,
			requiredQuantity: matchedStrategy.requiredQuantity,
			currentQuantity: quantity,
			eligibleProducts: matchedStrategy.eligibleProducts,
			strategyMetadata: matchedStrategy.strategyMetadata,
			display: matchedStrategy.display
		});
	}
	const result = [];
	for (const data of unfulfilledMap.values()) {
		const needQuantity = data.requiredQuantity - data.currentQuantity;
		if (needQuantity > 0) result.push({
			strategyId: data.strategyId,
			strategyName: data.strategyName,
			actionType: data.actionType,
			needQuantity,
			currentQuantity: data.currentQuantity,
			requiredQuantity: data.requiredQuantity,
			eligibleProducts: data.eligibleProducts,
			strategyMetadata: data.strategyMetadata,
			display: data.display
		});
	}
	return result;
};
/**
* 处理购物车商品的促销计算
*
* @param list - 原商品列表（包含主商品和赠品）
* @param promotionEvaluator - 促销评估器实例
* @returns 处理后的商品列表和优惠信息
*/
const processCartPromotion = (list, promotionEvaluator) => {
	const emptyResult = {
		products: list || [],
		totalDiscount: 0,
		gifts: [],
		giftActions: {
			toAdd: [],
			toReduce: [],
			toRemove: []
		},
		unfulfilledPromotions: []
	};
	if (!list || list.length === 0 || !promotionEvaluator) return emptyResult;
	const mainProductsWithIndex = [];
	const existingGiftsWithIndex = [];
	const editProductsWithIndex = [];
	for (let i = 0; i < list.length; i++) {
		const item = list[i];
		if (item._giftInfo) existingGiftsWithIndex.push({
			item,
			originalListIndex: i
		});
		else if (item.booking_id && item.booking_id !== 0 && item.booking_id !== "0") editProductsWithIndex.push({
			item,
			originalListIndex: i
		});
		else mainProductsWithIndex.push({
			item,
			originalListIndex: i
		});
	}
	const mainProducts = mainProductsWithIndex.map((x) => x.item);
	const existingGifts = existingGiftsWithIndex.map((x) => x.item);
	if (mainProducts.length === 0) {
		const editProducts = editProductsWithIndex.map((x) => x.item);
		if (existingGifts.length > 0) {
			const toRemove = [];
			for (const gift of existingGifts) if (gift._id) toRemove.push(gift._id);
			return {
				products: editProducts,
				totalDiscount: 0,
				gifts: [],
				giftActions: {
					toAdd: [],
					toReduce: [],
					toRemove
				},
				unfulfilledPromotions: []
			};
		}
		return _objectSpread2(_objectSpread2({}, emptyResult), {}, { products: editProducts.length > 0 ? editProducts : list || [] });
	}
	const promotionProducts = [];
	const originalItemMap = /* @__PURE__ */ new Map();
	const productsForStrategies = [];
	for (let i = 0; i < mainProductsWithIndex.length; i++) {
		var _ref2, _other$product_id2, _other$product_varian2, _extend$quantity2;
		const { item, originalListIndex } = mainProductsWithIndex[i];
		const promotionProduct = convertToPromotionProduct(item, originalListIndex);
		promotionProducts.push(promotionProduct);
		originalItemMap.set(promotionProduct.id, {
			item,
			index: originalListIndex
		});
		const extend = item._extend || {};
		const other = extend.other || {};
		productsForStrategies.push({
			id: i,
			product_id: (_ref2 = (_other$product_id2 = other.product_id) !== null && _other$product_id2 !== void 0 ? _other$product_id2 : item.product_id) !== null && _ref2 !== void 0 ? _ref2 : item.id,
			product_variant_id: (_other$product_varian2 = other.product_variant_id) !== null && _other$product_varian2 !== void 0 ? _other$product_varian2 : 0,
			name: item.title || extend.product_name,
			price: getMainOriginalPrice(item),
			quantity: (_extend$quantity2 = extend.quantity) !== null && _extend$quantity2 !== void 0 ? _extend$quantity2 : 1,
			bundle: []
		});
	}
	const applicableStrategiesResult = promotionEvaluator.getProductsApplicableStrategies({ products: productsForStrategies });
	const result = promotionEvaluator.evaluateCartWithPricing({ products: promotionProducts });
	console.log("result123", result);
	const strategySourceProductIds = /* @__PURE__ */ new Map();
	for (const pricedProduct of result.products) if (pricedProduct.inPromotion && pricedProduct.strategyId) {
		var _pricedProduct$origin2;
		const strategyId = pricedProduct.strategyId;
		const sourceId = (_pricedProduct$origin2 = pricedProduct.originalId) !== null && _pricedProduct$origin2 !== void 0 ? _pricedProduct$origin2 : pricedProduct.id;
		const originalData = originalItemMap.get(sourceId);
		if (originalData) {
			const productId = originalData.item._id;
			const ids = strategySourceProductIds.get(strategyId) || [];
			if (!ids.includes(productId)) ids.push(productId);
			strategySourceProductIds.set(strategyId, ids);
		}
	}
	const extendedGifts = result.gifts.map((gift) => _objectSpread2(_objectSpread2({}, gift), {}, { sourceProductIds: strategySourceProductIds.get(gift.strategyId) || [] }));
	const processedProducts = [];
	const strategyGiftInfoMap = /* @__PURE__ */ new Map();
	for (const gift of extendedGifts) strategyGiftInfoMap.set(gift.strategyId, gift);
	const strategyGiftInfoOwner = /* @__PURE__ */ new Map();
	for (const pricedProduct of result.products) {
		const mappedItem = mapPricedProductToOriginal(pricedProduct, originalItemMap);
		if (mappedItem) {
			if (pricedProduct.inPromotion && pricedProduct.strategyId) {
				const strategyId = pricedProduct.strategyId;
				const giftInfo = strategyGiftInfoMap.get(strategyId);
				if (giftInfo && giftInfo.giftOptions && giftInfo.giftOptions.length > 0 && !strategyGiftInfoOwner.has(strategyId)) {
					var _mappedItem$_extend, _mappedItem$_extend2;
					const giftInfoData = {
						strategyName: giftInfo.strategyName,
						giftCount: giftInfo.giftCount,
						giftOptions: giftInfo.giftOptions
					};
					const matchedBundleIndex = mappedItem._matchedBundleIndex;
					if (matchedBundleIndex !== void 0 && ((_mappedItem$_extend = mappedItem._extend) === null || _mappedItem$_extend === void 0 || (_mappedItem$_extend = _mappedItem$_extend.other) === null || _mappedItem$_extend === void 0 || (_mappedItem$_extend = _mappedItem$_extend.bundle) === null || _mappedItem$_extend === void 0 || (_mappedItem$_extend = _mappedItem$_extend[matchedBundleIndex]) === null || _mappedItem$_extend === void 0 ? void 0 : _mappedItem$_extend._promotion)) mappedItem._extend.other.bundle[matchedBundleIndex]._promotion.giftInfo = giftInfoData;
					else if ((_mappedItem$_extend2 = mappedItem._extend) === null || _mappedItem$_extend2 === void 0 ? void 0 : _mappedItem$_extend2._promotion) mappedItem._extend._promotion.giftInfo = giftInfoData;
					strategyGiftInfoOwner.set(strategyId, mappedItem._id);
				}
			}
			processedProducts.push(mappedItem);
		}
	}
	for (const { item, originalListIndex } of existingGiftsWithIndex) {
		var _item$_giftInfo;
		item._sortIndex = originalListIndex;
		item._sortSubIndex = 0;
		const strategyId = (_item$_giftInfo = item._giftInfo) === null || _item$_giftInfo === void 0 ? void 0 : _item$_giftInfo.strategyId;
		if (strategyId) {
			const latestGiftInfo = strategyGiftInfoMap.get(strategyId);
			const ownerId = strategyGiftInfoOwner.get(strategyId);
			if (latestGiftInfo) {
				var _item$_extend3;
				item._giftInfo.sourceProductIds = latestGiftInfo.sourceProductIds;
				if ((_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3._giftInfo) item._extend._giftInfo.sourceProductIds = latestGiftInfo.sourceProductIds;
			}
			if (ownerId) {
				var _item$_extend4;
				item._giftInfo.sourceProductId = ownerId;
				if ((_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4._giftInfo) item._extend._giftInfo.sourceProductId = ownerId;
			}
		}
		processedProducts.push(item);
	}
	for (const { item, originalListIndex } of editProductsWithIndex) {
		item._sortIndex = originalListIndex;
		item._sortSubIndex = 0;
		processedProducts.push(item);
	}
	processedProducts.sort((a, b) => {
		if (a._sortIndex !== b._sortIndex) return a._sortIndex - b._sortIndex;
		return a._sortSubIndex - b._sortSubIndex;
	});
	for (const product of processedProducts) {
		delete product._sortIndex;
		delete product._sortSubIndex;
		delete product._matchedBundleIndex;
	}
	for (let i = 0; i < processedProducts.length; i++) {
		const product = processedProducts[i];
		const extend = product._extend || {};
		if (extend._promotion) continue;
		const lookupId = product._originalProductId || product._id;
		const originalIndex = mainProducts.findIndex((item) => item._id === lookupId);
		if (originalIndex === -1) continue;
		const strategyData = applicableStrategiesResult[originalIndex];
		if (!strategyData || !strategyData.hasApplicableStrategy) continue;
		const firstStrategy = strategyData.applicableStrategies[0];
		if (firstStrategy) {
			const originalPrice = getMainOriginalPrice(mainProducts[originalIndex]);
			extend._promotion = {
				strategyId: firstStrategy.strategyId,
				strategyMetadata: firstStrategy.strategyMetadata,
				inPromotion: false,
				originalPrice,
				finalPrice: originalPrice
			};
			product._extend = extend;
		}
	}
	const giftActions = calculateGiftActions(extendedGifts, existingGifts);
	for (const gift of existingGifts) {
		var _gift$_giftInfo2;
		const strategyId = (_gift$_giftInfo2 = gift._giftInfo) === null || _gift$_giftInfo2 === void 0 ? void 0 : _gift$_giftInfo2.strategyId;
		if (strategyId) {
			const latestGiftInfo = strategyGiftInfoMap.get(strategyId);
			if (latestGiftInfo) {
				var _gift$_extend3;
				gift._giftInfo.lastEvaluatedGiftCount = latestGiftInfo.giftCount;
				if ((_gift$_extend3 = gift._extend) === null || _gift$_extend3 === void 0 ? void 0 : _gift$_extend3._giftInfo) gift._extend._giftInfo.lastEvaluatedGiftCount = latestGiftInfo.giftCount;
			}
		}
	}
	const unfulfilledPromotions = calculateUnfulfilledPromotions(processedProducts, applicableStrategiesResult, mainProducts);
	for (const product of processedProducts) delete product._originalProductId;
	return {
		products: processedProducts,
		totalDiscount: result.totalDiscount,
		gifts: extendedGifts,
		giftActions,
		unfulfilledPromotions
	};
};
const usePromotion = (state, dispatch, options) => {
	var _engineContext$appHel;
	const { onCartChange, effectOn } = useCartChangeEffect();
	const engineContext = useEngineContext();
	const promotionEvaluator = engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 || (_engineContext$appHel = _engineContext$appHel.utils) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.promotionEvaluator;
	const { onGiftSelection } = options || {};
	/**
	* 检查并处理自动添加赠品
	* @param gift - 赠品选项
	* @param giftData - 赠品相关数据
	* @returns Promise<格式化后的赠品商品对象 | null>
	*/
	const handleAutoAddGift = useMemoizedFn(function() {
		var _ref3 = _asyncToGenerator(function* (gift, giftData) {
			if (gift === null || gift === void 0 ? void 0 : gift.product_variant_id) return null;
			if (!gift.product_id) return null;
			try {
				const { data } = yield getProductDetail(gift.product_id.toString(), { is_eject: 1 });
				if (!data) return null;
				if (data.is_eject === 0) return new Promise((resolve) => {
					var _getHandleAddService;
					(_getHandleAddService = getHandleAddService()) === null || _getHandleAddService === void 0 || _getHandleAddService(data, (cacheItem) => {
						var _giftData$sourceProdu, _cacheItem$_extend;
						const _giftData = _objectSpread2(_objectSpread2({}, giftData || {}), {}, {
							sourceProductId: giftData === null || giftData === void 0 || (_giftData$sourceProdu = giftData.sourceProductIds) === null || _giftData$sourceProdu === void 0 ? void 0 : _giftData$sourceProdu[0],
							lastEvaluatedGiftCount: (giftData === null || giftData === void 0 ? void 0 : giftData.giftCount) || 1
						});
						const priceParams = {
							price: 0,
							total: 0,
							origin_total: (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.price) || (cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.price) || 0,
							_initPrice: (cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.price) || 0
						};
						let product = _objectSpread2(_objectSpread2(_objectSpread2({}, cacheItem), priceParams), {}, {
							_giftInfo: _giftData,
							_extend: _objectSpread2(_objectSpread2(_objectSpread2({}, cacheItem._extend || {}), {}, { _giftInfo: _giftData }, priceParams), {}, { quantity: (giftData === null || giftData === void 0 ? void 0 : giftData.giftCount) || 1 })
						});
						product.discount_list = formatDiscountLists(product, giftData === null || giftData === void 0 ? void 0 : giftData.strategyName);
						resolve(product);
					});
				});
				else return null;
			} catch (error) {
				return null;
			}
		});
		return function(_x, _x2) {
			return _ref3.apply(this, arguments);
		};
	}());
	/**
	* 处理赠品操作
	* 
	* @param giftActions - 赠品操作
	* @param products - 当前商品列表
	* @returns 处理后的商品列表
	*/
	const handleGiftActions = useMemoizedFn(function() {
		var _ref4 = _asyncToGenerator(function* (giftActions, products) {
			const { toAdd, toReduce, toRemove } = giftActions;
			let newProducts = [...products];
			for (const addAction of toAdd) {
				const { strategyId, strategyName, giftCount, giftOptions, sourceProductIds } = addAction;
				if (giftOptions.length === 1) {
					console.log("[usePromotion] Auto-select single gift:", {
						strategyId,
						giftOptions,
						giftCount,
						sourceProductIds
					});
					onGiftSelection === null || onGiftSelection === void 0 || onGiftSelection({
						strategyId,
						strategyName,
						giftOptions,
						giftCount,
						sourceProductIds
					});
					const sameStrategyGift = (newProducts || []).find((p) => {
						var _p$_giftInfo;
						return (p === null || p === void 0 || (_p$_giftInfo = p._giftInfo) === null || _p$_giftInfo === void 0 ? void 0 : _p$_giftInfo.strategyId) === strategyId;
					});
					if (!sameStrategyGift) {
						const product = yield handleAutoAddGift(giftOptions[0], addAction);
						if (product) newProducts.push(product);
					} else {
						var _sameStrategyGift$_ex;
						const remainingCount = Number(giftCount || 0);
						sameStrategyGift._extend.quantity += remainingCount;
						if (sameStrategyGift === null || sameStrategyGift === void 0 || (_sameStrategyGift$_ex = sameStrategyGift._extend) === null || _sameStrategyGift$_ex === void 0 || (_sameStrategyGift$_ex = _sameStrategyGift$_ex.other) === null || _sameStrategyGift$_ex === void 0 ? void 0 : _sameStrategyGift$_ex.quantity) sameStrategyGift._extend.other.quantity += remainingCount;
					}
				} else if (giftOptions.length > 1) {
					console.log("[usePromotion] Need user selection for gifts:", {
						strategyId,
						giftOptions,
						giftCount,
						sourceProductIds
					});
					onGiftSelection === null || onGiftSelection === void 0 || onGiftSelection({
						strategyId,
						strategyName,
						giftOptions,
						giftCount,
						sourceProductIds
					});
				}
			}
			if (toReduce.length > 0) {
				console.log("[usePromotion] Gifts to reduce:", toReduce);
				for (const reduceAction of toReduce) for (const item of reduceAction.items) {
					const giftIndex = newProducts.findIndex((p) => p._id === item._id);
					if (giftIndex !== -1) {
						const gift = newProducts[giftIndex];
						if (gift._extend) {
							gift._extend.quantity = item.newQuantity;
							if (gift._extend.price !== void 0) gift._extend.total = gift._extend.price * item.newQuantity;
						}
						console.log("[usePromotion] Reduced gift quantity:", {
							_id: item._id,
							from: item.currentQuantity,
							to: item.newQuantity
						});
					}
				}
			}
			if (toRemove.length > 0) {
				console.log("[usePromotion] Gifts to remove:", toRemove);
				newProducts = newProducts.filter((p) => !toRemove.includes(p._id));
			}
			return newProducts;
		});
		return function(_x3, _x4) {
			return _ref4.apply(this, arguments);
		};
	}());
	/**
	* 购物车变更时的回调处理
	*/
	const onCartChangeEffect = useMemoizedFn(function() {
		var _ref5 = _asyncToGenerator(function* ({ type, list }) {
			console.log("[usePromotion] onCartChange", type, list);
			if (!promotionEvaluator) {
				console.warn("[usePromotion] promotionEvaluator not available");
				return;
			}
			console.log(list, "list444");
			const { products, totalDiscount, gifts, giftActions, unfulfilledPromotions } = processCartPromotion(list, promotionEvaluator);
			console.log("[usePromotion] processed result:", {
				products,
				totalDiscount,
				gifts,
				giftActions,
				unfulfilledPromotions
			});
			const finalProducts = yield handleGiftActions(giftActions, products);
			setTimeout(() => {
				dispatch({
					type: "setService",
					payload: {
						value: finalProducts,
						unfulfilledPromotions,
						edit: true
					}
				});
			}, 100);
		});
		return function(_x5) {
			return _ref5.apply(this, arguments);
		};
	}());
	return {
		run: useMemoizedFn(() => {
			return effectOn(onCartChangeEffect);
		}),
		formatProductList: useMemoizedFn((list) => {
			if (!list || list.length === 0 || !promotionEvaluator) return list || [];
			const promotionProducts = list.map((item, index) => {
				var _ref6, _other$product_id3, _other$product_varian3, _extend$quantity3;
				const extend = item._extend || {};
				const other = extend.other || {};
				return {
					id: index,
					product_id: (_ref6 = (_other$product_id3 = other.product_id) !== null && _other$product_id3 !== void 0 ? _other$product_id3 : item.product_id) !== null && _ref6 !== void 0 ? _ref6 : item.id,
					product_variant_id: (_other$product_varian3 = other.product_variant_id) !== null && _other$product_varian3 !== void 0 ? _other$product_varian3 : 0,
					name: item.title || extend.product_name,
					price: getMainOriginalPrice(item),
					quantity: (_extend$quantity3 = extend.quantity) !== null && _extend$quantity3 !== void 0 ? _extend$quantity3 : 1,
					bundle: []
				};
			});
			const strategiesResult = promotionEvaluator.getProductsApplicableStrategies({ products: promotionProducts }, false);
			const newList = list.map((item, index) => {
				const strategyData = strategiesResult[index];
				if (!strategyData || !strategyData.hasApplicableStrategy) {
					const { _promotionTags } = item;
					return _objectWithoutProperties(item, _excluded);
				}
				const promotionTags = strategyData.applicableStrategies.map((strategy) => strategy.display);
				return _objectSpread2(_objectSpread2({}, item), {}, { _promotionTags: promotionTags });
			});
			console.log(newList, "newList444");
			return newList;
		}),
		processPromotion: useMemoizedFn((list) => {
			if (!promotionEvaluator) {
				console.warn("[usePromotion] promotionEvaluator not available");
				return {
					products: list || [],
					totalDiscount: 0,
					gifts: [],
					giftActions: {
						toAdd: [],
						toReduce: [],
						toRemove: []
					},
					unfulfilledPromotions: []
				};
			}
			return processCartPromotion(list, promotionEvaluator);
		})
	};
};
//#endregion
export { usePromotion as default };
