var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/booking/hooks/usePromotion.ts
var usePromotion_exports = {};
__export(usePromotion_exports, {
  default: () => usePromotion_default
});
module.exports = __toCommonJS(usePromotion_exports);
var import_ahooks = require("ahooks");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_useCartChangeEffect = __toESM(require("../../ticketBooking/hooks/pisellos/useCartChangeEffect"));
var import_serve = require("../../booking/info/service/serve");
var import_utils = require("../../ticketBooking/components/addServiceVariant/utils");
var import_utils2 = require("../../shoppingCart/utils");
var import_lodash = require("lodash");
var import_utils3 = require("../utils");
var generateNumericId = () => {
  return Math.floor(Math.random() * 1e9) + Date.now();
};
var generateStringId = () => {
  return `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};
var getMainOriginalPrice = (item) => {
  var _a, _b, _c;
  let price = item == null ? void 0 : item.price;
  if (((_b = (_a = item._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.product_variant_id) > 0 && ((_c = item == null ? void 0 : item.variant) == null ? void 0 : _c.length) > 0) {
    const variant = item.variant.find(
      (d) => {
        var _a2, _b2;
        return d.id === ((_b2 = (_a2 = item._extend) == null ? void 0 : _a2.other) == null ? void 0 : _b2.product_variant_id);
      }
    );
    if (variant) {
      price = variant == null ? void 0 : variant.price;
    }
  }
  return typeof price === "string" ? parseFloat(price) : price;
};
var convertToPromotionProduct = (item, index) => {
  const extend = item._extend || {};
  const other = extend.other || {};
  const numericId = generateNumericId();
  return {
    id: numericId,
    product_id: other.product_id ?? item.product_id ?? item.id,
    product_variant_id: other.product_variant_id ?? 0,
    name: item.title || extend.product_name,
    // 使用原始价格，确保每次计算都基于原价，而不是被促销修改过的价格
    price: getMainOriginalPrice(item),
    quantity: extend.quantity ?? 1,
    bundle: [],
    // 保存原商品引用和原 _id，用于后续映射
    _originalItem: item,
    _originalId: item._id,
    // 保存原始索引，用于后续排序
    _originalIndex: index
  };
};
var 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;
  }
};
var mapPricedProductToOriginal = (pricedProduct, originalItemMap) => {
  var _a, _b, _c, _d;
  const sourceId = pricedProduct.originalId ?? 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 = (0, import_lodash.cloneDeep)(originalItem);
  const extend = newItem._extend || {};
  const wasInPromotion = ((_a = extend._promotion) == null ? void 0 : _a.inPromotion) === true;
  delete extend._promotion;
  delete extend._promotionInfo;
  delete extend._giftInfo;
  if (((_b = extend.other) == null ? void 0 : _b.bundle) && Array.isArray(extend.other.bundle)) {
    for (const bundleItem of extend.other.bundle) {
      delete bundleItem._promotion;
    }
  }
  const originalPrice = getMainOriginalPrice(originalItem);
  const shouldModifyPrice = pricedProduct.inPromotion || wasInPromotion;
  if (shouldModifyPrice) {
    extend.main_product_selling_price = pricedProduct.finalPrice;
    extend.price = pricedProduct.finalPrice;
    extend.total = pricedProduct.inPromotion ? (0, import_utils3.getProductTotalPrice)(newItem, {
      isUseExtendPrice: true
    }) : extend.origin_total;
  }
  extend.quantity = pricedProduct.quantity;
  if (pricedProduct.isSplit) {
    newItem._id = generateStringId();
  }
  if (pricedProduct.strategyId) {
    const promotionInfo = {
      strategyId: pricedProduct.strategyId,
      strategyMetadata: pricedProduct == null ? void 0 : pricedProduct.strategyMetadata,
      inPromotion: pricedProduct.inPromotion,
      originalPrice: getMainOriginalPrice(originalItem),
      finalPrice: pricedProduct.finalPrice
      // giftInfo 会在后续逻辑中按需添加
    };
    if (pricedProduct.matchedBundleIndex !== void 0 && ((_c = extend.other) == null ? void 0 : _c.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) {
    const discountAmount = originalPrice - pricedProduct.finalPrice;
    updateDiscountList(newItem, {
      title: ((_d = pricedProduct.strategyMetadata) == null ? void 0 : _d.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;
};
var calculateGiftActions = (gifts, existingGifts) => {
  var _a, _b, _c, _d, _e, _f, _g;
  const toAdd = [];
  const toReduce = [];
  const toRemove = [];
  const existingGiftMap = /* @__PURE__ */ new Map();
  for (const gift of existingGifts) {
    const strategyId = (_a = gift._giftInfo) == null ? void 0 : _a.strategyId;
    if (!strategyId) continue;
    const existing = existingGiftMap.get(strategyId);
    if (existing) {
      existing.items.push(gift);
      existing.totalQuantity += ((_b = gift._extend) == null ? void 0 : _b.quantity) ?? 1;
    } else {
      existingGiftMap.set(strategyId, {
        items: [gift],
        totalQuantity: ((_c = gift._extend) == null ? void 0 : _c.quantity) ?? 1
      });
    }
  }
  const processedStrategyIds = /* @__PURE__ */ new Set();
  for (const giftInfo of gifts) {
    const { strategyId, strategyName, giftCount, giftOptions, sourceProductIds } = giftInfo;
    processedStrategyIds.add(strategyId);
    const existing = existingGiftMap.get(strategyId);
    const existingCount = (existing == null ? void 0 : existing.totalQuantity) ?? 0;
    const diff = giftCount - existingCount;
    if (diff > 0) {
      const lastEvaluatedGiftCount = (_f = (_e = (_d = existing == null ? void 0 : existing.items) == null ? void 0 : _d[0]) == null ? void 0 : _e._giftInfo) == null ? void 0 : _f.lastEvaluatedGiftCount;
      const isStrategyGiftCountChanged = lastEvaluatedGiftCount === void 0 || giftCount !== lastEvaluatedGiftCount;
      if (isStrategyGiftCountChanged) {
        toAdd.push({
          strategyId,
          strategyName,
          giftCount: diff,
          giftOptions,
          sourceProductIds
        });
      }
    } else if (diff < 0) {
      const reduceCount = Math.abs(diff);
      const reduceItems = [];
      const removeIds = [];
      if (existing == null ? void 0 : existing.items) {
        let remainingReduce = reduceCount;
        const reversedItems = [...existing.items].reverse();
        for (const giftItem of reversedItems) {
          if (remainingReduce <= 0) break;
          const itemId = giftItem._id;
          const itemQuantity = ((_g = giftItem._extend) == null ? void 0 : _g.quantity) ?? 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 };
};
var calculateUnfulfilledPromotions = (processedProducts, applicableStrategiesResult, mainProducts) => {
  var _a, _b;
  const unfulfilledMap = /* @__PURE__ */ new Map();
  for (let i = 0; i < processedProducts.length; i++) {
    const product = processedProducts[i];
    const promotion = (_a = product._extend) == null ? void 0 : _a._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 = ((_b = product._extend) == null ? void 0 : _b.quantity) ?? 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;
};
var processCartPromotion = (list, promotionEvaluator) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
  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 {
      ...emptyResult,
      products: editProducts.length > 0 ? editProducts : list || []
    };
  }
  const promotionProducts = [];
  const originalItemMap = /* @__PURE__ */ new Map();
  const productsForStrategies = [];
  for (let i = 0; i < mainProductsWithIndex.length; i++) {
    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,
      // 使用主商品数组索引作为 id，方便后续匹配 applicableStrategiesResult
      product_id: other.product_id ?? item.product_id ?? item.id,
      product_variant_id: other.product_variant_id ?? 0,
      name: item.title || extend.product_name,
      price: getMainOriginalPrice(item),
      quantity: extend.quantity ?? 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) {
      const strategyId = pricedProduct.strategyId;
      const sourceId = pricedProduct.originalId ?? 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) => ({
    ...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)) {
          const giftInfoData = {
            strategyName: giftInfo.strategyName,
            giftCount: giftInfo.giftCount,
            giftOptions: giftInfo.giftOptions
          };
          const matchedBundleIndex = mappedItem._matchedBundleIndex;
          if (matchedBundleIndex !== void 0 && ((_d = (_c = (_b = (_a = mappedItem._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.bundle) == null ? void 0 : _c[matchedBundleIndex]) == null ? void 0 : _d._promotion)) {
            mappedItem._extend.other.bundle[matchedBundleIndex]._promotion.giftInfo = giftInfoData;
          } else if ((_e = mappedItem._extend) == null ? void 0 : _e._promotion) {
            mappedItem._extend._promotion.giftInfo = giftInfoData;
          }
          strategyGiftInfoOwner.set(strategyId, mappedItem._id);
        }
      }
      processedProducts.push(mappedItem);
    }
  }
  for (const { item, originalListIndex } of existingGiftsWithIndex) {
    item._sortIndex = originalListIndex;
    item._sortSubIndex = 0;
    const strategyId = (_f = item._giftInfo) == null ? void 0 : _f.strategyId;
    if (strategyId) {
      const latestGiftInfo = strategyGiftInfoMap.get(strategyId);
      const ownerId = strategyGiftInfoOwner.get(strategyId);
      if (latestGiftInfo) {
        item._giftInfo.sourceProductIds = latestGiftInfo.sourceProductIds;
        if ((_g = item._extend) == null ? void 0 : _g._giftInfo) {
          item._extend._giftInfo.sourceProductIds = latestGiftInfo.sourceProductIds;
        }
      }
      if (ownerId) {
        item._giftInfo.sourceProductId = ownerId;
        if ((_h = item._extend) == null ? void 0 : _h._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) {
    const strategyId = (_i = gift._giftInfo) == null ? void 0 : _i.strategyId;
    if (strategyId) {
      const latestGiftInfo = strategyGiftInfoMap.get(strategyId);
      if (latestGiftInfo) {
        gift._giftInfo.lastEvaluatedGiftCount = latestGiftInfo.giftCount;
        if ((_j = gift._extend) == null ? void 0 : _j._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
  };
};
var usePromotion = (state, dispatch, options) => {
  var _a, _b;
  const { onCartChange, effectOn } = (0, import_useCartChangeEffect.default)();
  const engineContext = (0, import_useEngineContext.default)();
  const promotionEvaluator = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.promotionEvaluator;
  const { onGiftSelection } = options || {};
  const handleAutoAddGift = (0, import_ahooks.useMemoizedFn)(
    async (gift, giftData) => {
      if (gift == null ? void 0 : gift.product_variant_id) {
        return null;
      }
      if (!gift.product_id) {
        return null;
      }
      try {
        const { data } = await (0, import_serve.getProductDetail)(gift.product_id.toString(), {
          is_eject: 1
        });
        if (!data) {
          return null;
        }
        if (data.is_eject === 0) {
          return new Promise((resolve) => {
            var _a2;
            (_a2 = (0, import_utils.getHandleAddService)()) == null ? void 0 : _a2(data, (cacheItem) => {
              var _a3, _b2;
              const _giftData = {
                ...giftData || {},
                sourceProductId: (_a3 = giftData == null ? void 0 : giftData.sourceProductIds) == null ? void 0 : _a3[0],
                /** 上一次评估器计算的该策略赠品总数，用于判断是否需要补回赠品 */
                lastEvaluatedGiftCount: (giftData == null ? void 0 : giftData.giftCount) || 1
              };
              const priceParams = {
                price: 0,
                total: 0,
                origin_total: ((_b2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _b2.price) || (cacheItem == null ? void 0 : cacheItem.price) || 0,
                _initPrice: (cacheItem == null ? void 0 : cacheItem.price) || 0
              };
              let product = {
                ...cacheItem,
                ...priceParams,
                _giftInfo: _giftData,
                _extend: {
                  ...cacheItem._extend || {},
                  _giftInfo: _giftData,
                  ...priceParams,
                  quantity: (giftData == null ? void 0 : giftData.giftCount) || 1
                }
              };
              product.discount_list = (0, import_utils2.formatDiscountLists)(product, giftData == null ? void 0 : giftData.strategyName);
              resolve(product);
            });
          });
        } else {
          return null;
        }
      } catch (error) {
        return null;
      }
    }
  );
  const handleGiftActions = (0, import_ahooks.useMemoizedFn)(async (giftActions, products) => {
    var _a2, _b2;
    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 ? void 0 : onGiftSelection({
          strategyId,
          strategyName,
          giftOptions,
          giftCount,
          sourceProductIds
        });
        const sameStrategyGift = (newProducts || []).find((p) => {
          var _a3;
          return ((_a3 = p == null ? void 0 : p._giftInfo) == null ? void 0 : _a3.strategyId) === strategyId;
        });
        if (!sameStrategyGift) {
          const product = await handleAutoAddGift(giftOptions[0], addAction);
          if (product) {
            newProducts.push(product);
          }
        } else {
          const remainingCount = Number(giftCount || 0);
          sameStrategyGift._extend.quantity += remainingCount;
          if ((_b2 = (_a2 = sameStrategyGift == null ? void 0 : sameStrategyGift._extend) == null ? void 0 : _a2.other) == null ? void 0 : _b2.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 ? 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;
  });
  const onCartChangeEffect = (0, import_ahooks.useMemoizedFn)(
    async ({ 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 = await handleGiftActions(giftActions, products);
      setTimeout(() => {
        dispatch({
          type: "setService",
          payload: { value: finalProducts, unfulfilledPromotions, edit: true }
        });
      }, 100);
    }
  );
  const run = (0, import_ahooks.useMemoizedFn)(() => {
    return effectOn(onCartChangeEffect);
  });
  const formatProductList = (0, import_ahooks.useMemoizedFn)((list) => {
    if (!list || list.length === 0 || !promotionEvaluator) {
      return list || [];
    }
    const promotionProducts = list.map((item, index) => {
      const extend = item._extend || {};
      const other = extend.other || {};
      return {
        id: index,
        // 使用索引作为临时 id
        product_id: other.product_id ?? item.product_id ?? item.id,
        product_variant_id: other.product_variant_id ?? 0,
        name: item.title || extend.product_name,
        price: getMainOriginalPrice(item),
        quantity: extend.quantity ?? 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, ...rest } = item;
        return rest;
      }
      const promotionTags = strategyData.applicableStrategies.map((strategy) => strategy.display);
      return {
        ...item,
        _promotionTags: promotionTags
      };
    });
    console.log(newList, "newList444");
    return newList;
  });
  const processPromotion = (0, import_ahooks.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);
  });
  return {
    run,
    formatProductList,
    processPromotion
  };
};
var usePromotion_default = usePromotion;
