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/modules/Rules/index.ts
var Rules_exports = {};
__export(Rules_exports, {
  RulesModule: () => RulesModule
});
module.exports = __toCommonJS(Rules_exports);
var import_BaseModule = require("../BaseModule");
var import_types = require("./types");
var import_utils = require("../../solution/ShopDiscount/utils");
var import_utils2 = require("../Cart/utils");
var import_decimal = __toESM(require("decimal.js"));
var import_lodash_es = require("lodash-es");
var import_dayjs = __toESM(require("dayjs"));
var import_utils3 = require("../../solution/ShopDiscount/utils");
var import_utils4 = require("../../solution/ShopDiscount/utils");
var RulesModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "rules";
    this.defaultVersion = "1.0.0";
    this.hooks = {};
  }
  async initialize(core, options) {
    this.core = core;
    this.hooks = options == null ? void 0 : options.hooks;
    this.store = options == null ? void 0 : options.store;
    this.window = core.getPlugin("window");
  }
  async setRulesList(rulesList) {
    this.store.rulesList = rulesList;
    await this.core.effects.emit(`${this.name}:onRulesListChange`, rulesList);
  }
  getRulesList() {
    return this.store.rulesList;
  }
  getWalletPassEvaluator() {
    var _a, _b;
    return (_b = (_a = this.window).getWalletPassEvaluator) == null ? void 0 : _b.call(_a);
  }
  // 商品不需要holder,则不需要判断，直接返回true，商品需要holder但是还没填写，那么暂时不使用带有holder的券，直到填写才去匹配
  checkHolderMatch(discount, product, holders) {
    var _a;
    if (((_a = discount.holder) == null ? void 0 : _a.holder_type) !== "form")
      return true;
    const orderHolderId = Array.isArray(holders) && holders.length > 0 ? holders[0].form_record_id : void 0;
    const productHolderId = Array.isArray(product.holder_id) ? product.holder_id[0] : product.holder_id;
    if (!product.isNeedHolder)
      return true;
    if (!orderHolderId && !productHolderId)
      return false;
    return (productHolderId || orderHolderId) === discount.holder.holder_id;
  }
  // 判断discountList 是否可以对当前productList生效
  isDiscountListAvailable({
    oldDiscountList,
    newDiscountList,
    productList,
    orderTotalAmount,
    holders,
    isFormSubject
  }) {
    if (!newDiscountList || newDiscountList.length === 0) {
      return {
        isAvailable: false,
        discountList: oldDiscountList,
        productList
      };
    }
    if (productList.every((item) => {
      var _a;
      const product = this.hooks.getProduct(item);
      return product.booking_id && (((_a = product.discount_list) == null ? void 0 : _a.length) || product.total == 0);
    })) {
      return {
        isAvailable: false,
        discountList: oldDiscountList,
        productList,
        unavailableReason: import_types.UnavailableReason.AlreadyUsed
      };
    }
    const filteredOldDiscountList = oldDiscountList.filter(
      (discount) => !discount.isEditMode && (discount.tag !== "good_pass" || discount.isScan)
    );
    const mergedDiscountList = (0, import_utils.uniqueById)([
      ...filteredOldDiscountList,
      ...newDiscountList
    ]);
    const result = this.calcDiscount(
      {
        discountList: mergedDiscountList,
        productList: [...productList],
        orderTotalAmount,
        holders,
        isFormSubject
      },
      {
        scan: true
      }
    );
    let hasApplicableDiscount = false;
    const newDiscountIds = newDiscountList.map((discount) => discount.id);
    result.productList.forEach((product) => {
      const { discount_list, bundle } = this.hooks.getProduct(product);
      const allDiscountList = [...discount_list || []];
      (bundle || []).forEach((item) => {
        allDiscountList.push(...(item == null ? void 0 : item.discount_list) || []);
      });
      if (allDiscountList && allDiscountList.length > 0) {
        const usedNewDiscount = allDiscountList.some(
          (discount) => {
            var _a;
            return newDiscountIds.includes((_a = discount == null ? void 0 : discount.discount) == null ? void 0 : _a.resource_id);
          }
        );
        if (usedNewDiscount) {
          hasApplicableDiscount = true;
        }
      }
    });
    let unavailableReason;
    if (!hasApplicableDiscount) {
      unavailableReason = this.getUnavailableReason(newDiscountList, productList);
    }
    return {
      isAvailable: hasApplicableDiscount,
      discountList: hasApplicableDiscount ? result.discountList : oldDiscountList,
      productList: hasApplicableDiscount ? result.productList : productList,
      unavailableReason
    };
  }
  filterDiscountListByType(discountList, type) {
    return (discountList || []).filter((item) => item.type === type || item.tag === type);
  }
  /** 剔除指定 type/tag 的折扣项，保留手动改价(type=product) / 券等 */
  excludeDiscountListByType(discountList, type) {
    return (discountList || []).filter((item) => item.type !== type && item.tag !== type);
  }
  /** 手动改价场景：去掉 promotion，保留 type=product 等行内折扣 */
  resolveDiscountListForManualOverride(discountList) {
    return this.excludeDiscountListByType(discountList, "promotion");
  }
  // 获取券不可用的原因
  getUnavailableReason(discountList, productList) {
    var _a;
    for (const discount of discountList) {
      for (const item of productList) {
        const product = this.hooks.getProduct(item);
        const bookingTime = ((product == null ? void 0 : product.startDate) || (0, import_dayjs.default)()).format("YYYY-MM-DD HH:mm:ss");
        const filteredList = (0, import_utils.filterDiscountListByBookingTime)([discount], bookingTime);
        if (filteredList.length === 0) {
          return import_types.UnavailableReason.TimeLimit;
        }
      }
    }
    for (const discount of discountList) {
      const limitedData = discount.limited_relation_product_data;
      let hasApplicableProduct = false;
      for (const item of productList) {
        const product = this.hooks.getProduct(item);
        if (limitedData.type === "product_all") {
          hasApplicableProduct = true;
          break;
        } else if ((_a = limitedData.product_ids) == null ? void 0 : _a.includes(product.id)) {
          hasApplicableProduct = true;
          break;
        }
      }
      if (!hasApplicableProduct) {
        return import_types.UnavailableReason.ProductNotApplicable;
      }
    }
    return import_types.UnavailableReason.Unknown;
  }
  calcDiscount({
    discountList,
    productList,
    holders,
    isFormSubject,
    orderTotalAmount
  }, options) {
    var _a;
    const isEditModeAddNewProduct = productList.find((n) => n.booking_id) && productList.find((n) => !n.booking_id);
    const editModeDiscount = [];
    const addModeDiscount = [];
    discountList.forEach((discount) => {
      if (discount.isEditMode) {
        editModeDiscount.push(discount);
      } else {
        addModeDiscount.push(discount);
      }
    });
    const editModeOrderLevelProductIds = /* @__PURE__ */ new Set();
    editModeDiscount.forEach((discount) => {
      var _a2, _b;
      if (((_a2 = discount.discount) == null ? void 0 : _a2.discount_calculation_mode) === "order_level") {
        editModeOrderLevelProductIds.add((_b = discount == null ? void 0 : discount.discount) == null ? void 0 : _b.discount_product_id);
      }
    });
    if (editModeOrderLevelProductIds.size > 0) {
      addModeDiscount.forEach((discount) => {
        if (editModeOrderLevelProductIds.has(discount.product_id)) {
          discount.isDisabled = true;
        }
      });
    }
    const filteredDiscountList = addModeDiscount.filter((discount) => {
      return !discount.isManualSelect;
    });
    const hasDiscountInput = editModeDiscount.length > 0 || addModeDiscount.length > 0 || Boolean(options == null ? void 0 : options.discountId) || Boolean((_a = options == null ? void 0 : options.selectedList) == null ? void 0 : _a.length) || Boolean(options == null ? void 0 : options.scan);
    if (!hasDiscountInput) {
      return {
        discountList,
        productList
      };
    }
    const flattenProductsWithBundle = (productList2) => {
      const flattened = [];
      productList2.forEach((originProduct) => {
        const product = this.hooks.getProduct(originProduct);
        flattened.push({
          type: "main",
          originProduct,
          product,
          price: Number(product.price || 0),
          id: product.id,
          _id: product._id,
          parentId: product._id,
          quantity: product.quantity,
          num: product.num
        });
        if (product.bundle && Array.isArray(product.bundle) && product.bundle.length > 0) {
          product.bundle.forEach((bundleItem, bundleIndex) => {
            flattened.push({
              type: "bundle",
              originProduct,
              parentProduct: product,
              bundleItem,
              bundleIndex,
              // 虚拟商品属性
              price: Number(bundleItem.price || 0),
              id: bundleItem._bundle_product_id,
              // 🔥 使用 _bundle_product_id
              _id: `${product._id}_bundle_${bundleIndex}`,
              parentId: product._id,
              num: bundleItem.num || 1,
              quantity: bundleItem.num || 1,
              total: new import_decimal.default(bundleItem.price || 0).mul(bundleItem.num || 1).toNumber(),
              origin_total: new import_decimal.default(bundleItem.price || 0).mul(bundleItem.num || 1).toNumber(),
              original_price: bundleItem.original_price,
              // 继承主商品属性
              booking_id: product.booking_id,
              discount_list: bundleItem.discount_list || []
            });
          });
        }
      });
      return flattened;
    };
    const sortedDiscountList = [...filteredDiscountList].sort((a, b) => {
      const isHolderDiscount = (discount) => {
        var _a2, _b;
        return ((_b = (_a2 = discount.metadata) == null ? void 0 : _a2.holder) == null ? void 0 : _b.type) === "custom";
      };
      const isGoodPass = (discount) => discount.tag === "good_pass";
      const isOrderLevelDiscount = (discount) => {
        var _a2;
        return discount.tag === "product_discount_card" && ((_a2 = discount.metadata) == null ? void 0 : _a2.discount_calculation_mode) === "order_level";
      };
      const isItemLevelDiscount = (discount) => {
        var _a2;
        return discount.tag === "product_discount_card" && ((_a2 = discount.metadata) == null ? void 0 : _a2.discount_calculation_mode) !== "order_level";
      };
      const getPriority = (discount) => {
        const isHolder = isHolderDiscount(discount);
        if (isHolder) {
          if (isGoodPass(discount))
            return 1;
          if (isItemLevelDiscount(discount))
            return 2;
          if (isOrderLevelDiscount(discount))
            return 3;
        } else {
          if (isGoodPass(discount))
            return 4;
          if (isItemLevelDiscount(discount))
            return 5;
          if (isOrderLevelDiscount(discount))
            return 6;
        }
        return 7;
      };
      function compareByExpireTime(itemA, itemB) {
        if (itemA.expire_time && itemB.expire_time) {
          const timeA = new Date(itemA.expire_time).getTime();
          const timeB = new Date(itemB.expire_time).getTime();
          return timeA - timeB;
        }
        return itemA.expire_time ? -1 : itemB.expire_time ? 1 : 0;
      }
      function compareDiscountCardValue(itemA, itemB) {
        var _a2, _b;
        const typeA = ((_a2 = itemA.metadata) == null ? void 0 : _a2.discount_card_type) || "percent";
        const typeB = ((_b = itemB.metadata) == null ? void 0 : _b.discount_card_type) || "percent";
        if (typeA === "fixed_amount" && typeB === "percent")
          return -1;
        if (typeA === "percent" && typeB === "fixed_amount")
          return 1;
        if (typeA === "fixed_amount" && typeB === "fixed_amount") {
          if (itemA.par_value !== itemB.par_value) {
            const valueA = new import_decimal.default(itemA.par_value || 0);
            const valueB = new import_decimal.default(itemB.par_value || 0);
            return valueB.minus(valueA).toNumber();
          }
        }
        if (typeA === "percent" && typeB === "percent") {
          if (itemA.par_value !== itemB.par_value) {
            const valueA = new import_decimal.default(100).minus(itemA.par_value || 0);
            const valueB = new import_decimal.default(100).minus(itemB.par_value || 0);
            return valueA.minus(valueB).toNumber();
          }
        }
        return 0;
      }
      const priorityA = getPriority(a);
      const priorityB = getPriority(b);
      if (priorityA !== priorityB) {
        return priorityA - priorityB;
      }
      if (isGoodPass(a) && isGoodPass(b)) {
        return compareByExpireTime(a, b);
      }
      if (a.tag === "product_discount_card" && b.tag === "product_discount_card") {
        const valueCompare = compareDiscountCardValue(a, b);
        if (valueCompare !== 0)
          return valueCompare;
        return compareByExpireTime(a, b);
      }
      return compareByExpireTime(a, b);
    });
    const flattenedList = flattenProductsWithBundle(productList);
    const sortedFlattenedList = flattenedList.sort((a, b) => {
      var _a2, _b;
      const priceA = new import_decimal.default(
        a.type === "bundle" ? a.original_price ?? a.price ?? "0" : a.price || "0"
      );
      const priceB = new import_decimal.default(
        b.type === "bundle" ? b.original_price ?? b.price ?? "0" : b.price || "0"
      );
      if (priceA.equals(priceB)) {
        if (a.type !== b.type) {
          return a.type === "main" ? -1 : 1;
        }
        if (a.type === "main" && b.type === "main") {
          if (a.product.quantity === b.product.quantity) {
            return (((_a2 = b.product.discount_list) == null ? void 0 : _a2.length) || 0) - (((_b = a.product.discount_list) == null ? void 0 : _b.length) || 0);
          }
          return a.product.quantity - b.product.quantity;
        }
        if (a.type === "bundle" && b.type === "bundle") {
          return (a.num || 1) - (b.num || 1);
        }
      }
      return priceB.minus(priceA).toNumber();
    });
    const evaluator = this.getWalletPassEvaluator();
    if (evaluator) {
      addModeDiscount.forEach((discount) => {
        var _a2, _b;
        const discountType = discount.tag || discount.type;
        if (["good_pass", "discount_card", "product_discount_card"].includes(
          discountType
        )) {
          const voucher = {
            id: discount.id,
            amount: Number(discount.par_value || 0),
            balance: Number(discount.balance || 0),
            type: discountType,
            product_id: discount.product_id,
            unified_available_status: 1,
            available_product_type: (_a2 = discount.limited_relation_product_data) == null ? void 0 : _a2.type,
            available_product_ids: (_b = discount.limited_relation_product_data) == null ? void 0 : _b.product_ids
          };
          const productsForEvaluate = sortedFlattenedList.map((item) => {
            var _a3;
            return {
              product_id: item.id,
              price: item.price || 0,
              quantity: item.quantity || item.num || 1,
              selling_price: item.price || 0,
              product_options: item.type === "main" ? (_a3 = item.product) == null ? void 0 : _a3.options : void 0
            };
          });
          const result = evaluator.checkVoucherAvailability({
            orderTotalAmount,
            products: productsForEvaluate,
            vouchers: [voucher]
          });
          if (result.isAvailable) {
            discount.config = {
              ...result.config,
              isAvailable: true
            };
          } else {
            discount.config = {
              isAvailable: false
            };
          }
        }
      });
    }
    const usedDiscounts = /* @__PURE__ */ new Map();
    const usedProductIdCounts = /* @__PURE__ */ new Map();
    const discountApplicability = /* @__PURE__ */ new Map();
    const discountApplicableProducts = /* @__PURE__ */ new Map();
    addModeDiscount.forEach((discount) => {
      discountApplicability.set(discount.id, []);
      discountApplicableProducts.set(discount.id, []);
    });
    const orderLevelDiscountAllocations = /* @__PURE__ */ new Map();
    const orderLevelDiscountApplicableItems = /* @__PURE__ */ new Map();
    const itemApplicableDiscounts = /* @__PURE__ */ new Map();
    const checkItemApplicableForDiscount = (flatItem, discount) => {
      var _a2, _b, _c, _d, _e, _f, _g, _h;
      let product;
      if (flatItem.type === "main") {
        product = flatItem.product;
      } else {
        product = {
          _id: flatItem._id,
          id: flatItem.id,
          price: flatItem.price,
          quantity: flatItem.quantity,
          num: flatItem.num,
          booking_id: flatItem.booking_id,
          discount_list: flatItem.discount_list || [],
          startDate: (_a2 = flatItem.parentProduct) == null ? void 0 : _a2.startDate
        };
      }
      const isAvailableProduct = flatItem.type === "main" ? !((product == null ? void 0 : product.booking_id) && ((_b = product == null ? void 0 : product.discount_list) == null ? void 0 : _b.length) && ((_c = product == null ? void 0 : product.discount_list) == null ? void 0 : _c.every((d) => d.id && ["good_pass", "discount_card", "product_discount_card"].includes(d.tag || d.type)))) : !((flatItem == null ? void 0 : flatItem.booking_id) && !!((_e = (_d = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _d.discount_list) == null ? void 0 : _e.length) && ((_g = (_f = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _f.discount_list) == null ? void 0 : _g.every((d) => d.id)));
      if (!isAvailableProduct) {
        return false;
      }
      if ((0, import_lodash_es.isBoolean)(product.vouchersApplicable) && !product.vouchersApplicable) {
        return false;
      }
      if (Number(product.price) <= 0 || !product.price) {
        return false;
      }
      const limitedData = discount.limited_relation_product_data;
      const timeLimit = !!(0, import_utils.filterDiscountListByBookingTime)([discount], ((product == null ? void 0 : product.startDate) || (0, import_dayjs.default)()).format("YYYY-MM-DD HH:mm:ss")).length;
      if (!timeLimit) {
        return false;
      }
      let isLimitedProduct = false;
      if (limitedData.type === "product_all") {
        if (limitedData.filter === 1 && ((_h = limitedData.exclude_product_ids) == null ? void 0 : _h.includes(product.id))) {
          isLimitedProduct = false;
        } else {
          isLimitedProduct = true;
        }
      } else if (limitedData.product_ids && limitedData.product_ids.includes(product.id)) {
        isLimitedProduct = true;
      }
      const isBundleAvailable = this.checkPackageSubItemUsageRules(discount, flatItem);
      return isLimitedProduct && isBundleAvailable;
    };
    const selectedOrderLevelDiscounts = sortedDiscountList.filter((discount) => {
      return (0, import_utils3.isOrderLevelFixedAmountDiscount)(discount) && discount.isSelected !== false;
    });
    selectedOrderLevelDiscounts.forEach((discount) => {
      const applicableItemIds = /* @__PURE__ */ new Set();
      sortedFlattenedList.forEach((flatItem) => {
        if (checkItemApplicableForDiscount(flatItem, discount)) {
          applicableItemIds.add(flatItem._id);
          if (!itemApplicableDiscounts.has(flatItem._id)) {
            itemApplicableDiscounts.set(flatItem._id, /* @__PURE__ */ new Set());
          }
          itemApplicableDiscounts.get(flatItem._id).add(discount.id);
        }
      });
      orderLevelDiscountApplicableItems.set(discount.id, applicableItemIds);
    });
    const occupiedItems = /* @__PURE__ */ new Map();
    selectedOrderLevelDiscounts.forEach((discount) => {
      const limitedData = discount.limited_relation_product_data;
      const isExclusiveDiscount = limitedData.type !== "product_all";
      if (isExclusiveDiscount) {
        const applicableItems = orderLevelDiscountApplicableItems.get(discount.id);
        if (applicableItems) {
          applicableItems.forEach((itemId) => {
            if (!occupiedItems.has(itemId)) {
              occupiedItems.set(itemId, discount.id);
            }
          });
        }
      }
    });
    sortedDiscountList.forEach((discount) => {
      if (!(0, import_utils3.isOrderLevelFixedAmountDiscount)(discount)) {
        return;
      }
      const applicableProducts = [];
      sortedFlattenedList.forEach((flatItem) => {
        var _a2, _b, _c;
        const occupyingDiscountId = occupiedItems.get(flatItem._id);
        if (occupyingDiscountId !== void 0 && occupyingDiscountId !== discount.id) {
          return;
        }
        if (!checkItemApplicableForDiscount(flatItem, discount)) {
          return;
        }
        let product;
        if (flatItem.type === "main") {
          product = flatItem.product;
        } else {
          product = {
            _id: flatItem._id,
            id: flatItem.id,
            price: flatItem.price,
            quantity: flatItem.quantity,
            num: flatItem.num
          };
        }
        const quantity = flatItem.type === "main" ? product.num || product.quantity || 1 : (product.num || product.quantity || 1) * (((_a2 = flatItem.parentProduct) == null ? void 0 : _a2.num) || ((_b = flatItem.parentProduct) == null ? void 0 : _b.quantity) || 1);
        const originalAmount = flatItem.type === "main" ? Number(product.price ?? 0) : Number(flatItem.original_price ?? flatItem.price ?? 0);
        const productData = {
          productId: flatItem._id,
          amount: originalAmount,
          quantity
        };
        if (flatItem.type === "bundle") {
          productData.parentQuantity = ((_c = flatItem.parentProduct) == null ? void 0 : _c.quantity) || 1;
        }
        applicableProducts.push(productData);
      });
      if (applicableProducts.length > 0) {
        const allocation = (0, import_utils4.calculateOrderLevelDiscountAllocation)(discount, applicableProducts);
        orderLevelDiscountAllocations.set(discount.id, allocation);
      }
    });
    const processedProductsMap = /* @__PURE__ */ new Map();
    const appliedDiscountProducts = /* @__PURE__ */ new Map();
    sortedFlattenedList.forEach((flatItem) => {
      var _a2;
      let product, originProduct;
      if (flatItem.type === "main") {
        product = flatItem.product;
        originProduct = flatItem.originProduct;
      } else {
        product = {
          _id: flatItem._id,
          id: flatItem.id,
          price: flatItem.price,
          quantity: flatItem.quantity,
          num: flatItem.num,
          total: flatItem.total,
          origin_total: flatItem.origin_total,
          booking_id: flatItem.booking_id,
          discount_list: flatItem.discount_list || [],
          startDate: (_a2 = flatItem.parentProduct) == null ? void 0 : _a2.startDate
        };
        originProduct = flatItem.originProduct;
      }
      addModeDiscount.forEach((discount) => {
        var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j;
        const limitedData = discount == null ? void 0 : discount.limited_relation_product_data;
        const _tempVar = (flatItem == null ? void 0 : flatItem.type) === "bundle" ? flatItem == null ? void 0 : flatItem.parentProduct : flatItem == null ? void 0 : flatItem.product;
        const isHolderMatch = this.checkHolderMatch(
          discount,
          {
            isNeedHolder: isFormSubject && !(_tempVar == null ? void 0 : _tempVar.isNormalProduct),
            holder_id: (_tempVar == null ? void 0 : _tempVar.holder_id) || product.holder_id
          },
          holders
        );
        let timeLimit = true;
        timeLimit = !!(0, import_utils.filterDiscountListByBookingTime)([discount], ((product == null ? void 0 : product.startDate) || (0, import_dayjs.default)()).format("YYYY-MM-DD HH:mm:ss")).length;
        const isLimitedProduct = (limitedData.type === "product_all" && limitedData.filter !== 1 || limitedData.type === "product_all" && limitedData.filter === 1 && !limitedData.exclude_product_ids.includes(product.id) || limitedData.product_ids && limitedData.product_ids.includes(product.id)) && isHolderMatch;
        const isAvailableProduct = flatItem.type === "main" ? !((product == null ? void 0 : product.booking_id) && ((_a3 = product == null ? void 0 : product.discount_list) == null ? void 0 : _a3.length) && ((_b = product == null ? void 0 : product.discount_list) == null ? void 0 : _b.every(
          (discount2) => discount2.id && [
            "good_pass",
            "discount_card",
            "product_discount_card"
          ].includes(discount2.tag || discount2.type)
        ))) : !((flatItem == null ? void 0 : flatItem.booking_id) && !!((_d = (_c = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _c.discount_list) == null ? void 0 : _d.length) && ((_f = (_e = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _e.discount_list) == null ? void 0 : _f.every((discount2) => discount2.id)));
        const isBundleAvailable = this.checkPackageSubItemUsageRules(discount, flatItem);
        if (isAvailableProduct && isLimitedProduct && timeLimit && isBundleAvailable && ((_g = discount.config) == null ? void 0 : _g.isAvailable)) {
          (_h = discountApplicability.get(discount.id)) == null ? void 0 : _h.push(product.id);
          const applicableProducts = discountApplicableProducts.get(discount.id) || [];
          const discountType = discount.tag || discount.type;
          const isGoodPass = discountType === "good_pass";
          const num = isGoodPass || (flatItem == null ? void 0 : flatItem.type) === "main" ? 1 : product.num;
          const productData = {
            amount: product.price * num,
            type: discountType,
            tag: discountType,
            discount: {
              discount_card_type: (_i = discount == null ? void 0 : discount.metadata) == null ? void 0 : _i.discount_card_type,
              fixed_amount: product.price,
              discount_calculation_mode: (_j = discount == null ? void 0 : discount.metadata) == null ? void 0 : _j.discount_calculation_mode,
              resource_id: discount.id,
              title: discount.format_title,
              original_amount: product.price || product.origin_total,
              pre_value: discount.par_value,
              product_id: originProduct.id,
              discount_product_id: discount.product_id
            },
            metadata: {
              num
            }
          };
          applicableProducts.push(productData);
          discountApplicableProducts.set(discount.id, applicableProducts);
        }
      });
    });
    const processedFlatItemsMap = /* @__PURE__ */ new Map();
    const applyDiscountToOptions = (options2, discount) => {
      if (!(options2 == null ? void 0 : options2.length))
        return { discountedOptions: options2, optionDiscountAmount: 0 };
      let optionDiscountAmount = 0;
      const discountedOptions = options2.map((option) => {
        const rawUnit = option._original_price ?? option._original_add_price ?? option.price ?? option.add_price;
        const baseUnitNum = Number(rawUnit ?? 0);
        if (baseUnitNum <= 0)
          return option;
        const discountedPrice = (0, import_utils.getDiscountAmount)(discount, baseUnitNum, baseUnitNum);
        const optQty = Number(option.num ?? option.quantity ?? 1);
        optionDiscountAmount = new import_decimal.default(optionDiscountAmount).plus(new import_decimal.default(baseUnitNum).minus(discountedPrice).mul(optQty)).toNumber();
        const { _original_add_price, ...rest } = option;
        const tmpl = rest.price ?? rest.add_price;
        const nextPrice = typeof tmpl === "string" ? String(discountedPrice) : discountedPrice;
        return {
          ...rest,
          _original_price: option._original_price ?? (_original_add_price !== void 0 ? _original_add_price : rawUnit),
          price: nextPrice
        };
      });
      return { discountedOptions, optionDiscountAmount };
    };
    const restoreOptionPrices = (options2) => {
      if (!(options2 == null ? void 0 : options2.length))
        return options2;
      return options2.map((option) => {
        const orig = option._original_price !== void 0 ? option._original_price : option._original_add_price;
        if (orig !== void 0) {
          const { _original_price, _original_add_price, ...rest } = option;
          return { ...rest, price: orig };
        }
        return option;
      });
    };
    const getOptionTotal = (options2) => {
      if (!(options2 == null ? void 0 : options2.length))
        return 0;
      return options2.reduce((sum, opt) => {
        const unit = Number(opt.price ?? opt.add_price ?? 0);
        const n = Number(opt.num ?? opt.quantity ?? 1);
        return new import_decimal.default(sum).plus(new import_decimal.default(unit).mul(n)).toNumber();
      }, 0);
    };
    sortedFlattenedList.forEach((flatItem, index) => {
      var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I;
      let product, originProduct;
      if (flatItem.type === "main") {
        product = flatItem.product;
        originProduct = flatItem.originProduct;
      } else {
        product = {
          _id: flatItem._id,
          id: flatItem.id,
          price: flatItem.price,
          quantity: flatItem.quantity,
          num: flatItem.num,
          total: flatItem.total,
          original_price: (_a2 = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _a2.original_price,
          origin_total: (_b = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _b.original_price,
          booking_id: flatItem.booking_id,
          discount_list: ((_c = flatItem == null ? void 0 : flatItem.bundleItem) == null ? void 0 : _c.discount_list) || [],
          startDate: (_d = flatItem.parentProduct) == null ? void 0 : _d.startDate
        };
        originProduct = flatItem.originProduct;
      }
      const isPersistedProduct = (product == null ? void 0 : product.booking_id) || (originProduct == null ? void 0 : originProduct.order_detail_id) || (originProduct == null ? void 0 : originProduct.orderDetailId) || (originProduct == null ? void 0 : originProduct.booking_id);
      const hasExistingWalletDiscount = ((_e = product.discount_list) == null ? void 0 : _e.length) && ((_f = product == null ? void 0 : product.discount_list) == null ? void 0 : _f.every((discount) => {
        var _a3;
        const discountIdentity = discount.id ?? ((_a3 = discount.discount) == null ? void 0 : _a3.resource_id);
        const discountType = discount.tag || discount.type;
        return Boolean(
          discountIdentity && ["good_pass", "discount_card", "product_discount_card"].includes(
            discountType
          )
        );
      }));
      if (isPersistedProduct && hasExistingWalletDiscount) {
        if (flatItem.type === "main") {
          processedProductsMap.set(product._id, [originProduct]);
        } else {
          processedFlatItemsMap.set(flatItem._id, [
            {
              ...flatItem,
              processed: true
            }
          ]);
        }
        return;
      }
      const applicableDiscounts = sortedDiscountList.filter((discount) => {
        var _a3, _b2, _c2, _d2;
        const discountType = discount.tag || discount.type;
        if (["good_pass", "discount_card", "product_discount_card"].includes(
          discountType
        )) {
          if (discount.config === void 0 || !((_a3 = discount == null ? void 0 : discount.config) == null ? void 0 : _a3.isAvailable)) {
            return false;
          }
        }
        if ((Number(product.price) <= 0 || !product.price) && !((_b2 = product.discount_list) == null ? void 0 : _b2.length) && (discount.tag || discount.type) === "good_pass")
          return false;
        if ((Number(product.price) <= 0 || !product.price) && !((_c2 = product.discount_list) == null ? void 0 : _c2.find((n) => {
          var _a4;
          return ((_a4 = n.discount) == null ? void 0 : _a4.resource_id) === discount.id;
        })) && (discount.tag || discount.type) !== "good_pass")
          return false;
        const targetUsedDiscounts = usedDiscounts.get(discount.id);
        if (targetUsedDiscounts && (discount.tag || discount.type) === "good_pass")
          return false;
        if ((discount.tag || discount.type) === "good_pass") {
          const maxUsagePerOrder = (_d2 = discount.config) == null ? void 0 : _d2.maxUsagePerOrder;
          if (maxUsagePerOrder && maxUsagePerOrder > 0) {
            const currentUsedCount = usedProductIdCounts.get(discount.product_id) || 0;
            if (currentUsedCount >= maxUsagePerOrder) {
              return false;
            }
          }
        }
        const limitedData = discount.limited_relation_product_data;
        const _tempVar = (flatItem == null ? void 0 : flatItem.type) === "bundle" ? flatItem == null ? void 0 : flatItem.parentProduct : flatItem == null ? void 0 : flatItem.product;
        const isHolderMatch = this.checkHolderMatch(
          discount,
          {
            isNeedHolder: isFormSubject && !(_tempVar == null ? void 0 : _tempVar.isNormalProduct),
            holder_id: (_tempVar == null ? void 0 : _tempVar.holder_id) || product.holder_id
          },
          holders
        );
        if (!isHolderMatch)
          return false;
        let timeLimit = true;
        timeLimit = !!(0, import_utils.filterDiscountListByBookingTime)([discount], (product.startDate || (0, import_dayjs.default)()).format("YYYY-MM-DD HH:mm:ss")).length;
        if (!timeLimit) {
          return false;
        }
        if (limitedData.type === "product_all") {
          if (limitedData.filter === 1 && limitedData.exclude_product_ids.includes(product.id)) {
            return false;
          }
          if (!this.checkPackageSubItemUsageRules(discount, flatItem)) {
            return false;
          }
          return true;
        } else if (limitedData.product_ids && limitedData.product_ids.includes(product.id)) {
          if (!this.checkPackageSubItemUsageRules(discount, flatItem)) {
            return false;
          }
          return true;
        }
        return false;
      });
      const selectedDiscountCard = applicableDiscounts.find(
        (n) => n.isScan && n.isSelected && (n.tag || n.type) !== "good_pass"
      );
      const selectedDiscount = selectedDiscountCard || applicableDiscounts[0];
      let isManualDiscount = false;
      if (flatItem.type === "main") {
        isManualDiscount = typeof product.isManualDiscount === "boolean" ? product.isManualDiscount : ((_g = product.discount_list) == null ? void 0 : _g.some((item) => item.type === "product")) || product.total != product.origin_total && (product.bundle || []).every(
          (item) => {
            var _a3;
            return !((_a3 = item.discount_list || []) == null ? void 0 : _a3.length);
          }
        ) && (!((_h = product.discount_list) == null ? void 0 : _h.length) || ((_j = (_i = product == null ? void 0 : product.discount_list) == null ? void 0 : _i.every) == null ? void 0 : _j.call(
          _i,
          (item) => item.type === "product"
        )));
        if (product.inPromotion) {
          isManualDiscount = false;
        }
      } else {
        const parentProduct = flatItem.parentProduct;
        if (parentProduct) {
          isManualDiscount = typeof parentProduct.isManualDiscount === "boolean" ? parentProduct.isManualDiscount : ((_k = parentProduct.discount_list) == null ? void 0 : _k.some((item) => item.type === "product")) || parentProduct.total != parentProduct.origin_total && (parentProduct.bundle || []).every(
            (item) => {
              var _a3;
              return !((_a3 = item.discount_list || []) == null ? void 0 : _a3.length);
            }
          ) && (!((_l = parentProduct.discount_list) == null ? void 0 : _l.length) || ((_n = (_m = parentProduct == null ? void 0 : parentProduct.discount_list) == null ? void 0 : _m.every) == null ? void 0 : _n.call(
            _m,
            (item) => item.type === "product"
          )));
        }
      }
      if (options == null ? void 0 : options.discountId) {
        if (flatItem.type === "main" && ((_o = product.discount_list) == null ? void 0 : _o.some(
          (item) => {
            var _a3;
            return ((_a3 = item.discount) == null ? void 0 : _a3.resource_id) === options.discountId;
          }
        ))) {
          isManualDiscount = false;
        }
        if (flatItem.type === "bundle") {
          if (((_p = product.discount_list) == null ? void 0 : _p.some(
            (item) => {
              var _a3;
              return ((_a3 = item.discount) == null ? void 0 : _a3.resource_id) === options.discountId;
            }
          )) || ((_r = (_q = flatItem.parentProduct) == null ? void 0 : _q.discount_list) == null ? void 0 : _r.some(
            (item) => {
              var _a3;
              return ((_a3 = item.discount) == null ? void 0 : _a3.resource_id) === options.discountId;
            }
          ))) {
            isManualDiscount = false;
          }
        }
      }
      if (options == null ? void 0 : options.selectedList) {
        if (flatItem.type === "main" && ((_s = product.discount_list) == null ? void 0 : _s.some(
          (item) => {
            var _a3;
            return (_a3 = options == null ? void 0 : options.selectedList) == null ? void 0 : _a3.some(
              (n) => {
                var _a4;
                return n.discountId === ((_a4 = item.discount) == null ? void 0 : _a4.resource_id);
              }
            );
          }
        ))) {
          isManualDiscount = false;
        }
        if (flatItem.type === "bundle") {
          if (((_t = product.discount_list) == null ? void 0 : _t.some(
            (item) => {
              var _a3;
              return (_a3 = options == null ? void 0 : options.selectedList) == null ? void 0 : _a3.some(
                (n) => {
                  var _a4;
                  return n.discountId === ((_a4 = item.discount) == null ? void 0 : _a4.resource_id);
                }
              );
            }
          )) || ((_v = (_u = flatItem.parentProduct) == null ? void 0 : _u.discount_list) == null ? void 0 : _v.some(
            (item) => {
              var _a3;
              return (_a3 = options == null ? void 0 : options.selectedList) == null ? void 0 : _a3.some(
                (n) => {
                  var _a4;
                  return n.discountId === ((_a4 = item.discount) == null ? void 0 : _a4.resource_id);
                }
              );
            }
          ))) {
            isManualDiscount = false;
          }
        }
      }
      if (applicableDiscounts.length === 0 || isManualDiscount || (0, import_lodash_es.isBoolean)(product.vouchersApplicable) && !product.vouchersApplicable) {
        if (flatItem.type === "main") {
          const restoredOptions = restoreOptionPrices(product.options);
          if (product.isClient) {
            processedProductsMap.set(product._id, [
              this.hooks.setProduct(originProduct, {
                ...isManualDiscount ? {} : {
                  origin_total: (0, import_utils2.getProductOriginTotalPrice)({
                    product: {
                      original_price: product.original_price
                    },
                    bundle: product.bundle,
                    options: restoredOptions
                  }),
                  variant: originProduct._productInit.variant,
                  original_price: originProduct._productInit.original_price,
                  total: (0, import_utils2.getProductTotalPrice)({
                    product: {
                      price: product.price
                    },
                    bundle: product.bundle,
                    options: restoredOptions
                  }),
                  price: product.price,
                  options: restoredOptions
                },
                discount_list: isManualDiscount ? this.resolveDiscountListForManualOverride(product.discount_list) : this.filterDiscountListByType(product.discount_list, "promotion")
              })
            ]);
          } else {
            let total = product.inPromotion ? ((_w = product == null ? void 0 : product._promotion) == null ? void 0 : _w.finalPrice) ?? product.origin_total ?? product.total : product.origin_total ?? product.total;
            let main_product_selling_price = product.price;
            if ((product.discount_list || []).some((item) => item.type === "promotion") || (0, import_lodash_es.isBoolean)(product.vouchersApplicable) && !product.vouchersApplicable) {
              total = product.total ?? product.origin_total;
              main_product_selling_price = product.main_product_selling_price ?? main_product_selling_price;
            }
            processedProductsMap.set(product._id, [
              this.hooks.setProduct(originProduct, {
                ...isManualDiscount ? {
                  price: product.price,
                  main_product_selling_price: product.price
                } : {
                  _id: product._id.split("___")[0] + "___" + index,
                  total,
                  price: product.price,
                  main_product_selling_price,
                  options: restoredOptions
                },
                discount_list: isManualDiscount ? this.resolveDiscountListForManualOverride(product.discount_list) : this.filterDiscountListByType(product.discount_list, "promotion")
              })
            ]);
          }
        } else {
          processedFlatItemsMap.set(flatItem._id, [{
            ...flatItem,
            discount_list: isManualDiscount ? this.resolveDiscountListForManualOverride(((_x = flatItem.bundleItem) == null ? void 0 : _x.discount_list) || []) : this.filterDiscountListByType(((_y = flatItem.bundleItem) == null ? void 0 : _y.discount_list) || [], "promotion"),
            price: isManualDiscount ? flatItem.bundleItem.price : flatItem.bundleItem.original_price,
            processed: true
          }]);
        }
        return;
      }
      if (applicableDiscounts.length && product.booking_id && typeof selectedDiscount.isManualSelect === "undefined" && !(options == null ? void 0 : options.scan) && !isEditModeAddNewProduct) {
        return;
      }
      const isNeedSplit = (selectedDiscount.tag || selectedDiscount.type) === "good_pass";
      const totalQuantity = product.quantity || product.num || 1;
      const availableGoodPassCount = applicableDiscounts.filter(
        (item) => (item.tag || item.type) === "good_pass"
      ).length;
      let maxUsageLimit = availableGoodPassCount;
      if (selectedDiscount.config && selectedDiscount.config.maxUsagePerOrder) {
        maxUsageLimit = Math.min(
          availableGoodPassCount,
          selectedDiscount.config.maxUsagePerOrder
        );
      }
      const splitCount = isNeedSplit ? Math.min(product.quantity || product.num || 1, maxUsageLimit) : 1;
      const arr = [];
      if (flatItem.type === "main") {
        if (splitCount < totalQuantity && isNeedSplit) {
          let total = product.origin_total ?? product.total;
          if ((product.discount_list || []).some((item) => item.type === "promotion")) {
            total = product.total ?? product.origin_total;
          }
          arr.push(
            this.hooks.setProduct(originProduct, {
              discount_list: this.filterDiscountListByType(product.discount_list, "promotion"),
              quantity: totalQuantity - splitCount,
              _id: product._id.split("___")[0],
              total
            })
          );
        }
        for (let i = 0; i < splitCount; i++) {
          const selectedDiscount2 = selectedDiscountCard || applicableDiscounts[i];
          usedDiscounts.set(selectedDiscount2.id, true);
          if ((selectedDiscount2.tag || selectedDiscount2.type) === "good_pass") {
            const currentCount = usedProductIdCounts.get(selectedDiscount2.product_id) || 0;
            usedProductIdCounts.set(selectedDiscount2.product_id, currentCount + 1);
          }
          const appliedProducts = appliedDiscountProducts.get(selectedDiscount2.id) || [];
          let productOriginTotal = product.origin_total || product.total || 0;
          if (this.filterDiscountListByType(product.discount_list, "promotion").length && product.origin_total) {
            productOriginTotal = product.origin_total;
          }
          if (Number(((_z = originProduct == null ? void 0 : originProduct._productInit) == null ? void 0 : _z.original_price) || 0) > 0 && product.origin_total && product.total && product.origin_total !== product.total) {
            productOriginTotal = product.total;
          }
          const isOrderLevel = (0, import_utils3.isOrderLevelFixedAmountDiscount)(selectedDiscount2);
          const orderLevelAllocation = isOrderLevel ? orderLevelDiscountAllocations.get(selectedDiscount2.id) : null;
          const productAllocation = orderLevelAllocation == null ? void 0 : orderLevelAllocation.get(flatItem._id);
          const isDeductOptionPrice = !!((_A = selectedDiscount2.config) == null ? void 0 : _A.deductOptionPrice);
          let mainProductSellingPrice;
          let amount;
          let productDiscountDifference;
          let discountedOptions = product.options;
          let optionDiscountAmount = 0;
          if (isOrderLevel && productAllocation) {
            amount = productAllocation.discountAmount;
            productDiscountDifference = productAllocation.difference;
            mainProductSellingPrice = Math.max(new import_decimal.default(product.price).minus(amount).toNumber(), 0);
          } else {
            mainProductSellingPrice = (0, import_utils.getDiscountAmount)(
              selectedDiscount2,
              product.price,
              product.price
            );
            amount = new import_decimal.default(product.price).minus(new import_decimal.default(mainProductSellingPrice)).toNumber();
          }
          if (isDeductOptionPrice && ((_B = product.options) == null ? void 0 : _B.length)) {
            const optionResult = applyDiscountToOptions(
              product.options,
              selectedDiscount2
            );
            discountedOptions = optionResult.discountedOptions;
            optionDiscountAmount = optionResult.optionDiscountAmount;
          }
          const optionsForLineTotal = isDeductOptionPrice && ((_C = product.options) == null ? void 0 : _C.length) ? discountedOptions : product.options;
          const optionsLineTotal = getOptionTotal(optionsForLineTotal || []);
          const total = new import_decimal.default(mainProductSellingPrice).plus(optionsLineTotal).toNumber();
          const mainProductDiscountAmount = amount;
          const lineDiscountAmount = new import_decimal.default(mainProductDiscountAmount).plus(optionDiscountAmount).toNumber();
          const discountType = selectedDiscount2.tag || selectedDiscount2.type;
          const isGoodPass = discountType === "good_pass";
          const discountDetail = {
            amount: lineDiscountAmount,
            type: selectedDiscount2.tag === "product_discount_card" ? "discount_card" : discountType,
            discount: {
              discount_card_type: (_D = selectedDiscount2 == null ? void 0 : selectedDiscount2.metadata) == null ? void 0 : _D.discount_card_type,
              fixed_amount: lineDiscountAmount,
              discount_calculation_mode: (_E = selectedDiscount2 == null ? void 0 : selectedDiscount2.metadata) == null ? void 0 : _E.discount_calculation_mode,
              resource_id: selectedDiscount2.id,
              title: selectedDiscount2.format_title,
              original_amount: product.price,
              product_id: originProduct.id,
              percent: selectedDiscount2.par_value,
              discount_product_id: selectedDiscount2.product_id
            },
            // 前端使用的num数量，为了计算优惠金额
            _num: isGoodPass ? 1 : product.num,
            config: selectedDiscount2 == null ? void 0 : selectedDiscount2.config,
            metadata: {
              num: 1,
              // 🔥 order_level 分摊差值
              ...productDiscountDifference !== void 0 && { product_discount_difference: productDiscountDifference },
              /** 仅主商品上的优惠金额（不含 option） */
              mainProductDiscountAmount,
              optionDiscountAmount
            }
          };
          appliedProducts.push(discountDetail);
          appliedDiscountProducts.set(selectedDiscount2.id, appliedProducts);
          if (product.isClient) {
            arr.push(
              this.hooks.setProduct(originProduct, {
                discount_list: [discountDetail],
                // good_pass：主商品价以折后价为准；勿用 product.price - amount（amount 含 option 优惠时会算错）
                price: isGoodPass ? mainProductSellingPrice : product.price,
                quantity: isNeedSplit ? 1 : product.quantity,
                origin_total: (0, import_utils2.getProductOriginTotalPrice)({
                  product: {
                    original_price: product.original_price
                  },
                  bundle: product.bundle,
                  options: restoreOptionPrices(product.options)
                }),
                variant: originProduct._productInit.variant,
                original_price: new import_decimal.default(product.price || 0).toNumber(),
                total,
                options: discountedOptions
              })
            );
          } else {
            arr.push(
              this.hooks.setProduct(originProduct, {
                discount_list: this.filterDiscountListByType(product.discount_list, "promotion").concat([discountDetail]),
                _id: product._id.split("___")[0] + "___" + selectedDiscount2.id + index,
                price: selectedDiscount2.tag === "good_pass" ? 0 : product.price,
                quantity: isNeedSplit ? 1 : product.quantity,
                total,
                origin_total: productOriginTotal,
                main_product_selling_price: mainProductSellingPrice,
                options: discountedOptions
              })
            );
          }
        }
        processedProductsMap.set(product._id, arr);
      } else {
        const processedItems = [];
        if (isNeedSplit) {
          const discountNum = splitCount;
          const normalNum = totalQuantity - discountNum;
          for (let i = 0; i < discountNum; i++) {
            const selectedDiscount2 = applicableDiscounts[i];
            usedDiscounts.set(selectedDiscount2.id, true);
            if ((selectedDiscount2.tag || selectedDiscount2.type) === "good_pass") {
              const currentCount = usedProductIdCounts.get(selectedDiscount2.product_id) || 0;
              usedProductIdCounts.set(selectedDiscount2.product_id, currentCount + 1);
            }
            const uniqueId = `${flatItem._id}_split_${i}`;
            const discountedPrice = (0, import_utils.getDiscountAmount)(
              selectedDiscount2,
              product.origin_total,
              product.origin_total
            );
            const bundleDiscountAmount = new import_decimal.default(product.origin_total || 0).minus(discountedPrice).toNumber();
            const discountDetail = {
              amount: bundleDiscountAmount,
              type: "good_pass",
              discount: {
                fixed_amount: product.origin_total,
                discount_calculation_mode: (_F = selectedDiscount2 == null ? void 0 : selectedDiscount2.metadata) == null ? void 0 : _F.discount_calculation_mode,
                resource_id: selectedDiscount2.id,
                title: selectedDiscount2.format_title,
                original_amount: product.origin_total,
                product_id: product.id,
                discount_product_id: selectedDiscount2.product_id
              },
              metadata: {
                // 🔥 使用拆分后的唯一 _id
                custom_product_bundle_map_id: uniqueId,
                num: 1
              },
              _num: 1,
              config: selectedDiscount2 == null ? void 0 : selectedDiscount2.config
            };
            const appliedProducts = appliedDiscountProducts.get(selectedDiscount2.id) || [];
            appliedProducts.push(discountDetail);
            appliedDiscountProducts.set(selectedDiscount2.id, appliedProducts);
            processedItems.push({
              ...flatItem,
              // 🔥 使用唯一的 _id
              _id: uniqueId,
              num: 1,
              quantity: 1,
              price: discountedPrice,
              // 折扣后的价格
              total: discountedPrice,
              discount_list: [discountDetail],
              processed: true,
              _discountId: selectedDiscount2.id
            });
          }
          if (normalNum > 0) {
            processedItems.push({
              ...flatItem,
              // 🔥 为剩余商品生成唯一的 _id
              _id: `${flatItem._id}_split_rest`,
              num: normalNum,
              quantity: normalNum,
              discount_list: [],
              processed: true
            });
          }
        } else {
          const selectedDiscount2 = selectedDiscountCard || applicableDiscounts[0];
          usedDiscounts.set(selectedDiscount2.id, true);
          if ((selectedDiscount2.tag || selectedDiscount2.type) === "good_pass") {
            const currentCount = usedProductIdCounts.get(selectedDiscount2.product_id) || 0;
            usedProductIdCounts.set(selectedDiscount2.product_id, currentCount + 1);
          }
          const productOriginTotal = product.original_price || product.price || 0;
          const isOrderLevel = (0, import_utils3.isOrderLevelFixedAmountDiscount)(selectedDiscount2);
          const orderLevelAllocation = isOrderLevel ? orderLevelDiscountAllocations.get(selectedDiscount2.id) : null;
          const productAllocation = orderLevelAllocation == null ? void 0 : orderLevelAllocation.get(flatItem._id);
          let targetProductTotal;
          let fixedAmountPerItem;
          let productDiscountDifference;
          if (isOrderLevel && productAllocation) {
            fixedAmountPerItem = productAllocation.discountAmount;
            productDiscountDifference = productAllocation.difference;
            targetProductTotal = Math.max(new import_decimal.default(productOriginTotal).minus(fixedAmountPerItem).toNumber(), 0);
          } else {
            targetProductTotal = (0, import_utils.getDiscountAmount)(
              selectedDiscount2,
              productOriginTotal,
              productOriginTotal
            );
            fixedAmountPerItem = new import_decimal.default(productOriginTotal).minus(targetProductTotal).toNumber();
          }
          const uniqueId = flatItem._id;
          const discountDetail = {
            amount: fixedAmountPerItem * (product.num || 1),
            type: selectedDiscount2.tag === "product_discount_card" ? "discount_card" : selectedDiscount2.tag,
            discount: {
              discount_card_type: (_G = selectedDiscount2 == null ? void 0 : selectedDiscount2.metadata) == null ? void 0 : _G.discount_card_type,
              fixed_amount: fixedAmountPerItem,
              discount_calculation_mode: (_H = selectedDiscount2 == null ? void 0 : selectedDiscount2.metadata) == null ? void 0 : _H.discount_calculation_mode,
              resource_id: selectedDiscount2.id,
              title: selectedDiscount2.format_title,
              original_amount: product.original_price,
              product_id: product.id,
              percent: selectedDiscount2.par_value,
              discount_product_id: selectedDiscount2.product_id
            },
            metadata: {
              // 🔥 使用唯一的 _id
              custom_product_bundle_map_id: uniqueId,
              num: product.num || 1,
              // 🔥 order_level 分摊差值
              ...productDiscountDifference !== void 0 && { product_discount_difference: productDiscountDifference }
            },
            config: selectedDiscount2 == null ? void 0 : selectedDiscount2.config,
            _num: (product.num || 1) * (((_I = flatItem == null ? void 0 : flatItem.parentProduct) == null ? void 0 : _I.num) || 1)
          };
          const appliedProducts = appliedDiscountProducts.get(selectedDiscount2.id) || [];
          appliedProducts.push(discountDetail);
          appliedDiscountProducts.set(selectedDiscount2.id, appliedProducts);
          processedItems.push({
            ...flatItem,
            total: targetProductTotal,
            price: new import_decimal.default(productOriginTotal || 0).minus(fixedAmountPerItem).toNumber(),
            discount_list: [discountDetail],
            processed: true
          });
        }
        processedFlatItemsMap.set(flatItem._id, processedItems);
      }
    });
    const reconstructProductsWithBundle = (processedProductsMap2, processedFlatItemsMap2, originalProductList) => {
      const result = [];
      originalProductList.forEach((originProduct) => {
        const product = this.hooks.getProduct(originProduct);
        const mainProductArr = processedProductsMap2.get(product._id);
        if (!mainProductArr || mainProductArr.length === 0) {
          const getDefaultProduct = () => {
            const restoredOptions = restoreOptionPrices(product.options);
            if (product.isClient) {
              return this.hooks.setProduct(originProduct, {
                discount_list: this.filterDiscountListByType(product.discount_list, "promotion"),
                price: product.price,
                origin_total: (0, import_utils2.getProductOriginTotalPrice)({
                  product: {
                    original_price: product.original_price
                  },
                  bundle: product.bundle,
                  options: restoredOptions
                }),
                variant: originProduct._productInit.variant,
                original_price: originProduct._productInit.original_price,
                total: (0, import_utils2.getProductTotalPrice)({
                  product: {
                    price: product.price
                  },
                  bundle: product.bundle,
                  options: restoredOptions
                }),
                options: restoredOptions
              });
            } else {
              return this.hooks.setProduct(originProduct, {
                discount_list: this.filterDiscountListByType(product.discount_list, "promotion"),
                total: product.total,
                origin_total: product.origin_total,
                price: product.price,
                options: restoreOptionPrices(product.options)
              });
            }
          };
          result.push(getDefaultProduct());
          return;
        }
        const hasBundle = product.bundle && Array.isArray(product.bundle) && product.bundle.length > 0;
        if (!hasBundle) {
          result.push(...mainProductArr);
        } else {
          const bundleProcessingInfo = /* @__PURE__ */ new Map();
          let hasGoodPassApplied = false;
          if (product.bundle && Array.isArray(product.bundle)) {
            product.bundle.forEach((bundleItem, bundleIndex) => {
              const bundleItemId = `${product._id}_bundle_${bundleIndex}`;
              const processedBundleItems = processedFlatItemsMap2.get(bundleItemId);
              if (!processedBundleItems || processedBundleItems.length === 0) {
                bundleProcessingInfo.set(bundleIndex, [bundleItem]);
              } else {
                bundleProcessingInfo.set(bundleIndex, processedBundleItems);
                const hasGoodPass = processedBundleItems.some(
                  (item) => {
                    var _a2;
                    return (_a2 = item.discount_list) == null ? void 0 : _a2.some(
                      (discount) => discount.type === "good_pass" || discount.tag === "good_pass"
                    );
                  }
                );
                if (hasGoodPass) {
                  hasGoodPassApplied = true;
                }
              }
            });
          }
          const mainProductQuantity = mainProductArr[0] ? this.hooks.getProduct(mainProductArr[0]).quantity : 1;
          if (hasGoodPassApplied && mainProductArr.length === 1 && mainProductQuantity > 1) {
            const mainProduct = mainProductArr[0];
            const mainProductData = this.hooks.getProduct(mainProduct);
            const newBundleWithDiscount = [];
            (product.bundle || []).forEach(
              (bundleItem, bundleIndex) => {
                const processedItems = bundleProcessingInfo.get(
                  bundleIndex
                ) || [bundleItem];
                if (processedItems.length > 1) {
                  processedItems.forEach((item) => {
                    const updatedDiscountList2 = (item.discount_list || []).map((discount) => {
                      var _a2;
                      return {
                        ...discount,
                        metadata: {
                          ...discount.metadata,
                          num: item.num,
                          custom_product_bundle_map_id: (_a2 = item.metadata) == null ? void 0 : _a2.custom_product_bundle_map_id
                        }
                        // num: item.num, // 使用拆分后的 num
                      };
                    });
                    newBundleWithDiscount.push({
                      ...bundleItem,
                      _id: item._id,
                      product_id: bundleItem.product_id,
                      price: item.price,
                      num: item.num,
                      discount_list: updatedDiscountList2
                    });
                  });
                } else {
                  const item = processedItems[0];
                  if (item.processed) {
                    const updatedDiscountList2 = (item.discount_list || []).map((discount) => {
                      var _a2;
                      return {
                        ...discount,
                        metadata: {
                          ...discount.metadata,
                          num: item.num,
                          custom_product_bundle_map_id: (_a2 = item.metadata) == null ? void 0 : _a2.custom_product_bundle_map_id
                        }
                        // num: item.num, // 使用当前的 num
                      };
                    });
                    newBundleWithDiscount.push({
                      ...bundleItem,
                      _id: item._id,
                      product_id: bundleItem.product_id,
                      price: item.price,
                      num: item.num,
                      discount_list: updatedDiscountList2
                    });
                  } else {
                    newBundleWithDiscount.push(item);
                  }
                }
              }
            );
            let newTotalWithDiscount = Number(mainProductData.price || 0);
            let newOriginTotalWithDiscount = Number(
              mainProductData.original_price || mainProductData.price || 0
            );
            const updatedMainDiscountList = mainProductData.discount_list.map((discount) => {
              var _a2, _b;
              if ((_a2 = discount == null ? void 0 : discount.metadata) == null ? void 0 : _a2.custom_product_bundle_map_id) {
                return discount;
              }
              return {
                ...discount,
                // num: 1,
                metadata: {
                  ...discount.metadata,
                  custom_product_bundle_map_id: (_b = discount == null ? void 0 : discount.metadata) == null ? void 0 : _b.custom_product_bundle_map_id,
                  num: 1
                }
              };
            });
            const mainDiscountList = updatedMainDiscountList.filter(
              (item) => {
                var _a2;
                return !((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.custom_product_bundle_map_id);
              }
            );
            if (mainDiscountList && mainDiscountList.length > 0) {
              const allDiscountAmount = (0, import_utils.getDiscountListAmountTotal)(mainDiscountList);
              newTotalWithDiscount = new import_decimal.default(mainProductData.price || 0).minus(allDiscountAmount).toNumber() ?? newTotalWithDiscount;
              newOriginTotalWithDiscount = mainProductData.origin_total ?? newOriginTotalWithDiscount;
            }
            if (newBundleWithDiscount.length > 0) {
              newBundleWithDiscount.forEach((item) => {
                newTotalWithDiscount += Number(item.price) * Number(item.num);
              });
              newBundleWithDiscount.forEach((item) => {
                var _a2, _b, _c;
                const originalPrice = ((_c = (_b = (_a2 = item.discount_list) == null ? void 0 : _a2[0]) == null ? void 0 : _b.discount) == null ? void 0 : _c.original_amount) || item.price;
                newOriginTotalWithDiscount += Number(originalPrice) * Number(item.num);
              });
            }
            if (product == null ? void 0 : product.options) {
              newTotalWithDiscount = product.options.reduce((accumulator, currentValue) => {
                const currentPrice = new import_decimal.default(currentValue.price || 0);
                const currentNum = new import_decimal.default(currentValue.num || 0);
                return accumulator.add(currentPrice.mul(currentNum));
              }, new import_decimal.default(newTotalWithDiscount)).toNumber();
            }
            result.push(
              this.hooks.setProduct(mainProduct, {
                ...mainProductData,
                _id: `${mainProductData._id.split("___")[0]}___split_discount`,
                quantity: 1,
                discount_list: updatedMainDiscountList,
                bundle: newBundleWithDiscount,
                total: new import_decimal.default(newTotalWithDiscount).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber(),
                origin_total: new import_decimal.default(newOriginTotalWithDiscount).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber()
              })
            );
            if (mainProductQuantity > 1) {
              const newBundleOriginal = [];
              (product.bundle || []).forEach(
                (bundleItem, bundleIndex) => {
                  newBundleOriginal.push({
                    ...bundleItem,
                    discount_list: []
                  });
                }
              );
              let newTotalOriginal = Number(mainProductData.price || 0);
              let newOriginTotalOriginal = Number(
                mainProductData.original_price || mainProductData.price || 0
              );
              const updatedMainDiscountListOriginal = mainProductData.discount_list.map((discount) => {
                var _a2, _b;
                if ((_a2 = discount == null ? void 0 : discount.metadata) == null ? void 0 : _a2.custom_product_bundle_map_id) {
                  return discount;
                }
                return {
                  ...discount,
                  metadata: {
                    ...discount.metadata,
                    num: mainProductQuantity - 1,
                    custom_product_bundle_map_id: (_b = discount == null ? void 0 : discount.metadata) == null ? void 0 : _b.custom_product_bundle_map_id
                  }
                  // num: mainProductQuantity - 1,
                };
              });
              const mainDiscountListOriginal = updatedMainDiscountListOriginal.filter(
                (item) => {
                  var _a2;
                  return !((_a2 = item == null ? void 0 : item.metadata) == null ? void 0 : _a2.custom_product_bundle_map_id);
                }
              );
              if (mainDiscountListOriginal && mainDiscountListOriginal.length > 0) {
                const allDiscountAmount = (0, import_utils.getDiscountListAmount)(
                  mainDiscountListOriginal
                );
                newTotalOriginal = new import_decimal.default(mainProductData.price || 0).minus(allDiscountAmount).toNumber() ?? newTotalOriginal;
                newOriginTotalOriginal = mainProductData.origin_total ?? newOriginTotalOriginal;
              }
              if (newBundleOriginal.length > 0) {
                newBundleOriginal.forEach((item) => {
                  newTotalOriginal += Number(item.price) * Number(item.num);
                  newOriginTotalOriginal += Number(item.price) * Number(item.num);
                });
              }
              if (product == null ? void 0 : product.options) {
                newTotalOriginal = product.options.reduce((accumulator, currentValue) => {
                  const currentPrice = new import_decimal.default(currentValue.price || 0);
                  const currentNum = new import_decimal.default(currentValue.num || 0);
                  return accumulator.add(currentPrice.mul(currentNum));
                }, new import_decimal.default(newTotalOriginal)).toNumber();
              }
              newTotalOriginal = new import_decimal.default(newTotalOriginal).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
              newOriginTotalOriginal = new import_decimal.default(newOriginTotalOriginal).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
              result.push(
                this.hooks.setProduct(mainProduct, {
                  ...mainProductData,
                  _id: `${mainProductData._id.split("___")[0]}___split_normal`,
                  quantity: mainProductQuantity - 1,
                  discount_list: updatedMainDiscountListOriginal,
                  bundle: newBundleOriginal,
                  total: newTotalOriginal,
                  origin_total: newOriginTotalOriginal
                })
              );
            }
          } else {
            mainProductArr.forEach((mainProduct) => {
              var _a2, _b, _c;
              const mainProductData = this.hooks.getProduct(mainProduct);
              const newBundle = [];
              if (product.bundle && Array.isArray(product.bundle)) {
                product.bundle.forEach((bundleItem, bundleIndex) => {
                  const bundleItemId = `${product._id}_bundle_${bundleIndex}`;
                  const processedBundleItems = processedFlatItemsMap2.get(bundleItemId);
                  if (!processedBundleItems || processedBundleItems.length === 0) {
                    newBundle.push(bundleItem);
                  } else {
                    processedBundleItems.forEach((item) => {
                      const nextBundlePrice = item.price ?? bundleItem.price;
                      const nextBundleSellingPrice = item.bundle_selling_price ?? item.price ?? bundleItem.bundle_selling_price;
                      const updatedDiscountList2 = (item.discount_list || []).map((discount) => {
                        var _a3;
                        return {
                          ...discount,
                          metadata: {
                            ...discount.metadata,
                            num: item.num,
                            custom_product_bundle_map_id: (_a3 = discount == null ? void 0 : discount.metadata) == null ? void 0 : _a3.custom_product_bundle_map_id
                          }
                          // num: item.num, // 使用拆分后的 num
                        };
                      });
                      newBundle.push({
                        ...bundleItem,
                        _id: item._id,
                        product_id: bundleItem.product_id,
                        price: nextBundlePrice,
                        num: item.num,
                        discount_list: updatedDiscountList2,
                        bundle_selling_price: bundleItem.bundle_selling_price !== void 0 ? nextBundleSellingPrice : void 0
                      });
                    });
                  }
                });
              }
              const mainSellingPrice = mainProductData.main_product_selling_price ?? mainProductData.price ?? 0;
              let newTotal = Number(mainSellingPrice || 0);
              let newOriginTotal = Number(mainProductData.original_price || mainProductData.price || 0);
              const isManualDiscount = typeof mainProductData.isManualDiscount === "boolean" ? mainProductData.isManualDiscount : mainProductData.total != mainProductData.origin_total && (!((_a2 = mainProductData.discount_list) == null ? void 0 : _a2.length) || ((_c = (_b = mainProductData == null ? void 0 : mainProductData.discount_list) == null ? void 0 : _b.every) == null ? void 0 : _c.call(_b, (item) => item.type === "product")));
              if (isManualDiscount) {
                newTotal = mainProductData.total ?? newTotal;
                newOriginTotal = mainProductData.origin_total ?? newOriginTotal;
              } else {
                if (newBundle.length > 0) {
                  newBundle.forEach((item) => {
                    const bundleSellingPrice = item.bundle_selling_price ?? item.price;
                    newTotal += Number(bundleSellingPrice) * Number(item.num);
                  });
                  newBundle.forEach((item) => {
                    var _a3, _b2, _c2;
                    const originalPrice = ((_c2 = (_b2 = (_a3 = item.discount_list) == null ? void 0 : _a3[0]) == null ? void 0 : _b2.discount) == null ? void 0 : _c2.original_amount) || item.price;
                    newOriginTotal += Number(originalPrice) * Number(item.num);
                  });
                }
              }
              if (product == null ? void 0 : product.options) {
                newTotal = product.options.reduce((accumulator, currentValue) => {
                  const currentPrice = new import_decimal.default(currentValue.price || 0);
                  const currentNum = new import_decimal.default(currentValue.num || 0);
                  return accumulator.add(currentPrice.mul(currentNum));
                }, new import_decimal.default(newTotal)).toNumber();
              }
              newTotal = new import_decimal.default(newTotal).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
              newOriginTotal = new import_decimal.default(newOriginTotal).toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
              result.push(
                this.hooks.setProduct(mainProduct, {
                  ...mainProductData,
                  bundle: newBundle,
                  total: newTotal,
                  origin_total: newOriginTotal
                })
              );
            });
          }
        }
      });
      return result;
    };
    const processedProductList = reconstructProductsWithBundle(
      processedProductsMap,
      processedFlatItemsMap,
      productList
    );
    const updatedDiscountList = addModeDiscount.map((discount) => {
      const applicableProducts = discountApplicability.get(discount.id) || [];
      const applicableProductDetails = discountApplicableProducts.get(discount.id) || [];
      const appliedProductDetails = appliedDiscountProducts.get(discount.id) || [];
      const isAvailable = applicableProducts.length > 0;
      if (typeof discount.isSelected === "boolean" && discount.isSelected === false && discount.isManualSelect) {
        return {
          ...discount,
          isSelected: false,
          isAvailable,
          // 正确设置可用性
          applicableProductIds: applicableProducts,
          // 添加可抵扣的商品详情
          applicableProductDetails,
          // 添加实际抵扣的商品详情（对于未选中的优惠券，为空数组）
          appliedProductDetails: []
        };
      }
      if (usedDiscounts.get(discount.id)) {
        return {
          ...discount,
          isSelected: true,
          isManualSelect: (options == null ? void 0 : options.scan) ? false : discount.isManualSelect,
          // 标记为可用，因为它已被应用
          isAvailable: true,
          // 记录适用的商品IDs
          applicableProductIds: applicableProducts,
          // 添加可抵扣的商品详情
          applicableProductDetails,
          // 添加实际抵扣的商品详情
          appliedProductDetails
        };
      }
      let isSelected = typeof discount.isSelected === "boolean" ? discount.isSelected : void 0;
      if (isAvailable && appliedProductDetails.length && !discount.isManualSelect) {
        isSelected = true;
      } else if (!appliedProductDetails.length) {
        isSelected = false;
      }
      return {
        ...discount,
        // 如果有适用的商品，标记为可用
        isAvailable,
        isSelected,
        // 如果是扫码进来的，要手动设置为手动选择：false
        isManualSelect: (options == null ? void 0 : options.scan) ? false : discount.isManualSelect,
        // 记录适用的商品IDs
        applicableProductIds: applicableProducts,
        // 添加可抵扣的商品详情
        applicableProductDetails,
        // 添加实际抵扣的商品详情（对于未使用的优惠券，为空数组）
        appliedProductDetails: []
      };
    });
    return {
      productList: processedProductList,
      discountList: [...editModeDiscount, ...updatedDiscountList]
    };
  }
  /**
   * 检查优惠是否符合 PackageSubItemUsageRules 配置
   * @param discount 优惠券
   * @param flatItem 扁平化后的商品项（可能是主商品或bundle子商品）
   * @returns 是否可用
   */
  checkPackageSubItemUsageRules(discount, flatItem) {
    var _a, _b, _c, _d, _e, _f, _g;
    const limitedData = discount.limited_relation_product_data;
    const usageRules = limitedData == null ? void 0 : limitedData.package_sub_item_usage_rules;
    const rules = ["original_price", ...(usageRules == null ? void 0 : usageRules.rules) || []];
    if (!usageRules) {
      return true;
    }
    const ruleType = usageRules.type;
    const packageScope = usageRules == null ? void 0 : usageRules.package_scope;
    const { type: scopeType, exclude_bundle_product_ids = [], include_bundle_product_ids = [], filter = 0 } = packageScope || {};
    const isMainProduct = flatItem.type === "main";
    const isBundleItem = flatItem.type === "bundle";
    if (isMainProduct) {
      return true;
    }
    if (ruleType === "universal_discount") {
      if (isMainProduct) {
        return true;
      }
      if (isBundleItem) {
        const priceType = (_a = flatItem.bundleItem) == null ? void 0 : _a.price_type;
        const priceTypeExt = (_b = flatItem.bundleItem) == null ? void 0 : _b.price_type_ext;
        const mainProductId = ((_d = (_c = flatItem == null ? void 0 : flatItem.originProduct) == null ? void 0 : _c._productOrigin) == null ? void 0 : _d.id) || ((_e = flatItem == null ? void 0 : flatItem.parentProduct) == null ? void 0 : _e.id) || 0;
        const isOriginalPrice = priceType === "markup" && priceTypeExt === "product_price";
        const isMarkupPrice = priceType === "markup" && (priceTypeExt === "" || !priceTypeExt);
        if (rules.length > 0) {
          const _isOriginalPrice = isOriginalPrice && rules.includes("original_price");
          const _isMarkupPrice = isMarkupPrice && rules.includes("markup_price");
          const isPriceValid = _isOriginalPrice || _isMarkupPrice;
          let isScopeValid = false;
          if (scopeType === "all_packages" || scopeType === "product_all") {
            if (!filter) {
              isScopeValid = true;
            } else {
              isScopeValid = !exclude_bundle_product_ids.includes(Number(mainProductId));
            }
          }
          if (scopeType === "specific_packages" || scopeType === "products") {
            isScopeValid = include_bundle_product_ids.includes(Number(mainProductId));
          }
          if (isPriceValid && isScopeValid) {
            return true;
          }
          return false;
        }
        return isOriginalPrice;
      }
      return true;
    }
    if (ruleType === "package_exclusive") {
      if (isMainProduct) {
        return false;
      }
      if (isBundleItem) {
        const priceType = (_f = flatItem.bundleItem) == null ? void 0 : _f.price_type;
        const priceTypeExt = (_g = flatItem.bundleItem) == null ? void 0 : _g.price_type_ext;
        const isOriginalPrice = priceType === "markup" && priceTypeExt === "product_price";
        const isMarkupPrice = priceType === "markup" && (priceTypeExt === "" || !priceTypeExt);
        if (rules.length > 0) {
          if (isOriginalPrice && rules.includes("original_price")) {
            return true;
          }
          if (isMarkupPrice && rules.includes("markup_price")) {
            return true;
          }
          return false;
        }
        return isOriginalPrice;
      }
      return false;
    }
    if (ruleType === "single_item_promo") {
      return isMainProduct;
    }
    return true;
  }
  async destroy() {
    this.core.effects.offByModuleDestroy(this.name);
    await this.core.effects.emit(`${this.name}:onDestroy`, {});
    console.log("[Rules] 已销毁");
  }
  async clear() {
    console.log("[Rules] clear");
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  RulesModule
});
