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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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 { isNormalProduct } from "../../Product/utils";
import { getDiscountAmount } from "../../../solution/ShopDiscount/utils";
import { calcDiscountListDifference } from "../../Summary/utils";
import { getBundleSellingMagnitude } from "../../Order/utils";

/** 与 Rules / ShopDiscount 一致的折扣入参，用于主价与 option 单价 */
var toDiscountPayload = function toDiscountPayload(discountItem) {
  var _discountItem$discoun, _discountItem$discoun2;
  return {
    amount: discountItem.amount,
    tag: discountItem.type,
    par_value: (_discountItem$discoun = discountItem.discount) === null || _discountItem$discoun === void 0 ? void 0 : _discountItem$discoun.percent,
    config: discountItem.config,
    metadata: {
      discount_card_type: discountItem === null || discountItem === void 0 || (_discountItem$discoun2 = discountItem.discount) === null || _discountItem$discoun2 === void 0 ? void 0 : _discountItem$discoun2.discount_card_type
    }
  };
};

/**
 * @title 处理组合商品
 * @description 组合商品需要直接修改 product 里的价格和 is_charge_tax
 * @param product 商品
 * @returns 处理后的商品
 */
export var handleVariantProduct = function handleVariantProduct(product) {
  // 判断组合商品，然后直接修改 product 里的价格和 is_charge_tax
  if (product !== null && product !== void 0 && product.product_variant_id) {
    var _product$variant;
    // 还需要判断 能从 variant 里找到对应的组合规格信息，才可以替换
    var targetVariant = product === null || product === void 0 || (_product$variant = product.variant) === null || _product$variant === void 0 ? void 0 : _product$variant.find(function (n) {
      return n.id === product.product_variant_id;
    });
    if (targetVariant) {
      product.price = targetVariant.price;
      // 如果 original_price 为 0，就不改了
      if (Number(targetVariant.original_price) > 0) {
        product.original_price = targetVariant.original_price;
      }
      product.is_charge_tax = targetVariant.is_charge_tax;
    }
  }
  return product;
};

/**
 * 格式化商品到购物车
 * @param product 商品
 * @returns 格式化后的商品
 */
export var formatProductToCartItem = function formatProductToCartItem(params) {
  var _product$custom_depos;
  console.log('formatProductToCartItem>>>>>>', params);
  var cartItem = params.cartItem,
    product = params.product,
    bundle = params.bundle,
    options = params.options,
    product_variant_id = params.product_variant_id,
    _params$quantity = params.quantity,
    quantity = _params$quantity === void 0 ? 1 : _params$quantity,
    discounts = params.discounts;
  var num = quantity; // 当前按照单个商品加入购物车

  if (product) {
    cartItem.id = product === null || product === void 0 ? void 0 : product.id;
    cartItem.name = product === null || product === void 0 ? void 0 : product.title;
    cartItem.price = product === null || product === void 0 ? void 0 : product.price;
    cartItem.num = num;
    cartItem.total = getProductTotalPrice({
      product: product,
      bundle: bundle,
      options: options,
      num: num,
      discounts: discounts
    });
    cartItem.totalDifference = getTotalDifference({
      product: product,
      bundle: bundle,
      discounts: discounts
    });
    cartItem.summaryTotal = cartItem.total * (num || 1);
    cartItem.origin_total = getProductOriginTotalPrice({
      product: product,
      bundle: bundle,
      options: options,
      num: num,
      discounts: discounts
    });
    // 不包含折扣卡商品券的总价
    var origin_total = getProductTotalPrice({
      product: cartItem._productInit || cartItem._productOrigin,
      bundle: bundle,
      options: options,
      num: num,
      discounts: []
    });
    cartItem.summaryOriginTotal = (origin_total || 0) * (num || 1);
    cartItem.image = product === null || product === void 0 ? void 0 : product.cover;
    cartItem.like_status = 'common';
    cartItem.duration = product === null || product === void 0 ? void 0 : product.duration;
    cartItem.isNormalProduct = isNormalProduct(product);
    cartItem.is_charge_tax = product === null || product === void 0 ? void 0 : product.is_charge_tax;
  }
  if (bundle !== null && bundle !== void 0 && bundle.length) {
    cartItem.bundle = formatBundle(bundle);
  }
  if (options !== null && options !== void 0 && options.length) {
    cartItem.options = formatOptions(options);
  }
  // 拼装出 product_option_string
  if (product_variant_id) {
    var _product$variant2;
    var sku_key = product === null || product === void 0 || (_product$variant2 = product.variant) === null || _product$variant2 === void 0 || (_product$variant2 = _product$variant2.find(function (n) {
      return n.id === product_variant_id;
    })) === null || _product$variant2 === void 0 ? void 0 : _product$variant2.sku_key;
    if (sku_key) {
      var sku_key_arr = sku_key.split('_');
      var product_option_string = [];
      sku_key_arr.forEach(function (item) {
        var _product$variant_grou, _targetVariantGroup$v;
        var keyMap = item.split(':');
        var targetVariantGroup = product === null || product === void 0 || (_product$variant_grou = product.variant_group) === null || _product$variant_grou === void 0 ? void 0 : _product$variant_grou.find(function (n) {
          return String(n.position_id) === keyMap[0];
        });
        var targetVariantItem = targetVariantGroup === null || targetVariantGroup === void 0 || (_targetVariantGroup$v = targetVariantGroup.variant_item) === null || _targetVariantGroup$v === void 0 ? void 0 : _targetVariantGroup$v.find(function (n) {
          return String(n.position_id) === keyMap[1];
        });
        if (targetVariantGroup && targetVariantItem) {
          product_option_string.push("".concat(targetVariantGroup.name, ":").concat(targetVariantItem.name));
        }
      });
      cartItem.product_option_string = product_option_string.join(', ');
    }
  }

  // 如果商品有定金规则，则计算定金
  if ((product === null || product === void 0 || (_product$custom_depos = product.custom_deposit_data) === null || _product$custom_depos === void 0 ? void 0 : _product$custom_depos.has_deposit) == 1) {
    cartItem.deposit = getProductDeposit({
      cartItem: cartItem,
      product: product,
      bundle: bundle,
      options: options,
      num: num
    });
  }
  var oringin = formatProductToCartItemOrigin(params);
  cartItem._origin = oringin;
  return cartItem;
};
export var formatProductToCartItemOrigin = function formatProductToCartItemOrigin(params) {
  var _origin$product;
  var cartItem = params.cartItem,
    product = params.product,
    bundle = params.bundle,
    options = params.options,
    product_variant_id = params.product_variant_id,
    _params$quantity2 = params.quantity,
    quantity = _params$quantity2 === void 0 ? 1 : _params$quantity2;
  var origin = cartItem._origin;
  var product_discount_difference = (((_origin$product = origin.product) === null || _origin$product === void 0 ? void 0 : _origin$product.discount_list) || []).filter(function (item) {
    var _item$metadata;
    return !(item !== null && item !== void 0 && (_item$metadata = item.metadata) !== null && _item$metadata !== void 0 && _item$metadata.custom_product_bundle_map_id);
  }).reduce(function (pre, cur) {
    var _cur$metadata;
    return pre + ((cur === null || cur === void 0 || (_cur$metadata = cur.metadata) === null || _cur$metadata === void 0 ? void 0 : _cur$metadata.product_discount_difference) || 0);
  }, 0);
  if (product) {
    var _origin$product2, _origin$product3, _product$duration, _product$duration2;
    origin.product = _objectSpread(_objectSpread({}, origin.product || {}), {}, {
      num: quantity,
      product_id: product.id,
      product_variant_id: product_variant_id || 0,
      product_bundle: ((_origin$product2 = origin.product) === null || _origin$product2 === void 0 ? void 0 : _origin$product2.product_bundle) || [],
      product_sku: ((_origin$product3 = origin.product) === null || _origin$product3 === void 0 ? void 0 : _origin$product3.product_sku) || {
        option: []
      },
      metadata: {
        product_discount_difference: product_discount_difference
      }
    });
    // 时长类型
    origin.sub_type = product === null || product === void 0 || (_product$duration = product.duration) === null || _product$duration === void 0 ? void 0 : _product$duration.type;
    // 时长
    origin.duration = product === null || product === void 0 || (_product$duration2 = product.duration) === null || _product$duration2 === void 0 ? void 0 : _product$duration2.value;
    if (bundle !== null && bundle !== void 0 && bundle.length) {
      origin.product.product_bundle = formatBundleToOrigin(bundle);
    }
    if (options !== null && options !== void 0 && options.length) {
      origin.product.product_sku = _objectSpread(_objectSpread({}, origin.product.product_sku || {}), {}, {
        option: formatOptionsToOrigin(options).map(function (option) {
          var _option$add_price;
          var next = _objectSpread(_objectSpread({}, option), {}, {
            add_price: (_option$add_price = option.add_price) !== null && _option$add_price !== void 0 ? _option$add_price : option.price
          });
          delete next.price;
          return next;
        })
      });
    }
  }
  return origin;
};

/**
 * 获取商品总价
 * @description 当前总价计算基于商品数量为1
 * @param item 商品
 * @returns 商品总价
 */
export var getProductTotalPrice = function getProductTotalPrice(params) {
  var _options$map;
  var product = params.product,
    bundle = params.bundle,
    options = params.options,
    discounts = params.discounts;
  // const num = params.num || 1;
  var price = Number(product.price);

  // option 行：unit 折后价在循环中与主商品使用同一套 getDiscountAmount（含 deductOptionPrice）
  var optionRows = (_options$map = options === null || options === void 0 ? void 0 : options.map(function (currentValue) {
    var _ref, _currentValue$price, _ref2, _currentValue$num;
    return {
      unit: Number((_ref = (_currentValue$price = currentValue.price) !== null && _currentValue$price !== void 0 ? _currentValue$price : currentValue.add_price) !== null && _ref !== void 0 ? _ref : 0),
      num: Number((_ref2 = (_currentValue$num = currentValue.num) !== null && _currentValue$num !== void 0 ? _currentValue$num : currentValue.quantity) !== null && _ref2 !== void 0 ? _ref2 : 1)
    };
  })) !== null && _options$map !== void 0 ? _options$map : [];

  // 如果商品有折扣，则计算折扣
  if (discounts !== null && discounts !== void 0 && discounts.length) {
    discounts.forEach(function (currentValue) {
      var _currentValue$config;
      var payload = toDiscountPayload(currentValue);
      price = getDiscountAmount(payload, price, price);
      if (currentValue !== null && currentValue !== void 0 && (_currentValue$config = currentValue.config) !== null && _currentValue$config !== void 0 && _currentValue$config.deductOptionPrice && optionRows.length) {
        for (var i = 0; i < optionRows.length; i++) {
          var row = optionRows[i];
          optionRows[i] = _objectSpread(_objectSpread({}, row), {}, {
            unit: getDiscountAmount(payload, row.unit, row.unit)
          });
        }
      }
    });
  }
  if (bundle !== null && bundle !== void 0 && bundle.length) {
    price = bundle.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }

  // 单规格 / 加购 option
  if (optionRows.length) {
    price = optionRows.reduce(function (accumulator, row) {
      return accumulator + row.unit * row.num;
    }, price);
  }
  return Math.max(0, price);
};
var getTotalDifference = function getTotalDifference(params) {
  var bundle = params.bundle,
    discounts = params.discounts;
  var bundleDiscountList = [];
  if (bundle !== null && bundle !== void 0 && bundle.length) {
    bundle.forEach(function (currentValue) {
      bundleDiscountList.push.apply(bundleDiscountList, _toConsumableArray((currentValue === null || currentValue === void 0 ? void 0 : currentValue.discount_list) || []));
    });
  }
  var allDiscounts = [].concat(_toConsumableArray(discounts || []), bundleDiscountList);
  var productDiscountProductDiscountDifference = calcDiscountListDifference(allDiscounts);
  return productDiscountProductDiscountDifference || 0;
};

/**
 * 获取商品原始总价
 * @description 当前总价计算基于商品数量为1
 * @param item 商品
 * @returns 商品原始总价
 */
export var getProductOriginTotalPrice = function getProductOriginTotalPrice(params) {
  var product = params.product,
    bundle = params.bundle,
    options = params.options,
    discounts = params.discounts;
  var num = (params === null || params === void 0 ? void 0 : params.num) || 1;
  var price = Number(product.original_price);
  if ((isNaN(price) || price === 0) && !(discounts !== null && discounts !== void 0 && discounts.length)) {
    return undefined;
  }
  if (bundle !== null && bundle !== void 0 && bundle.length) {
    price = bundle.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }

  // 单规格
  if (options !== null && options !== void 0 && options.length) {
    price = options.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }
  return price;
};

/**
 * 格式化套餐规格信息
 * @param options 套餐规格信息
 * @returns 格式化后的套餐规格信息
 */
export var formatOptions = function formatOptions(options) {
  if (!(options !== null && options !== void 0 && options.length)) return [];
  return options.map(function (item) {
    return {
      id: item === null || item === void 0 ? void 0 : item.id,
      name: item === null || item === void 0 ? void 0 : item.name,
      num: item === null || item === void 0 ? void 0 : item.num,
      price: item === null || item === void 0 ? void 0 : item.price,
      total: item === null || item === void 0 ? void 0 : item.price,
      origin_total: item === null || item === void 0 ? void 0 : item.original_price
    };
  });
};
export var formatOptionsToOrigin = function formatOptionsToOrigin(options) {
  if (!(options !== null && options !== void 0 && options.length)) {
    return [];
  }
  return options.map(function (d) {
    return {
      num: d.num,
      option_group_item_id: d.option_group_item_id,
      option_group_id: d.option_group_id
    };
  });
};

/**
 * 格式化商品套餐信息
 * @param bundle 商品套餐信息
 * @returns 格式化后的商品套餐信息
 */
export var formatBundle = function formatBundle(bundle) {
  if (!(bundle !== null && bundle !== void 0 && bundle.length)) return [];
  return bundle.map(function (item) {
    return {
      id: item === null || item === void 0 ? void 0 : item.id,
      title: item === null || item === void 0 ? void 0 : item.title,
      num: item === null || item === void 0 ? void 0 : item.num,
      price: item === null || item === void 0 ? void 0 : item.price,
      total: item === null || item === void 0 ? void 0 : item.price,
      price_type: item === null || item === void 0 ? void 0 : item.price_type,
      original_price: item === null || item === void 0 ? void 0 : item.original_price,
      original_total: item === null || item === void 0 ? void 0 : item.original_total,
      price_type_ext: item === null || item === void 0 ? void 0 : item.price_type_ext,
      bundle_sum_price: item === null || item === void 0 ? void 0 : item.bundle_sum_price,
      bundle_sum_type: item === null || item === void 0 ? void 0 : item.bundle_sum_type,
      options: formatOptions(item === null || item === void 0 ? void 0 : item.option),
      _bundle_product_id: item._bundle_product_id,
      discount_list: item.discount_list,
      originBundleItem: item.originBundleItem || item,
      is_charge_tax: item === null || item === void 0 ? void 0 : item.is_charge_tax
    };
  });
};
export var formatBundleToOrigin = function formatBundleToOrigin(bundle) {
  if (!(bundle !== null && bundle !== void 0 && bundle.length)) return [];
  return bundle.map(function (d) {
    var _d$price, _d$price_type, _d$price_type_ext;
    var getBundleValueByKey = function getBundleValueByKey(key) {
      var _d$originBundleItem;
      return (d === null || d === void 0 ? void 0 : d[key]) || (d === null || d === void 0 || (_d$originBundleItem = d.originBundleItem) === null || _d$originBundleItem === void 0 ? void 0 : _d$originBundleItem[key]);
    };
    var product_discount_difference = ((d === null || d === void 0 ? void 0 : d.discount_list) || []).reduce(function (pre, cur) {
      var _cur$metadata2;
      return pre + ((cur === null || cur === void 0 || (_cur$metadata2 = cur.metadata) === null || _cur$metadata2 === void 0 ? void 0 : _cur$metadata2.product_discount_difference) || 0);
    }, 0);
    var normalizedBundle = _objectSpread(_objectSpread({}, d), {}, {
      // 计算 markdown 净额时只传真实毛价；若仅有 bundle_selling_price，则由 helper 当历史净额兜底。
      price: (_d$price = d === null || d === void 0 ? void 0 : d.price) !== null && _d$price !== void 0 ? _d$price : d === null || d === void 0 ? void 0 : d.custom_price,
      bundle_selling_price: d === null || d === void 0 ? void 0 : d.bundle_selling_price,
      price_type: (_d$price_type = d === null || d === void 0 ? void 0 : d.price_type) !== null && _d$price_type !== void 0 ? _d$price_type : d === null || d === void 0 ? void 0 : d.custom_price_type,
      price_type_ext: (_d$price_type_ext = d === null || d === void 0 ? void 0 : d.price_type_ext) !== null && _d$price_type_ext !== void 0 ? _d$price_type_ext : d === null || d === void 0 ? void 0 : d.custom_price_type_ext,
      option: getBundleValueByKey('option')
    });
    return {
      bundle_group_id: getBundleValueByKey('group_id'),
      bundle_id: d.id,
      bundle_product_id: getBundleValueByKey('_bundle_product_id') || getBundleValueByKey('product_id'),
      bundle_variant_id: getBundleValueByKey('bundle_variant_id'),
      num: d.num,
      extension_id: getBundleValueByKey('extension_id'),
      extension_type: getBundleValueByKey('extension_type'),
      option: formatOptionsToOrigin(getBundleValueByKey('option')),
      discount_list: d.discount_list,
      "bundle_selling_price": getBundleSellingMagnitude(normalizedBundle).toFixed(2),
      "custom_price": d === null || d === void 0 ? void 0 : d.price,
      metadata: {
        custom_product_bundle_map_id: d._id,
        product_discount_difference: product_discount_difference
      }
    };
  });
};

/**
 * 获取商品定金
 * @description 定金基于商品售价来算，最终乘商品数量
 * 1、如果套餐主商品有定金规则，则定金为：（套餐商品总售价 * 定金百分比 + 定金固定金额）* 商品数量
 * 2、如果套餐主商品没有定金规则，子商品有定金规则，则定金为：（套餐子商品售价 * 套餐子商品定金百分比 + 套餐子商品定金固定金额）* 商品数量，最终将所有子商品定金相加
 * 3、普通商品/单规格商品/组合规则商品，定金规则：（商品总售价 * 定金百分比 + 定金固定金额）* 商品数量
 * @param params 参数
 * @returns 商品定金
 */
export var getProductDeposit = function getProductDeposit(params) {
  var _product$custom_depos2;
  var cartItem = params.cartItem,
    product = params.product,
    bundle = params.bundle,
    options = params.options;
  var num = (params === null || params === void 0 ? void 0 : params.num) || 1;

  // 判定商品是否有定金规则
  if ((product === null || product === void 0 || (_product$custom_depos2 = product.custom_deposit_data) === null || _product$custom_depos2 === void 0 ? void 0 : _product$custom_depos2.has_deposit) == 1) {
    var total = new Decimal(0);
    var _ref3 = (product === null || product === void 0 ? void 0 : product.custom_deposit_data) || {},
      deposit_fixed = _ref3.deposit_fixed,
      deposit_percentage = _ref3.deposit_percentage,
      deposit_policy_data = _ref3.deposit_policy_data,
      self_deposit_policy_ids = _ref3.self_deposit_policy_ids;
    // 所有协议数据
    var allProtocols = deposit_policy_data || [];
    // 是否存在定金，主商品has_deposit为1，但是自身没有定金设置，需要判定子商品是否存在定金，如果不存在最终判定也是不存在定金
    var productHasDeposit = false;
    // 关联的定金协议id
    var protocolIds = [];

    // 判断主商品是否有定金规则
    if (typeof deposit_fixed === 'string' && typeof deposit_percentage === 'string') {
      var _handleProductDeposit = handleProductDeposit({
          depositData: product === null || product === void 0 ? void 0 : product.custom_deposit_data,
          total: cartItem.total || 0,
          num: num
        }),
        depositTotal = _handleProductDeposit.depositTotal,
        result = _handleProductDeposit.result;
      if (result) {
        total = depositTotal;
        protocolIds.push.apply(protocolIds, _toConsumableArray(self_deposit_policy_ids || []));
        productHasDeposit = true;
      }
    } else {
      // 组合规格商品
      if (product !== null && product !== void 0 && product.product_variant_id) {
        var _product$variant3;
        var variantProduct = product === null || product === void 0 || (_product$variant3 = product.variant) === null || _product$variant3 === void 0 ? void 0 : _product$variant3.find(function (item) {
          return (item === null || item === void 0 ? void 0 : item.id) === (product === null || product === void 0 ? void 0 : product.product_variant_id);
        });
        if (variantProduct) {
          var depositData = variantProduct === null || variantProduct === void 0 ? void 0 : variantProduct.custom_deposit_data;
          var _handleProductDeposit2 = handleProductDeposit({
              depositData: depositData,
              total: (cartItem === null || cartItem === void 0 ? void 0 : cartItem.total) || 0,
              num: num
            }),
            _depositTotal = _handleProductDeposit2.depositTotal,
            _result = _handleProductDeposit2.result;
          if (_result) {
            total = _depositTotal;
            protocolIds.push.apply(protocolIds, _toConsumableArray((depositData === null || depositData === void 0 ? void 0 : depositData.self_deposit_policy_ids) || []));
            productHasDeposit = true;
          }
        }
      }
      if (bundle !== null && bundle !== void 0 && bundle.length) {
        total = bundle.reduce(function (accumulator, currBundleProduct) {
          var depositData = currBundleProduct === null || currBundleProduct === void 0 ? void 0 : currBundleProduct.custom_deposit_data;
          var _handleProductDeposit3 = handleProductDeposit({
              depositData: depositData,
              total: currBundleProduct === null || currBundleProduct === void 0 ? void 0 : currBundleProduct.price,
              num: (currBundleProduct === null || currBundleProduct === void 0 ? void 0 : currBundleProduct.num) || 1
            }),
            depositTotal = _handleProductDeposit3.depositTotal,
            result = _handleProductDeposit3.result;
          if (result) {
            protocolIds.push.apply(protocolIds, _toConsumableArray((depositData === null || depositData === void 0 ? void 0 : depositData.self_deposit_policy_ids) || []));
            productHasDeposit = true;
            return accumulator.plus(depositTotal);
          }
          return accumulator;
        }, new Decimal(0));
      }
    }
    if (productHasDeposit) {
      var ids = new Set(protocolIds);
      var protocols = allProtocols.filter(function (item) {
        return ids.has(item.id);
      });
      return {
        total: total.toNumber(),
        protocols: protocols
      };
    }
    return null;
  }
  return null;
};

/**
 * 计算商品定金
 * @param params 参数
 * @returns 商品定金
 */
export var handleProductDeposit = function handleProductDeposit(params) {
  var depositData = params.depositData,
    total = params.total,
    num = params.num;
  if (!depositData) {
    return {
      result: false,
      depositTotal: new Decimal(0)
    };
  }
  var _ref4 = depositData || {},
    deposit_fixed = _ref4.deposit_fixed,
    deposit_percentage = _ref4.deposit_percentage;
  if (typeof deposit_fixed === 'string' && typeof deposit_percentage === 'string') {
    var depositFixed = Decimal(deposit_fixed || 0);
    var depositPercent = Decimal(deposit_percentage || 0);
    var productTotalPrice = Decimal(total || 0);
    var deposit = depositFixed.plus(depositPercent.times(productTotalPrice));
    return {
      depositTotal: deposit.times(num),
      result: true
    };
  }
  return {
    result: false,
    depositTotal: new Decimal(0)
  };
};