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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 { getSurcharge, getSurchargeAmount } from "../Summary/utils";
import { getBundleSellingMagnitude, getBundleSignedUnit, getProductSkuOptions, isMarkdownBundle } from "../Order/utils";
function toDecimal(value) {
  return new Decimal(value || 0);
}
function toFixed2(value) {
  return new Decimal(value || 0).toFixed(2);
}
function toAmountFormat(value) {
  return new Decimal(value || 0).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
}
function toBackendTaxFee(value) {
  return toBcScale(value, 2);
}
function toBcScale(value, scale) {
  var factor = new Decimal(10).pow(scale);
  return new Decimal(value || 0).times(factor).toDecimalPlaces(0, Decimal.ROUND_DOWN).div(factor);
}
function bcAdd(left, right, scale) {
  return toBcScale(new Decimal(left || 0).plus(right || 0), scale);
}
function bcSub(left, right, scale) {
  return toBcScale(new Decimal(left || 0).minus(right || 0), scale);
}
function bcMul(left, right, scale) {
  return toBcScale(new Decimal(left || 0).times(right || 0), scale);
}
function bcDiv(left, right, scale) {
  var divisor = new Decimal(right || 0);
  if (divisor.eq(0)) return new Decimal(0);
  return toBcScale(new Decimal(left || 0).div(divisor), scale);
}
function getSafeNum(num) {
  if (!num || Number.isNaN(num)) return 1;
  if (num < 1) return 1;
  return Math.floor(num);
}
function getBundleUnitPrice(product) {
  var useOriginal = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var bundleItems = product.product_bundle || [];
  return bundleItems.reduce(function (sum, item) {
    var quantity = getSafeNum(item === null || item === void 0 ? void 0 : item.num);
    // markdown（减价）按带符号净额取减；markup/原价维持相加。
    var signedUnit = getBundleSignedUnit(item, {
      useOriginal: useOriginal
    });
    return sum.plus(signedUnit.times(quantity));
  }, new Decimal(0));
}

// 单商品 composite 单价（随后再乘商品数量）：
// 新语义 v2 下 `metadata.main_product_selling_price` 已经是"含 option、含主商品折扣"的主价，
// composite 单价 = main_product_selling_price + Σ(bundle_selling_price × num)。
// 不再叠加 options（会重复计算），也不再用 variant/selling_price 兜底（选项已固化进 metadata）。
function getUnitPaymentTotal(product) {
  var _product$metadata, _product$metadata2;
  var mainSelling = (_product$metadata = product.metadata) === null || _product$metadata === void 0 ? void 0 : _product$metadata.main_product_selling_price;
  var mainOriginal = (_product$metadata2 = product.metadata) === null || _product$metadata2 === void 0 ? void 0 : _product$metadata2.main_product_original_price;
  var basePrice = mainSelling !== undefined ? toDecimal(mainSelling) : mainOriginal !== undefined ? toDecimal(mainOriginal) : toDecimal(product.selling_price);
  return basePrice.plus(getBundleUnitPrice(product));
}
function getUnitOriginalTotal(product) {
  var _product$metadata3, _product$metadata4;
  var mainOriginal = (_product$metadata3 = product.metadata) === null || _product$metadata3 === void 0 ? void 0 : _product$metadata3.main_product_original_price;
  var mainSelling = (_product$metadata4 = product.metadata) === null || _product$metadata4 === void 0 ? void 0 : _product$metadata4.main_product_selling_price;
  var basePrice = mainOriginal !== undefined ? toDecimal(mainOriginal) : mainSelling !== undefined ? toDecimal(mainSelling) : toDecimal(product.original_price || product.selling_price);
  return basePrice.plus(getBundleUnitPrice(product, true));
}
function isGeneratedVoucherProduct(product) {
  var record = product;
  var metadata = (record === null || record === void 0 ? void 0 : record.metadata) || {};
  return (record === null || record === void 0 ? void 0 : record.extension_type) === 'product_voucher' || metadata.parent_order_detail_id !== undefined || metadata.gift_card_type !== undefined;
}
function buildSurchargeServiceItems(products) {
  return products.map(function (product) {
    var _product$is_charge_ta, _product$metadata5, _product$metadata6;
    var quantity = getSafeNum(product.num);
    var unitTotal = getUnitPaymentTotal(product);
    var options = getProductSkuOptions(product);
    var persistedSurchargeFee = getPersistedMainSurchargeFee(product);
    return {
      id: product.product_id,
      num: quantity,
      total: unitTotal.toNumber(),
      price: unitTotal.toNumber(),
      is_charge_tax: (_product$is_charge_ta = product.is_charge_tax) !== null && _product$is_charge_ta !== void 0 ? _product$is_charge_ta : 0,
      isCustomItem: product.product_id === null,
      _origin: product._origin || {
        product: {
          discount_list: product.discount_list || [],
          product_bundle: product.product_bundle || [],
          product_sku: product.product_sku || {
            option: options
          }
        }
      },
      bundle: product.product_bundle || [],
      option: options,
      options: options,
      relation_details: [],
      metadata: _objectSpread(_objectSpread({}, product.metadata || {}), {}, {
        __persisted_surcharge_fee: persistedSurchargeFee === null || persistedSurchargeFee === void 0 ? void 0 : persistedSurchargeFee.toFixed(2)
      }),
      start_date: ((_product$metadata5 = product.metadata) === null || _product$metadata5 === void 0 ? void 0 : _product$metadata5.start_date) || '',
      start_time: ((_product$metadata6 = product.metadata) === null || _product$metadata6 === void 0 ? void 0 : _product$metadata6.start_time) || ''
    };
  });
}
function getRelationSurchargeIds(item) {
  var _item$metadata;
  var ids = [].concat(_toConsumableArray(Array.isArray(item === null || item === void 0 ? void 0 : item.relation_surcharge_ids) ? item.relation_surcharge_ids : []), _toConsumableArray(Array.isArray(item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.relation_surcharge_ids) ? item.metadata.relation_surcharge_ids : []));
  return _toConsumableArray(new Set(ids.filter(function (id) {
    return id !== undefined && id !== null && id !== '';
  })));
}
function getSurchargeConfigId(config) {
  var _config$id;
  return (_config$id = config === null || config === void 0 ? void 0 : config.id) !== null && _config$id !== void 0 ? _config$id : config === null || config === void 0 ? void 0 : config.surcharge_id;
}
function getSurchargeConfigById(surchargeList) {
  var map = new Map();
  var _iterator = _createForOfIteratorHelper(surchargeList || []),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var config = _step.value;
      var id = getSurchargeConfigId(config);
      if (id !== undefined) map.set(id, config);
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return map;
}
function getMainSurchargeUnitAmount(product) {
  var _ref, _ref2, _record$metadata$main, _record$metadata, _record$metadata2;
  var record = product;
  return toDecimal((_ref = (_ref2 = (_record$metadata$main = (_record$metadata = record.metadata) === null || _record$metadata === void 0 ? void 0 : _record$metadata.main_product_attached_bundle_selling_price) !== null && _record$metadata$main !== void 0 ? _record$metadata$main : (_record$metadata2 = record.metadata) === null || _record$metadata2 === void 0 ? void 0 : _record$metadata2.main_product_selling_price) !== null && _ref2 !== void 0 ? _ref2 : record.selling_price) !== null && _ref !== void 0 ? _ref : 0);
}
function getBundleSurchargeUnitAmount(bundle) {
  var _ref3, _ref4, _bundle$bundle_sellin;
  return toDecimal((_ref3 = (_ref4 = (_bundle$bundle_sellin = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_selling_price) !== null && _bundle$bundle_sellin !== void 0 ? _bundle$bundle_sellin : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_sum_price) !== null && _ref4 !== void 0 ? _ref4 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref3 !== void 0 ? _ref3 : 0);
}
function getBundleProductId(bundle) {
  var _ref5, _bundle$bundle_produc;
  var id = (_ref5 = (_bundle$bundle_produc = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_product_id) !== null && _bundle$bundle_produc !== void 0 ? _bundle$bundle_produc : bundle === null || bundle === void 0 ? void 0 : bundle._bundle_product_id) !== null && _ref5 !== void 0 ? _ref5 : bundle === null || bundle === void 0 ? void 0 : bundle.product_id;
  if (id === undefined || id === null || id === '') return null;
  var parsed = Number(id);
  if (!Number.isFinite(parsed)) return null;
  return parsed;
}
function getPersistedMainSurchargeFee(product) {
  var _ref6, _product$surcharge_fe, _product$metadata7;
  if ((product === null || product === void 0 ? void 0 : product.order_detail_id) === undefined || (product === null || product === void 0 ? void 0 : product.order_detail_id) === null) return null;
  var value = (_ref6 = (_product$surcharge_fe = product === null || product === void 0 ? void 0 : product.surcharge_fee) !== null && _product$surcharge_fe !== void 0 ? _product$surcharge_fe : product === null || product === void 0 ? void 0 : product.main_product_attached_bundle_surcharge_fee) !== null && _ref6 !== void 0 ? _ref6 : product === null || product === void 0 || (_product$metadata7 = product.metadata) === null || _product$metadata7 === void 0 ? void 0 : _product$metadata7.main_product_attached_bundle_surcharge_fee;
  if (value === undefined || value === null || value === '') return null;
  return toDecimal(value);
}
function getPersistedSourceSurchargeFee(sourceItem) {
  var _sourceItem$metadata;
  var value = sourceItem === null || sourceItem === void 0 || (_sourceItem$metadata = sourceItem.metadata) === null || _sourceItem$metadata === void 0 ? void 0 : _sourceItem$metadata.__persisted_surcharge_fee;
  if (value === undefined || value === null || value === '') return null;
  return toDecimal(value);
}
function getPersistedSurchargeRemainder(item, sourceItem) {
  var _ref7, _sourceItem$metadata$, _sourceItem$metadata2, _item$metadata2;
  var value = (_ref7 = (_sourceItem$metadata$ = sourceItem === null || sourceItem === void 0 || (_sourceItem$metadata2 = sourceItem.metadata) === null || _sourceItem$metadata2 === void 0 ? void 0 : _sourceItem$metadata2.surcharge_rounding_remainder) !== null && _sourceItem$metadata$ !== void 0 ? _sourceItem$metadata$ : item === null || item === void 0 ? void 0 : item.surcharge_rounding_remainder) !== null && _ref7 !== void 0 ? _ref7 : item === null || item === void 0 || (_item$metadata2 = item.metadata) === null || _item$metadata2 === void 0 ? void 0 : _item$metadata2.surcharge_rounding_remainder;
  if (value === undefined || value === null || value === '') return null;
  return toDecimal(value);
}
function getPersistedQuantity(item, fallbackQuantity) {
  var _item$product_quantit;
  var isPersistedLine = (item === null || item === void 0 ? void 0 : item.order_detail_id) !== undefined && (item === null || item === void 0 ? void 0 : item.order_detail_id) !== null;
  if (!isPersistedLine) return new Decimal(0);
  var value = (_item$product_quantit = item === null || item === void 0 ? void 0 : item.product_quantity) !== null && _item$product_quantit !== void 0 ? _item$product_quantit : item === null || item === void 0 ? void 0 : item.quantity;
  var parsed = new Decimal(value || 0);
  if (parsed.lte(0)) return Decimal.min(fallbackQuantity, 1);
  return Decimal.min(fallbackQuantity, parsed);
}
function getPersistedBundleSurchargeFee(bundle, product) {
  var _bundle$surcharge_fee, _bundle$metadata;
  if ((bundle === null || bundle === void 0 ? void 0 : bundle.order_detail_id) === undefined && (product === null || product === void 0 ? void 0 : product.order_detail_id) === undefined) return null;
  if ((bundle === null || bundle === void 0 ? void 0 : bundle.order_detail_id) === null && (product === null || product === void 0 ? void 0 : product.order_detail_id) === null) return null;
  var value = (_bundle$surcharge_fee = bundle === null || bundle === void 0 ? void 0 : bundle.surcharge_fee) !== null && _bundle$surcharge_fee !== void 0 ? _bundle$surcharge_fee : bundle === null || bundle === void 0 || (_bundle$metadata = bundle.metadata) === null || _bundle$metadata === void 0 ? void 0 : _bundle$metadata.surcharge_fee;
  if (value === undefined || value === null || value === '') return null;
  return toDecimal(value);
}
function createSurchargeAllocationNodes(products, sourceItems) {
  var nodes = [];
  for (var productIndex = 0; productIndex < products.length; productIndex++) {
    var _product$product_id, _getPersistedSourceSu;
    var product = products[productIndex];
    var sourceItem = sourceItems[productIndex] || {};
    var productQuantity = new Decimal(getSafeNum(product.num));
    for (var bundleIndex = 0; bundleIndex < (product.product_bundle || []).length; bundleIndex++) {
      var _sourceItem$bundle, _bundle$num, _bundle$num2;
      var bundle = product.product_bundle[bundleIndex];
      if (!isBundleOriginalPrice(bundle)) continue;
      var sourceBundle = (sourceItem === null || sourceItem === void 0 || (_sourceItem$bundle = sourceItem.bundle) === null || _sourceItem$bundle === void 0 ? void 0 : _sourceItem$bundle[bundleIndex]) || {};
      nodes.push({
        kind: 'bundle',
        target: bundle,
        source: sourceBundle,
        productId: getBundleProductId(bundle),
        unitAmount: getBundleSurchargeUnitAmount(bundle),
        quantity: new Decimal(getSafeNum((_bundle$num = bundle === null || bundle === void 0 ? void 0 : bundle.num) !== null && _bundle$num !== void 0 ? _bundle$num : bundle === null || bundle === void 0 ? void 0 : bundle.quantity)).times(productQuantity),
        persistedQuantity: getPersistedQuantity(bundle, new Decimal(getSafeNum((_bundle$num2 = bundle === null || bundle === void 0 ? void 0 : bundle.num) !== null && _bundle$num2 !== void 0 ? _bundle$num2 : bundle === null || bundle === void 0 ? void 0 : bundle.quantity)).times(productQuantity)),
        relationSurchargeIds: getRelationSurchargeIds(sourceBundle).length ? getRelationSurchargeIds(sourceBundle) : getRelationSurchargeIds(bundle),
        persistedUnitSurchargeFee: getPersistedBundleSurchargeFee(bundle, product),
        persistedSurchargeRemainder: getPersistedSurchargeRemainder(bundle, sourceBundle)
      });
    }
    nodes.push({
      kind: 'main',
      target: product,
      source: sourceItem,
      productId: (_product$product_id = product.product_id) !== null && _product$product_id !== void 0 ? _product$product_id : null,
      unitAmount: getMainSurchargeUnitAmount(product),
      quantity: productQuantity,
      persistedQuantity: getPersistedQuantity(product, productQuantity),
      relationSurchargeIds: getRelationSurchargeIds(sourceItem).length ? getRelationSurchargeIds(sourceItem) : getRelationSurchargeIds(product),
      persistedUnitSurchargeFee: (_getPersistedSourceSu = getPersistedSourceSurchargeFee(sourceItem)) !== null && _getPersistedSourceSu !== void 0 ? _getPersistedSourceSu : getPersistedMainSurchargeFee(product),
      persistedSurchargeRemainder: getPersistedSurchargeRemainder(product, sourceItem)
    });
  }
  return nodes;
}
function resetProductSurchargeFields(products) {
  for (var _i = 0, _arr = products; _i < _arr.length; _i++) {
    var product = _arr[_i];
    product.surcharge_fee = 0;
    product.main_product_attached_bundle_surcharge_fee = '0.00';
    product.surcharge_rounding_remainder = 0;
    product.relation_surcharge_ids = [];
    var _iterator2 = _createForOfIteratorHelper(product.product_bundle || []),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var bundle = _step2.value;
        bundle.surcharge_fee = 0;
        bundle.relation_surcharge_ids = [];
        bundle.metadata = _objectSpread(_objectSpread({}, bundle.metadata || {}), {}, {
          surcharge_fee: '0.00',
          surcharge_rounding_remainder: '0.00',
          relation_surcharge_ids: []
        });
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
  }
}
function getPersistedSurchargeIds(nodes) {
  var ids = new Set();
  var _iterator3 = _createForOfIteratorHelper(nodes),
    _step3;
  try {
    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      var node = _step3.value;
      if (!node.persistedUnitSurchargeFee || node.persistedUnitSurchargeFee.lte(0)) continue;
      var _iterator4 = _createForOfIteratorHelper(node.relationSurchargeIds),
        _step4;
      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var surchargeId = _step4.value;
          ids.add(surchargeId);
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }
  return ids;
}
function buildSurchargeQuantityTotals(nodes) {
  var totals = new Map();
  var _iterator5 = _createForOfIteratorHelper(nodes),
    _step5;
  try {
    for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
      var node = _step5.value;
      var _iterator6 = _createForOfIteratorHelper(node.relationSurchargeIds),
        _step6;
      try {
        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
          var surchargeId = _step6.value;
          totals.set(surchargeId, (totals.get(surchargeId) || new Decimal(0)).plus(node.quantity));
        }
      } catch (err) {
        _iterator6.e(err);
      } finally {
        _iterator6.f();
      }
    }
  } catch (err) {
    _iterator5.e(err);
  } finally {
    _iterator5.f();
  }
  return totals;
}
function getFallbackAllProductSurchargeIds(surchargeList) {
  return (surchargeList || []).reduce(function (ids, config) {
    var _config$open_product, _config$is_all;
    var id = getSurchargeConfigId(config);
    if (id === undefined) return ids;
    if (Number((_config$open_product = config.open_product) !== null && _config$open_product !== void 0 ? _config$open_product : 0) === 0) return ids;
    if (Number((_config$is_all = config.is_all) !== null && _config$is_all !== void 0 ? _config$is_all : 0) !== 1) return ids;
    ids.push(id);
    return ids;
  }, []);
}
function getBackendSurchargeState(stateMap, surchargeId, config) {
  var state = stateMap.get(surchargeId);
  if (!state) {
    state = {
      config: config,
      amount: new Decimal(0),
      totalOffsetFee: new Decimal(0),
      calculatedQuantity: new Decimal(0),
      fixedIncluded: false,
      fixedRemainderAssigned: false
    };
    stateMap.set(surchargeId, state);
  }
  return state;
}
function buildSurchargeResultItem(config, surchargeId, amount, index) {
  var name = (config === null || config === void 0 ? void 0 : config.name) || (config === null || config === void 0 ? void 0 : config.label) || {};
  return {
    key: "custom_surcharge_".concat(index),
    label: name,
    name: name,
    value: amount.toNumber(),
    surcharge_id: surchargeId,
    description: config === null || config === void 0 ? void 0 : config.description,
    type: 'default',
    fixed: config === null || config === void 0 ? void 0 : config.fixed,
    amount: amount.toNumber(),
    percentage: config === null || config === void 0 ? void 0 : config.percentage,
    metadata: {
      open_product: config === null || config === void 0 ? void 0 : config.open_product
    }
  };
}
function applySurchargeNodeResult(node, params) {
  var unitSurchargeFee = params.unitSurchargeFee,
    roundingRemainder = params.roundingRemainder,
    surchargeIds = params.surchargeIds;
  if (node.kind === 'main') {
    node.target.surcharge_fee = unitSurchargeFee.toNumber();
    node.target.main_product_attached_bundle_surcharge_fee = toFixed2(unitSurchargeFee);
    node.target.surcharge_rounding_remainder = roundingRemainder.toNumber();
    node.target.relation_surcharge_ids = surchargeIds;
    return;
  }
  node.target.surcharge_fee = unitSurchargeFee.toNumber();
  node.target.relation_surcharge_ids = surchargeIds;
  node.target.metadata = _objectSpread(_objectSpread({}, node.target.metadata || {}), {}, {
    surcharge_fee: toFixed2(unitSurchargeFee),
    surcharge_rounding_remainder: toFixed2(roundingRemainder),
    relation_surcharge_ids: surchargeIds
  });
}
function calculateBackendProductSurcharges(params) {
  var products = params.products,
    sourceItems = params.sourceItems,
    surchargeList = params.surchargeList;
  resetProductSurchargeFields(products);
  var configById = getSurchargeConfigById(surchargeList);
  var nodes = createSurchargeAllocationNodes(products, sourceItems);
  var fallbackAllProductSurchargeIds = getFallbackAllProductSurchargeIds(surchargeList);
  var _iterator7 = _createForOfIteratorHelper(nodes),
    _step7;
  try {
    for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
      var node = _step7.value;
      if (node.relationSurchargeIds.length === 0) {
        node.relationSurchargeIds = fallbackAllProductSurchargeIds;
      }
    }
  } catch (err) {
    _iterator7.e(err);
  } finally {
    _iterator7.f();
  }
  var persistedSurchargeIds = getPersistedSurchargeIds(nodes);
  var quantityTotals = buildSurchargeQuantityTotals(nodes);
  var stateMap = new Map();
  var _iterator8 = _createForOfIteratorHelper(nodes),
    _step8;
  try {
    for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
      var _node = _step8.value;
      var unitSurchargeFee = new Decimal(0);
      var roundingRemainder = new Decimal(0);
      var appliedSurchargeIds = [];
      var persistedRemainderApplied = false;
      var _iterator10 = _createForOfIteratorHelper(_node.relationSurchargeIds),
        _step10;
      try {
        for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
          var surchargeId = _step10.value;
          var config = configById.get(surchargeId);
          var totalQuantity = quantityTotals.get(surchargeId) || new Decimal(0);
          if (totalQuantity.lte(0)) continue;
          var persistedUnitSurchargeFee = _node.persistedUnitSurchargeFee;
          if (persistedUnitSurchargeFee && persistedUnitSurchargeFee.gt(0)) {
            var persistedQuantity = Decimal.min(_node.persistedQuantity, _node.quantity);
            var deltaQuantity = Decimal.max(_node.quantity.minus(persistedQuantity), 0);
            var _state = getBackendSurchargeState(stateMap, surchargeId, config || {
              surcharge_id: surchargeId
            });
            var persistedSurchargeRemainder = !persistedRemainderApplied && _node.persistedSurchargeRemainder ? _node.persistedSurchargeRemainder : new Decimal(0);
            _state.amount = bcAdd(bcAdd(_state.amount, bcMul(persistedUnitSurchargeFee, persistedQuantity, 2), 2), persistedSurchargeRemainder, 2);
            var _fixed = new Decimal((config === null || config === void 0 ? void 0 : config.fixed) || 0);
            if (_fixed.gt(0)) _state.fixedIncluded = true;
            var nodeTotalSurcharge = bcAdd(bcMul(persistedUnitSurchargeFee, persistedQuantity, 2), persistedSurchargeRemainder, 2);
            if (config && deltaQuantity.gt(0)) {
              var _percentage = new Decimal(config.percentage || 0);
              var deltaUnitPercentageFee = Decimal.max(0, bcMul(_node.unitAmount, _percentage, 2));
              var deltaSurcharge = bcMul(deltaQuantity, deltaUnitPercentageFee, 2);
              _state.amount = bcAdd(_state.amount, deltaSurcharge, 2);
              nodeTotalSurcharge = bcAdd(nodeTotalSurcharge, deltaSurcharge, 2);
            }
            if (_node.quantity.gt(0)) {
              unitSurchargeFee = bcAdd(unitSurchargeFee, bcDiv(nodeTotalSurcharge, _node.quantity, 2), 2);
            }
            if (!persistedSurchargeRemainder.eq(0)) {
              roundingRemainder = bcAdd(roundingRemainder, persistedSurchargeRemainder, 2);
              persistedRemainderApplied = true;
            }
            appliedSurchargeIds.push(surchargeId);
            continue;
          }
          if (!config) continue;
          var percentage = new Decimal(config.percentage || 0);
          var fixed = new Decimal(config.fixed || 0);
          var unitPercentageFee = Decimal.max(0, bcMul(_node.unitAmount, percentage, 2));
          var percentageTotalFee = bcMul(_node.quantity, unitPercentageFee, 2);
          var unitFixedFee = new Decimal(0);
          var fixedRemainder = new Decimal(0);
          if (fixed.gt(0) && !persistedSurchargeIds.has(surchargeId)) {
            unitFixedFee = bcDiv(fixed, totalQuantity, 2);
            var distributedFixed = bcMul(unitFixedFee, totalQuantity, 2);
            fixedRemainder = bcSub(fixed, distributedFixed, 2);
          }
          var currentUnitSurcharge = Decimal.max(0, bcAdd(unitPercentageFee, unitFixedFee, 2));
          if (currentUnitSurcharge.lte(0)) continue;
          var state = getBackendSurchargeState(stateMap, surchargeId, config);
          state.amount = bcAdd(state.amount, percentageTotalFee, 2);
          var precisePercentage = Decimal.max(0, bcMul(_node.unitAmount, percentage, 6));
          var offsetBaseFee = Decimal.max(0, bcSub(precisePercentage, unitPercentageFee, 6));
          state.totalOffsetFee = bcAdd(state.totalOffsetFee, bcMul(offsetBaseFee, _node.quantity, 6), 6);
          state.calculatedQuantity = bcAdd(state.calculatedQuantity, _node.quantity, 6);
          if (!state.fixedIncluded && fixed.gt(0) && !persistedSurchargeIds.has(surchargeId)) {
            state.amount = bcAdd(state.amount, fixed, 2);
            state.fixedIncluded = true;
          }
          if (!state.fixedRemainderAssigned && !fixedRemainder.eq(0)) {
            state.fixedRemainderAssigned = true;
            roundingRemainder = bcAdd(roundingRemainder, fixedRemainder, 2);
          }
          if (state.calculatedQuantity.gte(totalQuantity) && state.totalOffsetFee.gt(0)) {
            var totalOffsetFee = toAmountFormat(state.totalOffsetFee);
            state.amount = bcAdd(state.amount, totalOffsetFee, 2);
            roundingRemainder = bcAdd(roundingRemainder, totalOffsetFee, 2);
            state.totalOffsetFee = new Decimal(0);
          }
          unitSurchargeFee = bcAdd(unitSurchargeFee, currentUnitSurcharge, 2);
          appliedSurchargeIds.push(surchargeId);
        }
      } catch (err) {
        _iterator10.e(err);
      } finally {
        _iterator10.f();
      }
      applySurchargeNodeResult(_node, {
        unitSurchargeFee: unitSurchargeFee,
        roundingRemainder: roundingRemainder,
        surchargeIds: appliedSurchargeIds
      });
    }
  } catch (err) {
    _iterator8.e(err);
  } finally {
    _iterator8.f();
  }
  var result = (surchargeList || []).reduce(function (items, config, index) {
    var surchargeId = getSurchargeConfigId(config);
    if (surchargeId === undefined) return items;
    var state = stateMap.get(surchargeId);
    if (!state || state.amount.lte(0)) return items;
    items.push(buildSurchargeResultItem(config, surchargeId, state.amount, index));
    return items;
  }, []);
  var includedIds = new Set(result.map(function (item) {
    return item === null || item === void 0 ? void 0 : item.surcharge_id;
  }).filter(function (id) {
    return id !== undefined;
  }));
  var _iterator9 = _createForOfIteratorHelper(stateMap.entries()),
    _step9;
  try {
    for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
      var _step9$value = _slicedToArray(_step9.value, 2),
        _surchargeId = _step9$value[0],
        _state2 = _step9$value[1];
      if (includedIds.has(_surchargeId) || _state2.amount.lte(0)) continue;
      result.push(buildSurchargeResultItem(_state2.config, _surchargeId, _state2.amount, result.length));
    }
  } catch (err) {
    _iterator9.e(err);
  } finally {
    _iterator9.f();
  }
  return result;
}
function getProductDepositData(product) {
  var _product$_origin, _product$_origin2;
  var rootDepositData = (_product$_origin = product._origin) === null || _product$_origin === void 0 ? void 0 : _product$_origin.custom_deposit_data;
  if (rootDepositData && _typeof(rootDepositData) === 'object') return rootDepositData;
  var nestedDepositData = (_product$_origin2 = product._origin) === null || _product$_origin2 === void 0 || (_product$_origin2 = _product$_origin2.product) === null || _product$_origin2 === void 0 ? void 0 : _product$_origin2.custom_deposit_data;
  if (nestedDepositData && _typeof(nestedDepositData) === 'object') return nestedDepositData;
  return undefined;
}
function collectDepositPolicyIds(depositData) {
  var rawIds = [].concat(_toConsumableArray(Array.isArray(depositData === null || depositData === void 0 ? void 0 : depositData.self_deposit_policy_ids) ? depositData.self_deposit_policy_ids : []), _toConsumableArray(Array.isArray(depositData === null || depositData === void 0 ? void 0 : depositData.deposit_policy_ids) ? depositData.deposit_policy_ids : []));
  return rawIds.reduce(function (result, id) {
    var normalizedId = Number(id);
    if (!Number.isFinite(normalizedId)) return result;
    result.push(Math.floor(normalizedId));
    return result;
  }, []);
}
function collectDepositPolicyData(depositData) {
  var rawPolicyData = Array.isArray(depositData === null || depositData === void 0 ? void 0 : depositData.deposit_policy_data) ? depositData.deposit_policy_data : [];
  return rawPolicyData.reduce(function (result, policy) {
    var normalizedId = Number(policy === null || policy === void 0 ? void 0 : policy.id);
    if (!Number.isFinite(normalizedId)) return result;
    result.push({
      id: Math.floor(normalizedId),
      title: String((policy === null || policy === void 0 ? void 0 : policy.title) || '')
    });
    return result;
  }, []);
}
function calculateProductsDeposit(products) {
  var totalDeposit = new Decimal(0);
  var hasDeposit = false;
  var policyIds = new Set();
  var policyDataMap = new Map();
  var _iterator11 = _createForOfIteratorHelper(products),
    _step11;
  try {
    for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
      var product = _step11.value;
      var depositData = getProductDepositData(product);
      if (!depositData || depositData.has_deposit != 1) continue;
      var num = getSafeNum(product.num);
      var unitTotal = getUnitPaymentTotal(product);
      var productTotal = unitTotal.times(num);
      var deposit_fixed = depositData.deposit_fixed,
        deposit_percentage = depositData.deposit_percentage;
      var fixed = toDecimal(deposit_fixed);
      var percentage = toDecimal(deposit_percentage);
      var itemDeposit = fixed.plus(percentage.times(productTotal));
      totalDeposit = totalDeposit.plus(itemDeposit);
      hasDeposit = true;
      var _iterator13 = _createForOfIteratorHelper(collectDepositPolicyIds(depositData)),
        _step13;
      try {
        for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
          var id = _step13.value;
          policyIds.add(id);
        }
      } catch (err) {
        _iterator13.e(err);
      } finally {
        _iterator13.f();
      }
      var _iterator14 = _createForOfIteratorHelper(collectDepositPolicyData(depositData)),
        _step14;
      try {
        for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
          var policy = _step14.value;
          if (!policyDataMap.has(policy.id)) {
            policyDataMap.set(policy.id, policy);
          }
          policyIds.add(policy.id);
        }
      } catch (err) {
        _iterator14.e(err);
      } finally {
        _iterator14.f();
      }
    }
  } catch (err) {
    _iterator11.e(err);
  } finally {
    _iterator11.f();
  }
  if (!hasDeposit) return undefined;
  var _iterator12 = _createForOfIteratorHelper(policyIds),
    _step12;
  try {
    for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
      var _id = _step12.value;
      if (!policyDataMap.has(_id)) {
        policyDataMap.set(_id, {
          id: _id,
          title: ''
        });
      }
    }
  } catch (err) {
    _iterator12.e(err);
  } finally {
    _iterator12.f();
  }
  return {
    total: totalDeposit.toFixed(2),
    deposit_policy_ids: _toConsumableArray(policyIds),
    deposit_policy_data: _toConsumableArray(policyDataMap.values()),
    hasDeposit: true
  };
}
function isBundleOriginalPrice(item) {
  return (item === null || item === void 0 ? void 0 : item.price_type) === 'markup' && (item === null || item === void 0 ? void 0 : item.price_type_ext) === 'product_price';
}
function isBundleMarkupOrDiscount(item) {
  var isMarkup = (item === null || item === void 0 ? void 0 : item.price_type) === 'markup' && ((item === null || item === void 0 ? void 0 : item.price_type_ext) === '' || !(item !== null && item !== void 0 && item.price_type_ext));
  var isDiscount = (item === null || item === void 0 ? void 0 : item.price_type) === 'markdown' && ((item === null || item === void 0 ? void 0 : item.price_type_ext) === '' || !(item !== null && item !== void 0 && item.price_type_ext));
  return isMarkup || isDiscount;
}

/**
 * 计算单个商品税费（返回精确值，不四舍五入）。
 * 与 Summary/utils.ts 的 getProductItemTax 公式一致，但不依赖 bookingDetail。
 *
 * @param taxRate 百分比税率（如 5 表示 5%），函数内部会 /100
 */
function calculateSingleItemTax(params) {
  var price = params.price,
    taxRate = params.taxRate,
    isPriceIncludeTax = params.isPriceIncludeTax,
    isChargeTax = params.isChargeTax;
  if (price.lte(0)) return new Decimal(0);
  if (isChargeTax === 0 || !isChargeTax) return new Decimal(0);
  var rate = taxRate.div(100);
  if (isPriceIncludeTax === 0) {
    return price.times(rate);
  }
  var divisor = new Decimal(1).plus(rate);
  if (divisor.lte(0)) return new Decimal(0);
  return price.dividedBy(divisor).times(rate);
}

/**
 * 主商品 + 非原价(加价/减价)子商品的"折扣后"售价合计（含 option、含主商品折扣，未减整单折扣）。
 *
 * 对齐后端 metadata.main_product_attached_bundle_selling_price：
 * - `metadata.main_product_selling_price` 已是"含 option、含折扣"的主价；
 * - 叠加 `markup` / `markdown` 类 bundle（原价 bundle 由 `calculateProductsTax` 独立处理）。
 */
function getMainAttachedBundleSellingTotal(product) {
  var _ref8, _product$metadata$mai, _product$metadata8, _product$metadata9;
  var mainSelling = (_ref8 = (_product$metadata$mai = (_product$metadata8 = product.metadata) === null || _product$metadata8 === void 0 ? void 0 : _product$metadata8.main_product_selling_price) !== null && _product$metadata$mai !== void 0 ? _product$metadata$mai : (_product$metadata9 = product.metadata) === null || _product$metadata9 === void 0 ? void 0 : _product$metadata9.main_product_original_price) !== null && _ref8 !== void 0 ? _ref8 : 0;
  var total = toDecimal(mainSelling);
  var bundleItems = product.product_bundle || [];
  var _iterator15 = _createForOfIteratorHelper(bundleItems),
    _step15;
  try {
    for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
      var bundleItem = _step15.value;
      if (isBundleMarkupOrDiscount(bundleItem)) {
        var _bundleItem$num;
        // markdown（减价）按带符号净额取减；markup 维持相加。
        var unit = getBundleSignedUnit(bundleItem);
        var qty = getSafeNum((_bundleItem$num = bundleItem.num) !== null && _bundleItem$num !== void 0 ? _bundleItem$num : bundleItem.quantity);
        total = total.plus(unit.times(qty));
      }
    }
  } catch (err) {
    _iterator15.e(err);
  } finally {
    _iterator15.f();
  }
  return Decimal.max(total, 0);
}

/**
 * 获取主商品税费基数（含 option、含主商品折扣、含加价/减价 bundle、已减整单折扣均摊）。
 *
 * 对齐后端 handleMainProductTaxFee：税基使用 main_product_attached_bundle_payment_price。
 * - 优先读取均摊层写入的 payment 价；
 * - 兜底退化为 selling 合计（无整单折扣时两者相等）。
 */
function getMainProductPaymentTotal(product) {
  var _product$metadata10;
  var attachedPayment = (_product$metadata10 = product.metadata) === null || _product$metadata10 === void 0 ? void 0 : _product$metadata10.main_product_attached_bundle_payment_price;
  if (attachedPayment !== undefined && attachedPayment !== null && attachedPayment !== '') {
    return Decimal.max(toDecimal(attachedPayment), 0);
  }
  return getMainAttachedBundleSellingTotal(product);
}
function getExplicitTaxRemainder(item) {
  var _item$tax_fee_roundin, _item$metadata3;
  var value = (_item$tax_fee_roundin = item === null || item === void 0 ? void 0 : item.tax_fee_rounding_remainder) !== null && _item$tax_fee_roundin !== void 0 ? _item$tax_fee_roundin : item === null || item === void 0 || (_item$metadata3 = item.metadata) === null || _item$metadata3 === void 0 ? void 0 : _item$metadata3.tax_fee_rounding_remainder;
  if (value === undefined || value === null || value === '') return null;
  return new Decimal(value || 0);
}
function getPersistedTaxRemainder(item, parentProduct) {
  var isPersistedLine = (item === null || item === void 0 ? void 0 : item.order_detail_id) !== undefined && (item === null || item === void 0 ? void 0 : item.order_detail_id) !== null || (parentProduct === null || parentProduct === void 0 ? void 0 : parentProduct.order_detail_id) !== undefined && (parentProduct === null || parentProduct === void 0 ? void 0 : parentProduct.order_detail_id) !== null;
  if (!isPersistedLine) return null;
  return getExplicitTaxRemainder(item);
}
function getPersistedMainTaxFee(product) {
  var _ref9, _product$metadata$mai2, _product$metadata11;
  if ((product === null || product === void 0 ? void 0 : product.order_detail_id) === undefined || (product === null || product === void 0 ? void 0 : product.order_detail_id) === null) return null;
  var value = (_ref9 = (_product$metadata$mai2 = product === null || product === void 0 || (_product$metadata11 = product.metadata) === null || _product$metadata11 === void 0 ? void 0 : _product$metadata11.main_product_attached_bundle_tax_fee) !== null && _product$metadata$mai2 !== void 0 ? _product$metadata$mai2 : product === null || product === void 0 ? void 0 : product.main_product_attached_bundle_tax_fee) !== null && _ref9 !== void 0 ? _ref9 : product === null || product === void 0 ? void 0 : product.tax_fee;
  if (value === undefined || value === null || value === '') return null;
  return toDecimal(value);
}
function writeTaxRemainder(item, roundingRemainder) {
  item.tax_fee_rounding_remainder = roundingRemainder.toNumber();
  if (item.metadata && _typeof(item.metadata) === 'object') {
    item.metadata.tax_fee_rounding_remainder = roundingRemainder.toFixed(2);
  }
}
function resetTaxRemainderFields(products) {
  for (var _i2 = 0, _arr2 = products; _i2 < _arr2.length; _i2++) {
    var product = _arr2[_i2];
    var productRemainder = getPersistedTaxRemainder(product);
    if (productRemainder !== null) {
      product.tax_fee_rounding_remainder = productRemainder.toNumber();
    } else {
      delete product.tax_fee_rounding_remainder;
    }
    product.original_tax_fee_rounding_remainder = 0;
    var _iterator16 = _createForOfIteratorHelper(product.product_bundle || []),
      _step16;
    try {
      for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
        var bundle = _step16.value;
        var bundleRemainder = getPersistedTaxRemainder(bundle, product);
        bundle.metadata = _objectSpread({}, bundle.metadata || {});
        if (bundleRemainder !== null) {
          bundle.metadata.tax_fee_rounding_remainder = bundleRemainder.toFixed(2);
          bundle.tax_fee_rounding_remainder = bundleRemainder.toNumber();
        } else {
          delete bundle.metadata.tax_fee_rounding_remainder;
          delete bundle.tax_fee_rounding_remainder;
        }
        bundle.original_tax_fee_rounding_remainder = 0;
      }
    } catch (err) {
      _iterator16.e(err);
    } finally {
      _iterator16.f();
    }
  }
}
function getBundlePaymentPrice(bundle, product) {
  var _ref10, _ref11, _bundle$bundle_sellin2, _metadata$average_dis, _metadata;
  if ((bundle === null || bundle === void 0 ? void 0 : bundle.bundle_payment_price) !== undefined) return toDecimal(bundle.bundle_payment_price);
  var basePrice = toDecimal((_ref10 = (_ref11 = (_bundle$bundle_sellin2 = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_selling_price) !== null && _bundle$bundle_sellin2 !== void 0 ? _bundle$bundle_sellin2 : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_sum_price) !== null && _ref11 !== void 0 ? _ref11 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref10 !== void 0 ? _ref10 : 0);
  if (!isBundleOriginalPrice(bundle)) return basePrice;
  var averageDiscountRate = toDecimal((_metadata$average_dis = (_metadata = product.metadata) === null || _metadata === void 0 ? void 0 : _metadata.average_discount_amount_rate) !== null && _metadata$average_dis !== void 0 ? _metadata$average_dis : 1);
  return toAmountFormat(bcMul(basePrice, averageDiscountRate, 6));
}
function applyBackendTaxRemainder(params) {
  var target = params.target,
    rawTax = params.rawTax,
    formattedTax = params.formattedTax,
    quantity = params.quantity,
    state = params.state;
  var taxFeeDifference = bcMul(bcSub(rawTax, formattedTax, 6), quantity, 6);
  state.difference = bcAdd(state.difference, taxFeeDifference, 6);
  if (state.difference.lt(0.005)) return new Decimal(0);
  var roundingRemainder = toAmountFormat(state.difference);
  writeTaxRemainder(target, roundingRemainder);
  state.difference = bcSub(state.difference, roundingRemainder, 6);
  return roundingRemainder;
}

/**
 * 遍历所有商品计算税费，回写 tax_fee 到每个商品及 bundle 原价子商品，处理舍入差值。
 * 参照 Summary/utils.ts 的 processItemsTax，适配 SalesSummaryProduct 结构。
 */
function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
  var rate = new Decimal(taxRate);
  var taxRemainderState = {
    difference: new Decimal(0)
  };
  var totalTax = new Decimal(0);
  var totalOriginTax = new Decimal(0);
  resetTaxRemainderFields(products);
  var _iterator17 = _createForOfIteratorHelper(products),
    _step17;
  try {
    for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
      var _product$is_charge_ta2, _product$is_charge_ta3;
      var product = _step17.value;
      var quantity = new Decimal(getSafeNum(product.num));
      var productUnitTax = new Decimal(0);
      var productUnitOriginTax = new Decimal(0);
      var bundleItems = product.product_bundle || [];
      var _iterator18 = _createForOfIteratorHelper(bundleItems),
        _step18;
      try {
        for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
          var _bundleItem$num2, _ref12, _ref13, _bundleItem$original_, _ref14, _bundleItem$is_charge, _ref15, _bundleItem$is_charge2;
          var bundleItem = _step18.value;
          if (!isBundleOriginalPrice(bundleItem)) continue;
          var bundleQuantity = new Decimal(getSafeNum((_bundleItem$num2 = bundleItem.num) !== null && _bundleItem$num2 !== void 0 ? _bundleItem$num2 : bundleItem.quantity));
          var totalBundleQuantity = bundleQuantity.times(quantity);
          var bundlePrice = getBundlePaymentPrice(bundleItem, product);
          var bundleOriginalPrice = toDecimal((_ref12 = (_ref13 = (_bundleItem$original_ = bundleItem.original_price) !== null && _bundleItem$original_ !== void 0 ? _bundleItem$original_ : bundleItem.product_price) !== null && _ref13 !== void 0 ? _ref13 : bundleItem.price) !== null && _ref12 !== void 0 ? _ref12 : 0);
          var bundleSurchargeFee = toDecimal(bundleItem.surcharge_fee);
          var bundleTaxPrecise = calculateSingleItemTax({
            price: bundlePrice.plus(bundleSurchargeFee),
            taxRate: rate,
            isPriceIncludeTax: isPriceIncludeTax,
            isChargeTax: (_ref14 = (_bundleItem$is_charge = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge !== void 0 ? _bundleItem$is_charge : product.is_charge_tax) !== null && _ref14 !== void 0 ? _ref14 : 0
          });
          var bundleTaxRounded = toBackendTaxFee(bundleTaxPrecise);
          bundleItem.tax_fee = bundleTaxRounded.toNumber();
          var persistedBundleRemainder = getPersistedTaxRemainder(bundleItem, product);
          var bundleRemainder = persistedBundleRemainder !== null && persistedBundleRemainder !== void 0 ? persistedBundleRemainder : applyBackendTaxRemainder({
            target: bundleItem,
            rawTax: bundleTaxPrecise,
            formattedTax: bundleTaxRounded,
            quantity: totalBundleQuantity,
            state: taxRemainderState
          });
          if (persistedBundleRemainder) writeTaxRemainder(bundleItem, persistedBundleRemainder);
          var bundleOrigTaxPrecise = calculateSingleItemTax({
            price: bundleOriginalPrice.plus(bundleSurchargeFee),
            taxRate: rate,
            isPriceIncludeTax: isPriceIncludeTax,
            isChargeTax: (_ref15 = (_bundleItem$is_charge2 = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge2 !== void 0 ? _bundleItem$is_charge2 : product.is_charge_tax) !== null && _ref15 !== void 0 ? _ref15 : 0
          });
          var bundleOrigTaxRounded = toAmountFormat(bundleOrigTaxPrecise);
          bundleItem.original_tax_fee = bundleOrigTaxRounded.toNumber();
          productUnitTax = productUnitTax.plus(bundleTaxRounded.times(bundleQuantity));
          productUnitOriginTax = productUnitOriginTax.plus(bundleOrigTaxRounded.times(bundleQuantity));
          totalTax = totalTax.plus(bundleTaxRounded.times(totalBundleQuantity)).plus(bundleRemainder);
          totalOriginTax = totalOriginTax.plus(bundleOrigTaxRounded.times(totalBundleQuantity));
        }
      } catch (err) {
        _iterator18.e(err);
      } finally {
        _iterator18.f();
      }
      var mainTotal = getMainProductPaymentTotal(product);
      var surchargeFee = toDecimal(product.surcharge_fee);
      var mainTaxableBase = mainTotal.lte(0) ? surchargeFee : mainTotal.plus(surchargeFee);
      var mainTaxPrecise = calculateSingleItemTax({
        price: mainTaxableBase,
        taxRate: rate,
        isPriceIncludeTax: isPriceIncludeTax,
        isChargeTax: (_product$is_charge_ta2 = product.is_charge_tax) !== null && _product$is_charge_ta2 !== void 0 ? _product$is_charge_ta2 : 0
      });
      var mainTaxRounded = toBackendTaxFee(mainTaxPrecise);
      var persistedMainRemainder = getPersistedTaxRemainder(product);
      var persistedMainTaxFee = getPersistedMainTaxFee(product);
      var persistedQuantity = getPersistedQuantity(product, quantity);
      var deltaQuantity = Decimal.max(quantity.minus(persistedQuantity), 0);
      var shouldUsePersistedMainTax = persistedMainTaxFee && persistedMainTaxFee.gt(0) && persistedQuantity.gte(quantity);
      var shouldSplitPersistedMainTax = persistedMainTaxFee && persistedMainTaxFee.gt(0) && persistedQuantity.gt(0) && deltaQuantity.gt(0);
      var mainRemainder = shouldUsePersistedMainTax || shouldSplitPersistedMainTax ? new Decimal(0) : persistedMainRemainder !== null && persistedMainRemainder !== void 0 ? persistedMainRemainder : applyBackendTaxRemainder({
        target: product,
        rawTax: mainTaxPrecise,
        formattedTax: mainTaxRounded,
        quantity: quantity,
        state: taxRemainderState
      });
      if (persistedMainRemainder && !shouldSplitPersistedMainTax) {
        writeTaxRemainder(product, persistedMainRemainder);
      }
      var originalTotal = getUnitOriginalTotal(product);
      var originalTaxableBase = originalTotal.lte(0) ? surchargeFee : originalTotal.plus(surchargeFee);
      var originalTaxPrecise = calculateSingleItemTax({
        price: originalTaxableBase,
        taxRate: rate,
        isPriceIncludeTax: isPriceIncludeTax,
        isChargeTax: (_product$is_charge_ta3 = product.is_charge_tax) !== null && _product$is_charge_ta3 !== void 0 ? _product$is_charge_ta3 : 0
      });
      var originalTaxRounded = toAmountFormat(originalTaxPrecise);
      var effectiveMainUnitTax = shouldUsePersistedMainTax ? persistedMainTaxFee : shouldSplitPersistedMainTax ? persistedMainTaxFee.times(persistedQuantity).plus(mainTaxRounded.times(deltaQuantity)).div(quantity).toDecimalPlaces(2, Decimal.ROUND_HALF_UP) : mainTaxRounded;
      productUnitTax = productUnitTax.plus(effectiveMainUnitTax);
      productUnitOriginTax = productUnitOriginTax.plus(originalTaxRounded);
      product.main_product_attached_bundle_tax_fee = effectiveMainUnitTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
      product.tax_fee = productUnitTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
      product.original_tax_fee = productUnitOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
      totalTax = totalTax.plus(shouldUsePersistedMainTax ? persistedMainTaxFee.times(quantity).plus(persistedMainRemainder || 0) : shouldSplitPersistedMainTax ? persistedMainTaxFee.times(persistedQuantity).plus(mainTaxRounded.times(deltaQuantity)) : mainTaxRounded.times(quantity).plus(mainRemainder));
      totalOriginTax = totalOriginTax.plus(originalTaxRounded.times(quantity));
      if (product.tax_fee_rounding_remainder === undefined) {
        product.tax_fee_rounding_remainder = 0;
      }
    }
  } catch (err) {
    _iterator17.e(err);
  } finally {
    _iterator17.f();
  }
  return {
    tax: totalTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP),
    originTax: totalOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP)
  };
}

/**
 * 整单折扣（shop_discount）按各行 selling 合计占比均摊到 payment 维度。
 *
 * 文档口径：
 * - payment_price = selling_price − 整单折扣均摊；rate = payment/selling（全行同一 rate）；
 * - 附加费不受整单折扣影响（基数仍用 selling，本函数写 main_product_attached_bundle_selling_price）；
 * - 税费受整单折扣影响（基数用 payment，本函数写 main_product_attached_bundle_payment_price 与
 *   原价子商品 bundle_payment_price）。
 *
 * 与后端一致：bundle_payment_price = bundle_selling_price × rate，
 * main_product_attached_bundle_payment_price = main_product_attached_bundle_selling_price × rate。
 */
function allocateShopDiscountToPayment(products, productAmount, shopDiscountAmount) {
  var effectiveDiscount = productAmount.lte(0) ? new Decimal(0) : Decimal.max(Decimal.min(productAmount, shopDiscountAmount), 0);
  var allocatedDiscount = new Decimal(0);
  products.forEach(function (product, index) {
    var quantity = new Decimal(getSafeNum(product.num));
    var sellingUnit = getUnitPaymentTotal(product);
    var lineSellingTotal = sellingUnit.times(quantity);
    var lineDiscount = effectiveDiscount.lte(0) ? new Decimal(0) : index === products.length - 1 ? Decimal.max(effectiveDiscount.minus(allocatedDiscount), 0) : toAmountFormat(lineSellingTotal.div(productAmount).times(effectiveDiscount));
    allocatedDiscount = allocatedDiscount.plus(lineDiscount);
    var unitDiscount = quantity.lte(0) ? new Decimal(0) : lineDiscount.div(quantity);
    var paymentUnit = Decimal.max(sellingUnit.minus(unitDiscount), 0);
    var rate = sellingUnit.lte(0) ? new Decimal(1) : toBcScale(paymentUnit.div(sellingUnit), 6);
    var mainSellingTotal = getMainAttachedBundleSellingTotal(product);
    var mainPaymentTotal = toAmountFormat(bcMul(mainSellingTotal, rate, 6));
    product.metadata = _objectSpread(_objectSpread({}, product.metadata || {}), {}, {
      average_discount_amount_rate: rate.toString(),
      main_product_attached_bundle_selling_price: mainSellingTotal.toFixed(2),
      main_product_attached_bundle_payment_price: mainPaymentTotal.toFixed(2)
    });
    var _iterator19 = _createForOfIteratorHelper(product.product_bundle || []),
      _step19;
    try {
      for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
        var bundle = _step19.value;
        // 原价子商品：bundle_payment_price = bundle_selling_price × rate
        // markdown 子商品：以净额幅度 × rate（与后端一致，存正净额）
        if (isBundleOriginalPrice(bundle)) {
          var _ref16, _ref17, _bundle$bundle_sellin3;
          var bundleSelling = toDecimal((_ref16 = (_ref17 = (_bundle$bundle_sellin3 = bundle.bundle_selling_price) !== null && _bundle$bundle_sellin3 !== void 0 ? _bundle$bundle_sellin3 : bundle.bundle_sum_price) !== null && _ref17 !== void 0 ? _ref17 : bundle.price) !== null && _ref16 !== void 0 ? _ref16 : 0);
          bundle.bundle_payment_price = toAmountFormat(bcMul(bundleSelling, rate, 6)).toFixed(2);
          continue;
        }
        if (isMarkdownBundle(bundle)) {
          var _bundle$custom_price;
          var magnitude = getBundleSellingMagnitude(bundle);
          bundle.custom_price = (_bundle$custom_price = bundle.custom_price) !== null && _bundle$custom_price !== void 0 ? _bundle$custom_price : bundle.price;
          bundle.price = magnitude.toFixed(2);
          bundle.bundle_selling_price = magnitude.toFixed(2);
          bundle.bundle_payment_price = toAmountFormat(bcMul(magnitude, rate, 6)).toFixed(2);
        }
      }
    } catch (err) {
      _iterator19.e(err);
    } finally {
      _iterator19.f();
    }
    product.payment_price = paymentUnit.toFixed(2);
  });
}
export function createEmptySalesSummary() {
  return {
    product_quantity: 0,
    product_original_amount: '0.00',
    product_amount: '0.00',
    product_expect_amount: '0.00',
    product_tax_fee: '0.00',
    shipping_fee: '0.00',
    shipping_tax_fee: '0.00',
    tax_fee: '0.00',
    surcharge_fee: '0.00',
    surcharges: [],
    discount_amount: '0.00',
    deposit_amount: '0.00',
    expect_amount: '0.00',
    total_amount: '0.00',
    total_refund_amount: '0.00',
    customer_paid_amount: '0.00',
    order_paid_amount: '0.00',
    amount_gap: '0.00',
    rounding_amount: '0.00',
    pay_service_charge_amount: '0.00'
  };
}
export function calculateSalesSummary(params) {
  var products = params.products,
    isPriceIncludeTax = params.isPriceIncludeTax,
    taxRate = params.taxRate,
    surchargeList = params.surchargeList,
    _params$scheduleById = params.scheduleById,
    scheduleById = _params$scheduleById === void 0 ? {} : _params$scheduleById,
    isInScheduleByDate = params.isInScheduleByDate,
    shopDiscount = params.shopDiscount;
  if (!(products !== null && products !== void 0 && products.length)) return createEmptySalesSummary();
  var summaryProducts = products.filter(function (product) {
    return !isGeneratedVoucherProduct(product);
  });
  if (!summaryProducts.length) return createEmptySalesSummary();
  var productQuantity = summaryProducts.reduce(function (sum, item) {
    return sum + getSafeNum(item.num);
  }, 0);
  var productOriginalAmount = summaryProducts.reduce(function (sum, item) {
    return sum.plus(getUnitOriginalTotal(item).times(getSafeNum(item.num)));
  }, new Decimal(0));
  var productAmount = summaryProducts.reduce(function (sum, item) {
    return sum.plus(getUnitPaymentTotal(item).times(getSafeNum(item.num)));
  }, new Decimal(0));
  var shopDiscountAmount = Decimal.max(new Decimal(Number(shopDiscount) || 0), 0);
  var hasPersistedSurchargeSnapshot = summaryProducts.some(function (product) {
    var _getPersistedMainSurc;
    return (_getPersistedMainSurc = getPersistedMainSurchargeFee(product)) === null || _getPersistedMainSurc === void 0 ? void 0 : _getPersistedMainSurc.gt(0);
  });
  // 整单折扣均摊：附加费基数用 selling（不受折扣），税费基数用 payment（受折扣）。
  // persisted 快照（已下单编辑）优先采信后端回传值，不重算均摊。
  if (!hasPersistedSurchargeSnapshot) {
    allocateShopDiscountToPayment(summaryProducts, productAmount, shopDiscountAmount);
  }
  var surchargeServiceItems = buildSurchargeServiceItems(summaryProducts);
  getSurcharge({
    service: surchargeServiceItems,
    addons: [],
    bookingDetail: null,
    bookingId: undefined
  }, {
    isEdit: false,
    isInScheduleByDate: isInScheduleByDate,
    surcharge_list: surchargeList,
    scheduleById: scheduleById
  });
  var surcharge = calculateBackendProductSurcharges({
    products: summaryProducts,
    sourceItems: surchargeServiceItems,
    surchargeList: surchargeList
  });
  var surchargeAmount = new Decimal(getSurchargeAmount({
    bookingDetail: null,
    bookingId: undefined
  }, surcharge, {
    isEdit: false
  }) || 0);
  var hasTaxRate = taxRate !== undefined && taxRate !== null && taxRate > 0;
  var productTaxFee;
  if (hasTaxRate) {
    var taxResult = calculateProductsTax(summaryProducts, taxRate, isPriceIncludeTax);
    productTaxFee = taxResult.tax;
  } else {
    productTaxFee = summaryProducts.reduce(function (sum, item) {
      return sum.plus(toDecimal(item.tax_fee).times(getSafeNum(item.num)));
    }, new Decimal(0));
  }
  var orderAmountBeforeDiscount = productAmount.plus(surchargeAmount).plus(isPriceIncludeTax === 1 ? 0 : productTaxFee);
  var totalAmount = Decimal.max(0, orderAmountBeforeDiscount.minus(shopDiscountAmount));
  var deposit = calculateProductsDeposit(summaryProducts);
  return {
    product_quantity: productQuantity,
    product_original_amount: toFixed2(productOriginalAmount),
    product_amount: toFixed2(productAmount),
    product_expect_amount: toFixed2(productAmount),
    product_tax_fee: toFixed2(productTaxFee),
    shipping_fee: '0.00',
    shipping_tax_fee: '0.00',
    tax_fee: toFixed2(productTaxFee),
    surcharge_fee: toFixed2(surchargeAmount),
    surcharges: surcharge,
    discount_amount: toFixed2(shopDiscountAmount),
    deposit_amount: deposit ? deposit.total : '0.00',
    deposit: deposit,
    expect_amount: toFixed2(totalAmount),
    total_amount: toFixed2(totalAmount),
    total_refund_amount: '0.00',
    customer_paid_amount: '0.00',
    order_paid_amount: '0.00',
    amount_gap: '0.00',
    rounding_amount: '0.00',
    pay_service_charge_amount: '0.00',
    is_price_include_tax: isPriceIncludeTax
  };
}