function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import Decimal from 'decimal.js';
import { formatProducts } from "../booking/info/service2/utils";
import { getProductTotalPrice } from "../booking/utils";
import { isNormalProductByDurationSchedule } from "../booking/info/service2/utils";
import { getUniqueId } from '@pisell/utils';

/**
 * @title: 格式化购物车列表
 * @description:
 * @param {any} state
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-11-28 16:52
 */
export var formatCartList = function formatCartList(state) {
  var products = state.products,
    holders = state.holders;
  return holders === null || holders === void 0 ? void 0 : holders.map(function (holder) {
    return _objectSpread(_objectSpread({}, holder), {}, {
      products: products === null || products === void 0 ? void 0 : products.filter(function (product) {
        return (product === null || product === void 0 ? void 0 : product.holder_id) === (holder === null || holder === void 0 ? void 0 : holder.key);
      })
    });
  });
};

/**
 * @title: 是否是空页面
 * @description:
 * @param {any} state
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-11-28 16:47
 */
export var isEmptyStatus = function isEmptyStatus(state) {
  var products = state.products,
    holders = state.holders,
    isOpenGroup = state.isOpenGroup;
  // 没开启分组并且没有商品数据
  if (!isOpenGroup && !(products !== null && products !== void 0 && products.length)) return true;

  // 开启分组没有holders
  if (isOpenGroup && !(holders !== null && holders !== void 0 && holders.length)) return true;
  return false;
};

/**
 * @title: 是否是商品列表页面
 * @description:
 * @param {any} state
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-11-28 17:23
 */
export var isProductList = function isProductList(state) {
  var holders = state.holders,
    isOpenGroup = state.isOpenGroup;

  // 开启分组并且有holders, 则是购物车列表
  if (isOpenGroup && holders !== null && holders !== void 0 && holders.length) return false;
  return true;
};

/**
 * @title: 格式化数据最终结果
 * @description:
 * @param {any} state
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-11-28 18:35
 */
export var formatState = function formatState(state) {
  // 默认数据格式化holder数据
  var _default = _objectSpread({}, state);
  var _carts = formatCartList(_default);
  return {
    isEmpty: isEmptyStatus(_default),
    isProductList: isProductList(_default),
    carts: _carts
  };
};

/**
 * @title: 更新商品
 * @description:
 * @param {any} newState
 * @param {any} state
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-11-28 22:30
 */
export var updateProduct = function updateProduct(state, newProducts) {
  return {
    products: newProducts,
    carts: formatCartList(_objectSpread(_objectSpread({}, state), {}, {
      products: newProducts
    }))
  };
};

/**
 * @title: 格式化服务
 * @description:
 * @param {any} service
 * @param {number} id holder_id
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-09 22:47
 */
export var formatService = function formatService(service, id) {
  return service.map(function (item) {
    return _objectSpread(_objectSpread({}, item), {}, {
      holder_id: id
    });
  });
};

/**
 * 格式化商品列表：合并相同 product_id 的商品，将 product_variant_id 设置为数组
 * @param products - 原始商品列表
 * @returns 格式化后的商品列表
 */
export var formatProductsByVariant = function formatProductsByVariant(products) {
  try {
    if (!products || !Array.isArray(products) || products.length === 0) {
      return [];
    }

    // 使用 Map 来按 product_id 分组
    var productMap = new Map();
    products.forEach(function (product) {
      var productId = product === null || product === void 0 ? void 0 : product.product_id;
      var variantId = product === null || product === void 0 ? void 0 : product.product_variant_id;
      if (!productId) {
        return;
      }
      if (productMap.has(productId)) {
        // 如果已经存在该 product_id，将 product_variant_id 添加到数组中
        var existingProduct = productMap.get(productId);

        // 确保 product_variant_id 是数组
        if (!Array.isArray(existingProduct.product_variant_id)) {
          existingProduct.product_variant_id = [existingProduct.product_variant_id];
        }

        // 添加新的 variant_id（避免重复）
        if (variantId !== undefined && !existingProduct.product_variant_id.includes(variantId)) {
          existingProduct.product_variant_id.push(variantId);
        }

        // 可选：保存原始商品列表用于后续处理
        if (!existingProduct._variants) {
          existingProduct._variants = [existingProduct];
        }
        existingProduct._variants.push(product);
      } else {
        // 第一次遇到该 product_id，创建新条目
        productMap.set(productId, _objectSpread(_objectSpread({}, product), {}, {
          product_variant_id: variantId !== undefined ? [variantId] : [],
          _variants: [product] // 保存原始商品列表
        }));
      }
    });

    // 转换 Map 为数组
    var formattedProducts = Array.from(productMap.values());
    return formattedProducts;
  } catch (error) {
    return products || [];
  }
};

/**
 * @description: 赠品将商品价格设置为0
 * @param {any} product
 * @return {*}
 */
var isGiftProductPrice = function isGiftProductPrice(product) {
  return {
    price: 0,
    origin_price: (product === null || product === void 0 ? void 0 : product.price) || 0,
    total: 0,
    origin_total: (product === null || product === void 0 ? void 0 : product.price) || 0,
    base_price: 0,
    _isGift: true
  };
};

/**
 * @description: 将赠品的组合规格的价格设置为0
 * @param {any} variant
 * @return {*}
 */
export var giftVariants = function giftVariants(variant) {
  if (!(variant !== null && variant !== void 0 && variant.length) || !Array.isArray(variant)) return [];
  return variant === null || variant === void 0 ? void 0 : variant.map(function (item) {
    return _objectSpread(_objectSpread({}, item), {}, {
      price: 0,
      base_price: 0,
      original_price: 0
    });
  });
};

/**
 * @description: 批量转换商品列表数据
 * @param {any[]} products - 商品列表
 * @param {boolean} isGift - 是否为赠品
 * @param {any[]} selectedOriginGifts - 已选择的赠品列表（用于回填数据）
 * @return {any[]} 转换后的商品列表
 */
var transformInitProductLists = function transformInitProductLists(products) {
  var isGift = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var selectedOriginGifts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  if (!products || !Array.isArray(products)) return [];
  return products === null || products === void 0 ? void 0 : products.map(function (item) {
    var _selectedGift$_extend, _selectedGift$_extend2;
    // 查找是否已经选择过该商品（用于编辑回填）
    var selectedGift = selectedOriginGifts === null || selectedOriginGifts === void 0 ? void 0 : selectedOriginGifts.find(function (gift) {
      return (gift === null || gift === void 0 ? void 0 : gift.id) === (item === null || item === void 0 ? void 0 : item.id);
    });
    var _skuValue = (selectedGift === null || selectedGift === void 0 || (_selectedGift$_extend = selectedGift._extend) === null || _selectedGift$_extend === void 0 ? void 0 : _selectedGift$_extend._skuValue) || (selectedGift === null || selectedGift === void 0 || (_selectedGift$_extend2 = selectedGift._extend) === null || _selectedGift$_extend2 === void 0 ? void 0 : _selectedGift$_extend2.skuValue) || {};
    // 赠品处理：设置价格为 0
    // let priceParams: any = {};
    var extendParams = {};
    var initExtend = {
      price: (item === null || item === void 0 ? void 0 : item.price) || 0,
      total: (item === null || item === void 0 ? void 0 : item.price) || 0,
      origin_total: (item === null || item === void 0 ? void 0 : item.origin_price) || 0,
      quantity: (item === null || item === void 0 ? void 0 : item.num) || 1
    };
    if (isGift) {
      if (selectedGift) {
        return _objectSpread(_objectSpread({}, selectedGift), {}, {
          _giftInfo: null
        });
      }

      // 赠品的 _extend 参数
      extendParams = _objectSpread(_objectSpread({}, initExtend), {}, {
        base_price: 0,
        _extend: _objectSpread({}, initExtend)
      });
    } else {
      // 普通商品的 _extend 参数
      extendParams = {
        _extend: (item === null || item === void 0 ? void 0 : item._extend) || initExtend
      };
    }
    return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, item), extendParams), _skuValue), {}, {
      _isGift: isGift,
      options: (_skuValue === null || _skuValue === void 0 ? void 0 : _skuValue.option) || [],
      num: 1,
      image: (item === null || item === void 0 ? void 0 : item.cover) || '',
      name: (item === null || item === void 0 ? void 0 : item.title) || ''
    });
  });
};
var bundlePrice = function bundlePrice(bundle) {
  var _bundle$option;
  var _prefix = (bundle === null || bundle === void 0 ? void 0 : bundle.price_type) === 'markdown' ? -1 : 1;
  var _price = new Decimal((bundle === null || bundle === void 0 ? void 0 : bundle.price) || 0).mul(_prefix).toNumber() || 0;
  if (bundle !== null && bundle !== void 0 && (_bundle$option = bundle.option) !== null && _bundle$option !== void 0 && _bundle$option.length) {
    var _bundle$option2;
    var optionPrice = bundle === null || bundle === void 0 || (_bundle$option2 = bundle.option) === null || _bundle$option2 === void 0 ? void 0 : _bundle$option2.reduce(function (acc, item) {
      return acc.add(new Decimal((item === null || item === void 0 ? void 0 : item.price) || 0).mul(new Decimal((item === null || item === void 0 ? void 0 : item.num) || 0)));
    }, new Decimal(0));
    return new Decimal(_price).add(new Decimal(optionPrice)).toNumber() || 0;
  }
  return new Decimal(_price).toNumber() || 0;
};
var transformSkuValue = function transformSkuValue(skuValue) {
  var _skuValue$bundle;
  var _bundle = skuValue === null || skuValue === void 0 || (_skuValue$bundle = skuValue.bundle) === null || _skuValue$bundle === void 0 ? void 0 : _skuValue$bundle.map(function (item) {
    return _objectSpread(_objectSpread({}, item), {}, {
      price: bundlePrice(item),
      options: (item === null || item === void 0 ? void 0 : item.option) || []
    });
  });
  return _objectSpread(_objectSpread({}, skuValue), {}, {
    options: (skuValue === null || skuValue === void 0 ? void 0 : skuValue.option) || [],
    bundle: _bundle || []
  });
};

/**
 * @description: 弹窗最大可选择数量
 * @param {any} currentItem
 * @return {*}
 */
export var getMaxAvailableCount = function getMaxAvailableCount(currentItem) {
  var products = currentItem.products,
    isGift = currentItem.isGift,
    giftInfo = currentItem.giftInfo;
  var count = (currentItem === null || currentItem === void 0 ? void 0 : currentItem.needQuantity) || 1;
  if (isGift) {
    count = (giftInfo === null || giftInfo === void 0 ? void 0 : giftInfo.giftCount) || 1;
  }
  return count;
};

/**
 * @description: 计算当前商品编辑弹窗最大可选数量
 * @param {any} product 当前商品
 * @param {any[]} selected 已选择商品
 * @param {any} currentItem 当前配置信息
 * @param {boolean} isFilterCurrentProduct 是否过滤当前商品
 * @return {*}
 */
export var getCurrentMaxProductCount = function getCurrentMaxProductCount(product, selected, currentItem) {
  var _selected2;
  var isFilterCurrentProduct = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var _maxAvailableCount = getMaxAvailableCount(currentItem);
  if (!Array.isArray(selected) || !(selected !== null && selected !== void 0 && selected.length)) return _maxAvailableCount;
  var _selectedCount = 0;
  var _selected = selected;

  // 过滤当前商品
  if (isFilterCurrentProduct) {
    _selected = (selected === null || selected === void 0 ? void 0 : selected.filter(function (item) {
      return (item === null || item === void 0 ? void 0 : item.value) !== (product === null || product === void 0 ? void 0 : product.id);
    })) || [];
  }

  // 计算已选择商品数量
  _selectedCount = (_selected2 = _selected) === null || _selected2 === void 0 ? void 0 : _selected2.reduce(function (total, item) {
    return total + ((item === null || item === void 0 ? void 0 : item.quantity) || 1);
  }, 0);

  // 计算当前商品编辑弹窗最大可选数量
  return _maxAvailableCount - _selectedCount;
};

/**
 * @description: 获取商品选中数据的初始值
 * @param {any} cacheItem 商品数据
 * @return {*}
 */
var getProductInitValue = function getProductInitValue(product, selected, currentItem) {
  var _extend$other, _product$_extend;
  if (!product) return null;
  if (isNormalProductByDurationSchedule(product)) return null;
  var _isShowEditBtn = isProductNeedSku(product);
  if (!_isShowEditBtn) return null;
  var _extend = (product === null || product === void 0 ? void 0 : product._extend) || {};
  var _session = (_extend === null || _extend === void 0 || (_extend$other = _extend.other) === null || _extend$other === void 0 ? void 0 : _extend$other.session) || {};
  var params = _objectSpread(_objectSpread({}, (_extend === null || _extend === void 0 ? void 0 : _extend.other) || {}), {}, {
    quantity: (product === null || product === void 0 || (_product$_extend = product._extend) === null || _product$_extend === void 0 ? void 0 : _product$_extend.quantity) || 1,
    maxNumber: getCurrentMaxProductCount(product, selected, currentItem)
  });
  if (_session !== null && _session !== void 0 && _session.start_at || _extend !== null && _extend !== void 0 && _extend.duration) {
    params.startEndTime = {
      startDate: _session === null || _session === void 0 ? void 0 : _session.start_at,
      endDate: _session === null || _session === void 0 ? void 0 : _session.end_at,
      duration: (_extend === null || _extend === void 0 ? void 0 : _extend.duration) || 0
    };
  }
  return params;
};

/**
 * @description: 格式化商品列表数据
 * @param {any} products 商品列表
 * @param {any} currentItem 当前配置信息
 * @return {*}
 */
export var formatProductDatas = function formatProductDatas(products, currentItem, selected) {
  if (!products || !Array.isArray(products)) return [];
  var strategyMetadata = currentItem.strategyMetadata,
    isGift = currentItem.isGift;
  var _isGift = !!isGift;
  var giftParams = {};
  return products === null || products === void 0 ? void 0 : products.map(function (item) {
    var _product$_extend2, _product$_extend4, _product$_extend5, _product$_extend6, _product$_extend7, _product$_extend8;
    var product = _objectSpread({}, item);
    // 更新other中的quantity商品数量
    if (product !== null && product !== void 0 && (_product$_extend2 = product._extend) !== null && _product$_extend2 !== void 0 && _product$_extend2.other) {
      var _product$_extend3;
      product._extend.other.quantity = (product === null || product === void 0 || (_product$_extend3 = product._extend) === null || _product$_extend3 === void 0 ? void 0 : _product$_extend3.quantity) || 1;
    }

    // 折扣信息
    var discount_list;

    // 打开商品详情选中的值
    var initValue = getProductInitValue(product, selected, currentItem);

    // 记录预约商品购物车卡片数据
    var isGeneral = !!(product !== null && product !== void 0 && (_product$_extend4 = product._extend) !== null && _product$_extend4 !== void 0 && _product$_extend4.start_date && product !== null && product !== void 0 && (_product$_extend5 = product._extend) !== null && _product$_extend5 !== void 0 && _product$_extend5.end_date);
    var _skuValue = (product === null || product === void 0 || (_product$_extend6 = product._extend) === null || _product$_extend6 === void 0 ? void 0 : _product$_extend6.skuValue) || (product === null || product === void 0 || (_product$_extend7 = product._extend) === null || _product$_extend7 === void 0 ? void 0 : _product$_extend7._skuValue) || {};
    var total = getProductTotalPrice(product);
    var originTotal = product === null || product === void 0 || (_product$_extend8 = product._extend) === null || _product$_extend8 === void 0 ? void 0 : _product$_extend8.origin_total;
    if (_isGift && !originTotal) {
      originTotal = product === null || product === void 0 ? void 0 : product._initPrice;
    }

    // 赠品处理
    if (_isGift) {
      discount_list = formatDiscountLists(product, strategyMetadata === null || strategyMetadata === void 0 ? void 0 : strategyMetadata.name);
      giftParams = {
        _initPrice: product === null || product === void 0 ? void 0 : product._initPrice,
        original_price: product === null || product === void 0 ? void 0 : product._initPrice,
        discount_list: discount_list
      };
    }
    return _objectSpread(_objectSpread(_objectSpread({}, product), giftParams), {}, {
      _extend: _objectSpread(_objectSpread({}, (product === null || product === void 0 ? void 0 : product._extend) || {}), {}, {
        _skuValue: _skuValue,
        total: Number(total) || 0,
        // 设置为undefined为了createCacheItemFromParams方法中判断原价
        origin_total: originTotal || undefined
      }),
      _id: (product === null || product === void 0 ? void 0 : product._id) || getUniqueId(),
      _isGeneral: isGeneral,
      initValue: initValue,
      // 是否是赠品标识
      _isGiftPromotion: _isGift
    });
  });
};

/**
 * @description: 更新商品列表中的某个商品
 * @param {any[]} products - 商品列表
 * @param {string} productId - 要更新的商品 ID
 * @param {any} updates - 要更新的数据
 * @return {any[]} 更新后的商品列表
 */
var updateProductInList = function updateProductInList(props) {
  try {
    var products = props.products,
      productId = props.productId,
      cacheItem = props.cacheItem;
    var _products = (products || []).map(function (item) {
      if (item.id === productId) {
        return _objectSpread(_objectSpread({}, cacheItem), {}, {
          // 增加初始价格，用于赠品处理
          _initPrice: item === null || item === void 0 ? void 0 : item._initPrice
        });
      }
      return item;
    });
    return {
      originProducts: _products
    };
  } catch (error) {
    console.error('updateProductInList error:', error);
    return {
      originProducts: [],
      cartProducts: []
    };
  }
};
var formatCartProducts = function formatCartProducts(props) {
  try {
    var products = props.products,
      currentItem = props.currentItem;
    var state = currentItem.state,
      translationOriginal = currentItem.translationOriginal;
    if (!Array.isArray(products)) return [];
    return formatProducts(products, state, false, false, false, translationOriginal);
  } catch (error) {
    return [];
  }
};

/**
 * @description: 检查商品是否需要选择规格
 * @param {any} product - 商品数据
 * @return {boolean} 是否需要选择规格
 */
var isProductNeedSku = function isProductNeedSku(product) {
  return !!(product !== null && product !== void 0 && product.is_eject);
};

/**
 * @description: 从商品列表中查找商品
 * @param {any[]} products - 商品列表
 * @param {string} productId - 商品 ID
 * @return {any} 找到的商品或 undefined
 */
var findProductById = function findProductById(products, productId) {
  var _id = (productId === null || productId === void 0 ? void 0 : productId.value) || productId;
  return (products || []).find(function (item) {
    return item.id === _id;
  });
};

/**
 * @description: 从列表中查找匹配的商品
 */
var findMatchedProductFromList = function findMatchedProductFromList(products, targetProduct) {
  if (!products || !Array.isArray(products) || !targetProduct) {
    return undefined;
  }
  var targetProductId = targetProduct.product_id || targetProduct.id;
  return products.find(function (p) {
    var pId = p.product_id || p.id;
    return pId === targetProductId;
  });
};

/**
 * @description: 提取并标准化商品的 product_variant_id 为数组
 */
var extractVariantIds = function extractVariantIds(product) {
  if (!(product !== null && product !== void 0 && product.product_variant_id)) {
    return [];
  }
  return Array.isArray(product.product_variant_id) ? product.product_variant_id : [product.product_variant_id];
};

/**
 * @description: 根据允许的规格ID列表过滤商品的 variant 数据
 */
var filterProductVariants = function filterProductVariants(product, allowedVariantIds) {
  if (!product) {
    return product;
  }
  if (!allowedVariantIds || allowedVariantIds.length === 0) {
    return product;
  }

  // 如果没有 variant 数据，直接返回原商品
  if (!product.variant || !Array.isArray(product.variant) || product.variant.length === 0) {
    return product;
  }

  // 过滤 variant 数组，只保留 ID 在允许列表中的规格
  var filteredVariants = product.variant.filter(function (variant) {
    return allowedVariantIds.includes(variant.id);
  });

  // 如果没有匹配的规格，返回原商品（避免弹窗显示空规格）
  if (filteredVariants.length === 0) {
    return product;
  }

  // 返回过滤后的商品数据
  return _objectSpread(_objectSpread({}, product), {}, {
    variant: filteredVariants,
    variant_count: filteredVariants.length,
    _originalVariantCount: product.variant.length // 保存原始规格数量，便于调试
  });
};

/**
 * @description: 根据过滤后的 variant 重新生成 variant_group
 */
var filterVariantGroupByVariants = function filterVariantGroupByVariants(product) {
  if (!(product !== null && product !== void 0 && product.variant_group) || !Array.isArray(product.variant_group) || product.variant_group.length === 0) {
    return product;
  }
  if (!(product !== null && product !== void 0 && product.variant) || !Array.isArray(product.variant) || product.variant.length === 0) {
    return product;
  }

  // 1. 从所有 variant 中提取使用到的规格值 ID
  var usedValueIds = new Set();
  product.variant.forEach(function (variant) {
    if (variant.sku_ids) {
      // sku_ids 格式: "7224:20158_7225:20161_7226:20165"
      // 提取所有的 value_id (冒号后面的数字)
      var matches = variant.sku_ids.match(/:\d+/g);
      if (matches) {
        matches.forEach(function (match) {
          var valueId = parseInt(match.substring(1)); // 去掉冒号
          usedValueIds.add(valueId);
        });
      }
    }
  });

  // 2. 过滤 variant_group，只保留使用到的 variant_item
  var filteredVariantGroup = product.variant_group.map(function (group) {
    if (!group.variant_item || !Array.isArray(group.variant_item)) {
      return group;
    }
    var filteredValues = group.variant_item.filter(function (value) {
      return usedValueIds.has(value.id);
    });
    return _objectSpread(_objectSpread({}, group), {}, {
      variant_item: filteredValues
    });
  }).filter(function (group) {
    return group.variant_item && group.variant_item.length > 0;
  }); // 移除空的 group

  return filteredVariantGroup || [];
};

/**
 * @description: 根据列表数据中找到匹配的商品，并提取允许的规格 ID
 */
var filterProductByPromotionRules = function filterProductByPromotionRules(product, currentItem) {
  if (!product || !(currentItem !== null && currentItem !== void 0 && currentItem.products) || !Array.isArray(currentItem.products)) {
    return product;
  }

  // 1. 从 currentItem.products 中找到匹配的商品
  var matchedProduct = findMatchedProductFromList(currentItem.products, product);
  if (!matchedProduct) {
    return product;
  }

  // 2. 提取允许的规格 ID
  var allowedVariantIds = extractVariantIds(matchedProduct);
  if (allowedVariantIds.length === 0) {
    return product;
  }

  // 3. 过滤商品规格（variant 数组）
  var filteredProduct = filterProductVariants(product, allowedVariantIds);

  // 4. 根据过滤后的 variant，重新生成 variant_group（重要！）
  // filteredProduct = filterVariantGroupByVariants(filteredProduct);

  return filteredProduct;
};

/**
 * @description: 根据 selected ID(s) 从 products 中查找对应的商品
 * @param {any[]} products - 商品列表
 * @param {string | string[]} selected - 选中的商品 ID 或 ID 数组
 * @return {any[]} 匹配的商品数组
 */
var findSelectedProductsFromList = function findSelectedProductsFromList(products, selected) {
  if (!products || !products.length || !selected) {
    return [];
  }
  if (Array.isArray(selected)) {
    var selectedProducts = products.filter(function (product) {
      return selected.includes(product === null || product === void 0 ? void 0 : product.id);
    });
    return selectedProducts;
  }
  var selectedProduct = products.find(function (product) {
    return (product === null || product === void 0 ? void 0 : product.id) === selected;
  });
  return selectedProduct ? [selectedProduct] : [];
};

/**
 * @description: 设置赠品discount_list数据
 * @param {any} product
 * @param {any} strategyName
 * @return {*}
 */
var formatDiscountLists = function formatDiscountLists(product, strategyName) {
  try {
    var _amount = Number(product === null || product === void 0 ? void 0 : product._initPrice) || 0;
    return [{
      type: 'promotion',
      amount: _amount,
      discount: {
        original_amount: _amount,
        fixed_amount: _amount,
        title: strategyName || '',
        resource_id: ''
      }
    }];
  } catch (error) {
    return [];
  }
};

// 获取纯sourceProductId
var getPureSourceProductId = function getPureSourceProductId(sourceProductId) {
  if (!sourceProductId) return '';
  if (typeof sourceProductId !== 'string') return '';
  return sourceProductId.replace(/___.*/, '');
};
export { isGiftProductPrice, transformInitProductLists, transformSkuValue, updateProductInList, isProductNeedSku, findProductById, findMatchedProductFromList, extractVariantIds, filterProductVariants, filterVariantGroupByVariants, filterProductByPromotionRules, findSelectedProductsFromList, formatDiscountLists, formatCartProducts, getPureSourceProductId };