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 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); }
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 _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 _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 _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 _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; }
import { flexibleObj, getDiscountTimeByDayMinutes } from "../../utils";
import { formatAmount } from '@pisell/utils';
import Decimal from 'decimal.js';
import { isDayBooking, isNormalProductByDurationSchedule } from "../../info/service2/utils";
import { isMultiDayProduct } from "../../info2/service/addService/utils";
import { getBundleDiscountList } from "./utils";
export var getRelationDetailsTotal = function getRelationDetailsTotal(relation_details) {
  var total = new Decimal(0);
  var _iterator = _createForOfIteratorHelper(relation_details),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      var number = new Decimal(item.product_quantity || item.num || 0);
      var price = new Decimal(item.selling_price || item.payment_price || item.price || 0);
      total = total.add(price.mul(number));
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return total.toNumber();
};
export var getProductDiscountProductDiscountDifference = function getProductDiscountProductDiscountDifference(product) {
  var _product$_extend;
  var mainDiscountList = product.discount_list || [];
  var bundleDiscountList = getBundleDiscountList(((_product$_extend = product._extend) === null || _product$_extend === void 0 || (_product$_extend = _product$_extend.other) === null || _product$_extend === void 0 ? void 0 : _product$_extend.bundle) || []);
  var discountList = [].concat(_toConsumableArray(mainDiscountList), _toConsumableArray(bundleDiscountList));
  return discountList.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);
};

/**
 * 总金额
 * @param state
 * @returns
 */
var getProductExpectAmount = function getProductExpectAmount(state, isEdit, isOriginTotal) {
  var price = new Decimal(0);
  var duration = new Decimal(0);
  // 是否是跨日预约
  var isDay = isDayBooking(state);
  var dayDuration = new Decimal(0);
  var minuteDuration = new Decimal(0);
  if (isEdit) {
    // 计算总价  服务 和 附加商品
    if (state !== null && state !== void 0 && state.service || state !== null && state !== void 0 && state.addons) {
      var _state$service, _state$addons;
      // 处理服务商品
      if (Array.isArray(state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.value)) {
        var _iterator2 = _createForOfIteratorHelper(state.service.value),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var item = _step2.value;
            // 跨日预约
            if (isDay || isNormalProductByDurationSchedule(item) || isMultiDayProduct(item)) {
              var quantity = new Decimal(item._extend.quantity || 1);
              var itemTotal = new Decimal(item._extend.total || 0);
              var itemOriginTotal = new Decimal(item._extend.origin_total || 0);
              price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));

              // 商品折扣差价
              price = price.sub(getProductDiscountProductDiscountDifference(item));

              // 普通商品不能加到时长上
              var _duration = !isNormalProductByDurationSchedule(item) ? new Decimal(item._extend.duration || 0) : new Decimal(0);
              if (isDay || isMultiDayProduct(item)) {
                dayDuration = dayDuration.add(_duration);
              } else {
                minuteDuration = minuteDuration.add(_duration);
              }
            } else {
              var _quantity = new Decimal(item._extend.quantity || 1);
              var _itemTotal = new Decimal(item._extend.total || 0);
              var _itemOriginTotal = new Decimal(item._extend.origin_total || 0);
              price = price.add((isOriginTotal ? _itemOriginTotal : _itemTotal).mul(_quantity));

              // 附加商品
              var relationTotal = new Decimal(getRelationDetailsTotal(item._extend.relation_details || []));
              price = price.add(relationTotal);

              // 商品折扣差价
              price = price.sub(getProductDiscountProductDiscountDifference(item));
              var itemDuration = new Decimal(flexibleObj.getValue(item._extend.duration) || 0);
              duration = duration.add(itemDuration);
              if (isMultiDayProduct(item)) {
                dayDuration = dayDuration.add(itemDuration);
              } else {
                minuteDuration = minuteDuration.add(itemDuration);
              }
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }

      // 不是跨日预约才执行 - 处理附加商品
      if (!isDay && Array.isArray((_state$addons = state.addons) === null || _state$addons === void 0 ? void 0 : _state$addons.value)) {
        var _iterator3 = _createForOfIteratorHelper(state.addons.value),
          _step3;
        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var _item = _step3.value;
            var _quantity2 = new Decimal(_item._extend.quantity || 1);
            var _itemTotal2 = new Decimal(_item._extend.total || 0);
            var _itemOriginTotal2 = new Decimal(_item._extend.origin_total || 0);
            price = price.add((isOriginTotal ? _itemOriginTotal2 : _itemTotal2).mul(_quantity2));
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
      }
    }
  } else {
    var _state$bookingDetail, _state$service2;
    price = new Decimal(((_state$bookingDetail = state.bookingDetail) === null || _state$bookingDetail === void 0 ? void 0 : _state$bookingDetail.product_expect_amount) || 0);
    var services = (state === null || state === void 0 || (_state$service2 = state.service) === null || _state$service2 === void 0 ? void 0 : _state$service2.value) || [];
    duration = services.reduce(function (pre, cur) {
      var current = new Decimal(0);
      if (isDay || isMultiDayProduct(cur)) {
        // 普通商品不能加到时长上
        var _duration2 = !isNormalProductByDurationSchedule(cur) ? new Decimal(cur._extend.duration || 0) : new Decimal(0);
        current = _duration2;
      } else {
        var _cur$_extend;
        current = new Decimal(flexibleObj.getValue(((_cur$_extend = cur._extend) === null || _cur$_extend === void 0 ? void 0 : _cur$_extend.duration) || 0) || 0);
      }
      if (isDay || isMultiDayProduct(cur)) {
        dayDuration = dayDuration.add(current);
      } else {
        minuteDuration = minuteDuration.add(current);
      }
      return pre.add(current);
    }, new Decimal(0));
  }
  return {
    productExpectAmount: price.toNumber(),
    duration: getDiscountTimeByDayMinutes(dayDuration.toNumber(), minuteDuration.toNumber())
  };
};

/**
 * 计算单个商品的税费（返回精确值，不四舍五入）
 * @param item 商品信息
 * @param state 状态
 * @param options 选项
 * @returns 精确的税费值（Decimal类型）
 */
var getProductItemTax = function getProductItemTax(item, state, options) {
  var _bookingDetail$tax_ra, _ref, _bookingDetail$is_pri;
  var bookingDetail = state.bookingDetail;
  var tax_rate = options.tax_rate,
    is_price_include_tax = options.is_price_include_tax;

  // 折扣后的金额 = 商品金额 - 商品折扣
  var productDiscountPrice = new Decimal(item.total || 0);
  var quantity = new Decimal(item.quantity || 1);

  // 如果商品金额小于或等于0，不计算税费
  if (productDiscountPrice.lte(0)) {
    return new Decimal(0);
  }

  // 优先从 bookingDetail 取税率和是否含税设置，取不到则从 options 中取（兼容新增模式）
  // 注意：bookingDetail中的tax_rate不需要除以100，options 中的tax_rate需要除以100
  var currentTaxRate = new Decimal((_bookingDetail$tax_ra = bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.tax_rate) !== null && _bookingDetail$tax_ra !== void 0 ? _bookingDetail$tax_ra : tax_rate ? tax_rate / 100 : 0);
  var currentIsPriceIncludeTax = (_ref = (_bookingDetail$is_pri = bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.is_price_include_tax) !== null && _bookingDetail$is_pri !== void 0 ? _bookingDetail$is_pri : is_price_include_tax) !== null && _ref !== void 0 ? _ref : 0;
  var singleItemTax = new Decimal(0);

  // 计算单个商品税费, 一次性商品 is_charge_tax 可能为空
  if (item.is_charge_tax === 0 || !item.is_charge_tax) {
    // 该商品不需要收税
    singleItemTax = new Decimal(0);
  } else {
    // 该商品需要收税
    if (currentIsPriceIncludeTax === 0) {
      // 价格不含税：管理端填写的单价是不含税的价格
      singleItemTax = productDiscountPrice.times(currentTaxRate);
    } else {
      // 价格含税：管理端填写的单价是含税的价格
      // 含税总价 = 不含税价 + (不含税价 * 税率) = 不含税价 * (1 + 税率)
      // 商品不含税价 = 含税总价 / (1 + 税率)
      // 税 = 不含税价 * 税率
      var divisor = new Decimal(1).plus(currentTaxRate);
      if (divisor.lte(0)) {
        // 如果 (1 + 税率) <= 0，说明税率异常，不计算税费
        singleItemTax = new Decimal(0);
      } else {
        singleItemTax = productDiscountPrice.dividedBy(divisor).times(currentTaxRate);
      }
    }
  }

  // 结果 = 单个商品税费 × 数量（返回精确值，不四舍五入）
  return singleItemTax.times(quantity);
};

/**
 * 计算商品附加费 包含子商品的总附加费
 */
var getProductSurchargeFee = function getProductSurchargeFee(product) {
  var _extend = product._extend;
  if (!_extend) {
    return 0;
  }
  var surcharge_fee = _extend.surcharge_fee,
    relation_details = _extend.relation_details,
    other = _extend.other,
    surcharge_rounding_remainder = _extend.surcharge_rounding_remainder;
  var totalSurchargeFee = new Decimal(0);
  if (surcharge_fee) {
    totalSurchargeFee = totalSurchargeFee.plus(surcharge_fee);
  }
  if (surcharge_rounding_remainder) {
    totalSurchargeFee = totalSurchargeFee.plus(surcharge_rounding_remainder);
  }
  if (relation_details) {
    var _iterator4 = _createForOfIteratorHelper(relation_details),
      _step4;
    try {
      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
        var item = _step4.value;
        totalSurchargeFee = totalSurchargeFee.plus(getProductSurchargeFee(item));
      }
    } catch (err) {
      _iterator4.e(err);
    } finally {
      _iterator4.f();
    }
  }
  if (other !== null && other !== void 0 && other.bundle) {
    totalSurchargeFee = totalSurchargeFee.plus(other.bundle.reduce(function (total, item) {
      var surchargeFee = new Decimal(item.surcharge_fee || 0).times(item.num || item.quantity || 1);
      if (item.surcharge_rounding_remainder) {
        surchargeFee = surchargeFee.plus(item.surcharge_rounding_remainder);
      }
      return total.plus(surchargeFee);
    }, new Decimal(0)));
  }
  return totalSurchargeFee.toNumber();
};

/**
 * 处理商品税费计算（折扣前后）
 * 支持税费舍入差值追加到最后一个含税商品的 tax_fee_rounding_remainder / original_tax_fee_rounding_remainder 字段
 * @param items 商品数组
 * @param state 状态
 * @param options 选项
 * @param computed 计算结果
 * @returns 累积的税费信息
 */
var processItemsTax = function processItemsTax(items, state, options) {
  var tax_rate = options.tax_rate,
    is_price_include_tax = options.is_price_include_tax,
    computed = options.computed;
  var shopDiscount = computed.shopDiscount,
    productExpectAmount = computed.productExpectAmount;

  // 精确税费累加（不四舍五入）
  var preciseOriginTax = new Decimal(0);
  var preciseTax = new Decimal(0);
  // 四舍五入后的税费累加
  var roundedOriginTax = new Decimal(0);
  var roundedTax = new Decimal(0);

  /**
   * 最后一个含税商品的引用（按物理位置）
   * 用于追加税费舍入差值
   */
  var lastTaxableItem = null;
  var _iterator5 = _createForOfIteratorHelper(items),
    _step5;
  try {
    for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
      var _item$_extend, _item$_extend2, _item$_extend$other;
      var item = _step5.value;
      var quantity = new Decimal(item._extend.quantity || 1);
      var unitPrice = new Decimal(item._extend.total || 0);
      var mainProductPrice = new Decimal(getMainProductTotal(item) || 0);

      // 计算原始税费（折扣前）- 单个商品（精确值）
      var originalTaxPerItemPrecise = getProductItemTax(_objectSpread(_objectSpread({}, item), {}, {
        total: mainProductPrice.add(((_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.surcharge_fee) || 0).toNumber(),
        quantity: 1
      }), state, {
        tax_rate: tax_rate,
        is_price_include_tax: is_price_include_tax
      });

      // 计算平摊到该商品的折扣
      var itemDiscount = new Decimal(0);
      if (productExpectAmount > 0) {
        itemDiscount = unitPrice.dividedBy(productExpectAmount).times(shopDiscount);
      }

      // 按比例计算主商品应分摊的折扣
      var mainItemDiscount = new Decimal(0);
      if (unitPrice.greaterThan(0)) {
        mainItemDiscount = mainProductPrice.dividedBy(productExpectAmount).times(shopDiscount);
      }
      var mainItemDiscountedUnitPrice = mainProductPrice.minus(mainItemDiscount).add(((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.surcharge_fee) || 0);

      // 计算折后税费（折扣后）- 主商品的税费（精确值）
      var maxDiscountedTaxPerItemPrecise = getProductItemTax(_objectSpread(_objectSpread({}, item), {}, {
        total: mainItemDiscountedUnitPrice.toNumber(),
        price: item._extend.total,
        quantity: 1
      }), state, {
        tax_rate: tax_rate,
        is_price_include_tax: is_price_include_tax
      });

      // 四舍五入后的值
      var maxDiscountedTaxPerItemRounded = maxDiscountedTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);

      // 保存到商品扩展信息中（保留两位小数）
      item._extend.main_product_attached_bundle_tax_fee = maxDiscountedTaxPerItemRounded.toNumber();

      // 如果主商品有税费，记录为最后一个含税商品
      if (maxDiscountedTaxPerItemPrecise.gt(0)) {
        lastTaxableItem = {
          type: 'main',
          item: item
        };
      }

      // 注意：加时商品独立计算，不考虑主商品数量
      var addTimePreciseTax = new Decimal(0);
      var addTimeRoundedTax = new Decimal(0);
      if (Array.isArray(item._extend.relation_details)) {
        var _iterator6 = _createForOfIteratorHelper(item._extend.relation_details),
          _step6;
        try {
          for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
            var atItem = _step6.value;
            // 计算单件加时商品折扣后价格
            var _originTotal = new Decimal(atItem.selling_price || atItem.price || 0);
            var _discountedTotal = _originTotal;
            if (productExpectAmount > 0) {
              _discountedTotal = _originTotal.minus(_originTotal.dividedBy(productExpectAmount).times(shopDiscount));
            }
            var addTimeTaxPerItemPrecise = getProductItemTax(_objectSpread(_objectSpread({}, atItem), {}, {
              total: _discountedTotal.add((atItem === null || atItem === void 0 ? void 0 : atItem.surcharge_fee) || 0).toNumber(),
              quantity: atItem.product_quantity || atItem.num || 1
            }), state, {
              tax_rate: tax_rate,
              is_price_include_tax: is_price_include_tax
            });
            var addTimeTaxPerItemRounded = addTimeTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);

            // 保存到加时商品上（四舍五入后的值）
            atItem.tax_fee = addTimeTaxPerItemRounded.toNumber();
            addTimePreciseTax = addTimePreciseTax.plus(addTimeTaxPerItemPrecise);
            addTimeRoundedTax = addTimeRoundedTax.plus(addTimeTaxPerItemRounded);

            // 如果加时商品有税费，记录为最后一个含税商品
            if (addTimeTaxPerItemPrecise.gt(0)) {
              lastTaxableItem = {
                type: 'addTime',
                item: atItem
              };
            }
          }
        } catch (err) {
          _iterator6.e(err);
        } finally {
          _iterator6.f();
        }
      }

      // 处理 bundle 子商品（仅原价子商品）
      var bundlePreciseOriginTax = new Decimal(0);
      var bundlePreciseTax = new Decimal(0);
      var bundleRoundedOriginTax = new Decimal(0);
      var bundleRoundedTax = new Decimal(0);
      if (Array.isArray((_item$_extend$other = item._extend.other) === null || _item$_extend$other === void 0 ? void 0 : _item$_extend$other.bundle)) {
        var _iterator7 = _createForOfIteratorHelper(item._extend.other.bundle),
          _step7;
        try {
          for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
            var bundleItem = _step7.value;
            // 只处理原价的子商品
            if (getBundleItemIsOriginalPrice(bundleItem)) {
              var _ref2, _bundleItem$bundle_se;
              var bundleQuantity = new Decimal(bundleItem.quantity || 1);
              var bundleUnitPrice = new Decimal((_ref2 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref2 !== void 0 ? _ref2 : 0);

              // 计算原始税费（折扣前）- 单个商品（精确值）
              var bundleOriginalTaxPerItemPrecise = getProductItemTax(_objectSpread(_objectSpread({}, bundleItem), {}, {
                total: bundleUnitPrice.add((bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.surcharge_fee) || 0).toNumber(),
                quantity: 1
              }), state, {
                tax_rate: tax_rate,
                is_price_include_tax: is_price_include_tax
              });

              // 计算平摊到该bundle商品的折扣
              var bundleItemDiscount = new Decimal(0);
              if (productExpectAmount > 0) {
                bundleItemDiscount = bundleUnitPrice.dividedBy(productExpectAmount).times(shopDiscount);
              }

              // bundle商品折后单价
              var bundleDiscountedUnitPrice = bundleUnitPrice.minus(bundleItemDiscount).add((bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.surcharge_fee) || 0);

              // 计算折后税费（折扣后）- 单个商品（精确值）
              var bundleDiscountedTaxPerItemPrecise = getProductItemTax(_objectSpread(_objectSpread({}, bundleItem), {}, {
                total: bundleDiscountedUnitPrice.toNumber(),
                quantity: 1
              }), state, {
                tax_rate: tax_rate,
                is_price_include_tax: is_price_include_tax
              });

              // 四舍五入后的值
              var bundleOriginalTaxPerItemRounded = bundleOriginalTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
              var bundleDiscountedTaxPerItemRounded = bundleDiscountedTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);

              // 保存到bundle商品上（单个商品的税费，四舍五入后）
              bundleItem.original_tax_fee = bundleOriginalTaxPerItemRounded.toNumber();
              bundleItem.tax_fee = bundleDiscountedTaxPerItemRounded.toNumber();

              // 累加bundle税费（需要乘以bundle数量）
              bundlePreciseOriginTax = bundlePreciseOriginTax.plus(bundleOriginalTaxPerItemPrecise.times(bundleQuantity));
              bundlePreciseTax = bundlePreciseTax.plus(bundleDiscountedTaxPerItemPrecise.times(bundleQuantity));
              bundleRoundedOriginTax = bundleRoundedOriginTax.plus(bundleOriginalTaxPerItemRounded.times(bundleQuantity));
              bundleRoundedTax = bundleRoundedTax.plus(bundleDiscountedTaxPerItemRounded.times(bundleQuantity));

              // 如果bundle商品有税费，记录为最后一个含税商品
              if (bundleDiscountedTaxPerItemPrecise.gt(0)) {
                lastTaxableItem = {
                  type: 'bundle',
                  item: bundleItem
                };
              }
            }
          }
        } catch (err) {
          _iterator7.e(err);
        } finally {
          _iterator7.f();
        }
      }

      // 主商品的原始税费和折后税费（精确值）
      var originalTaxFeePrecise = originalTaxPerItemPrecise.plus(bundlePreciseOriginTax);
      var taxFeePrecise = maxDiscountedTaxPerItemPrecise.plus(bundlePreciseTax);

      // 主商品的原始税费和折后税费（四舍五入后）
      var originalTaxFeeRounded = originalTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).plus(bundleRoundedOriginTax);
      var taxFeeRounded = maxDiscountedTaxPerItemRounded.plus(bundleRoundedTax);

      // 保存到商品扩展信息中（四舍五入后的值）
      item._extend.original_tax_fee = originalTaxFeeRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
      item._extend.tax_fee = taxFeeRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();

      // 累加到总税费（乘以数量）
      preciseOriginTax = preciseOriginTax.plus(originalTaxFeePrecise.times(quantity)).plus(addTimePreciseTax);
      preciseTax = preciseTax.plus(taxFeePrecise.times(quantity)).plus(addTimePreciseTax);
      roundedOriginTax = roundedOriginTax.plus(originalTaxFeeRounded.times(quantity)).plus(addTimeRoundedTax);
      roundedTax = roundedTax.plus(taxFeeRounded.times(quantity)).plus(addTimeRoundedTax);
    }

    // 计算期望的总税费（精确累加后四舍五入）
  } catch (err) {
    _iterator5.e(err);
  } finally {
    _iterator5.f();
  }
  var expectedOriginTax = preciseOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
  var expectedTax = preciseTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);

  // 计算舍入差值
  var originTaxRemainder = expectedOriginTax.minus(roundedOriginTax).toNumber();
  var taxRemainder = expectedTax.minus(roundedTax).toNumber();

  // 将差值追加到最后一个含税商品
  if (lastTaxableItem) {
    if (originTaxRemainder !== 0) {
      if (lastTaxableItem.type === 'main') {
        lastTaxableItem.item._extend.original_tax_fee_rounding_remainder = originTaxRemainder;
      } else {
        lastTaxableItem.item.original_tax_fee_rounding_remainder = originTaxRemainder;
      }
    }
    if (taxRemainder !== 0) {
      if (lastTaxableItem.type === 'main') {
        lastTaxableItem.item._extend.tax_fee_rounding_remainder = taxRemainder;
      } else {
        lastTaxableItem.item.tax_fee_rounding_remainder = taxRemainder;
      }
    }
  }
  return {
    originTax: expectedOriginTax,
    tax: expectedTax
  };
};

/**
 * 清除税费相关字段
 * 在重新计算税费之前调用，避免残留数据影响计算结果
 */
var clearTaxFee = function clearTaxFee(state) {
  var service = state.service,
    addons = state.addons;
  if (Array.isArray(service === null || service === void 0 ? void 0 : service.value)) {
    var _iterator8 = _createForOfIteratorHelper(service.value),
      _step8;
    try {
      for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
        var _item$_extend$other2;
        var item = _step8.value;
        // 清除主商品税费字段
        item._extend.tax_fee = 0;
        item._extend.original_tax_fee = 0;
        item._extend.tax_fee_rounding_remainder = undefined;
        item._extend.main_product_attached_bundle_tax_fee = 0;

        // 清除 bundle 子商品税费字段
        var _iterator9 = _createForOfIteratorHelper(((_item$_extend$other2 = item._extend.other) === null || _item$_extend$other2 === void 0 ? void 0 : _item$_extend$other2.bundle) || []),
          _step9;
        try {
          for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
            var bundleItem = _step9.value;
            bundleItem.tax_fee = 0;
            bundleItem.original_tax_fee = 0;
            bundleItem.tax_fee_rounding_remainder = undefined;
          }

          // 清除加时商品税费字段
        } catch (err) {
          _iterator9.e(err);
        } finally {
          _iterator9.f();
        }
        var _iterator10 = _createForOfIteratorHelper(item._extend.relation_details || []),
          _step10;
        try {
          for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
            var relationDetail = _step10.value;
            relationDetail.tax_fee = 0;
            relationDetail.tax_fee_rounding_remainder = undefined;
          }
        } catch (err) {
          _iterator10.e(err);
        } finally {
          _iterator10.f();
        }
      }
    } catch (err) {
      _iterator8.e(err);
    } finally {
      _iterator8.f();
    }
  }
  if (Array.isArray(addons === null || addons === void 0 ? void 0 : addons.value)) {
    var _iterator11 = _createForOfIteratorHelper(addons.value),
      _step11;
    try {
      for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
        var _item2$_extend$other;
        var _item2 = _step11.value;
        // 清除主商品税费字段
        _item2._extend.tax_fee = 0;
        _item2._extend.original_tax_fee = 0;
        _item2._extend.tax_fee_rounding_remainder = undefined;
        _item2._extend.main_product_attached_bundle_tax_fee = 0;

        // 清除 bundle 子商品税费字段
        var _iterator12 = _createForOfIteratorHelper(((_item2$_extend$other = _item2._extend.other) === null || _item2$_extend$other === void 0 ? void 0 : _item2$_extend$other.bundle) || []),
          _step12;
        try {
          for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
            var _bundleItem = _step12.value;
            _bundleItem.tax_fee = 0;
            _bundleItem.original_tax_fee = 0;
            _bundleItem.tax_fee_rounding_remainder = undefined;
          }
        } catch (err) {
          _iterator12.e(err);
        } finally {
          _iterator12.f();
        }
      }
    } catch (err) {
      _iterator11.e(err);
    } finally {
      _iterator11.f();
    }
  }
};

/**
 * 税费
 * @param state
 * @param options 包含 isEdit、computed 和其他税费计算所需参数
 * @returns
 */
var getTax = function getTax(state, options) {
  var isEdit = options.isEdit,
    computed = options.computed,
    tax_rate = options.tax_rate,
    is_price_include_tax = options.is_price_include_tax;

  // 详情时未编辑的状态下, 取后端的值
  if (!isEdit) {
    var _state$bookingDetail2;
    return {
      tax: Number((_state$bookingDetail2 = state.bookingDetail) === null || _state$bookingDetail2 === void 0 ? void 0 : _state$bookingDetail2.tax_fee) || 0
    };
  }

  // 清除之前计算的税费数据
  clearTaxFee(state);
  var totalOriginTax = new Decimal(0);
  var totalTax = new Decimal(0);
  if (state !== null && state !== void 0 && state.service || state !== null && state !== void 0 && state.addons) {
    var _state$service3, _state$addons2;
    // 处理服务商品
    if (state !== null && state !== void 0 && (_state$service3 = state.service) !== null && _state$service3 !== void 0 && _state$service3.value) {
      var serviceResult = processItemsTax(state.service.value, state, {
        tax_rate: tax_rate,
        is_price_include_tax: is_price_include_tax,
        computed: computed
      });
      totalOriginTax = totalOriginTax.plus(serviceResult.originTax);
      totalTax = totalTax.plus(serviceResult.tax);
    }

    // 处理附加商品
    if (state !== null && state !== void 0 && (_state$addons2 = state.addons) !== null && _state$addons2 !== void 0 && _state$addons2.value) {
      var addonsResult = processItemsTax(state.addons.value, state, {
        tax_rate: tax_rate,
        is_price_include_tax: is_price_include_tax,
        computed: computed
      });
      totalOriginTax = totalOriginTax.plus(addonsResult.originTax);
      totalTax = totalTax.plus(addonsResult.tax);
    }
  }
  return {
    originTax: totalOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber(),
    tax: totalTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber()
  };
};

/**
 * 税费信息
 * @param state
 * @returns
 */
var getTaxInfo = function getTaxInfo(state, options) {
  var bookingDetail = state.bookingDetail;
  var tax_rate = options.tax_rate,
    tax_title = options.tax_title,
    is_price_include_tax = options.is_price_include_tax;
  return {
    title: (bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.tax_title) || tax_title,
    rate: (bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.tax_rate) || tax_rate / 100,
    is_price_include_tax: getIsPriceIncludeTax(state) || is_price_include_tax
  };
};
var getPaySurchargeFee = function getPaySurchargeFee(state) {
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;

  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  var processingFee = new Decimal(bookingDetail.pay_processing_fee || 0);
  var gatewayFee = new Decimal(bookingDetail.gateway_fee || 0);
  return processingFee.add(gatewayFee).toNumber();
};

/**
 * 判断商品是否符合附加费条件
 */
var isProductMatchSurchargeCondition = function isProductMatchSurchargeCondition(item, options) {
  var _options$ScheduleModu;
  if (!options.ScheduleModule) {
    console.warn('ScheduleModule not found!');
    return false;
  }
  //@ts-ignore
  var isInScheduleByDate = (_options$ScheduleModu = options.ScheduleModule) === null || _options$ScheduleModu === void 0 ? void 0 : _options$ScheduleModu.isInScheduleByDate;
  var surchargeConfig = options.surchargeConfig,
    _options$scheduleById = options.scheduleById,
    scheduleById = _options$scheduleById === void 0 ? {} : _options$scheduleById;
  var startDate = item.startDate,
    product_id = item.product_id,
    isCustomItem = item.isCustomItem;
  var _surchargeConfig$open = surchargeConfig.open_product,
    open_product = _surchargeConfig$open === void 0 ? 0 : _surchargeConfig$open,
    _surchargeConfig$is_a = surchargeConfig.is_all,
    is_all = _surchargeConfig$is_a === void 0 ? 0 : _surchargeConfig$is_a,
    _surchargeConfig$avai = surchargeConfig.available_product_ids,
    available_product_ids = _surchargeConfig$avai === void 0 ? [] : _surchargeConfig$avai,
    _surchargeConfig$open2 = surchargeConfig.open_schedule,
    open_schedule = _surchargeConfig$open2 === void 0 ? 0 : _surchargeConfig$open2,
    schedule_type = surchargeConfig.schedule_type,
    _surchargeConfig$avai2 = surchargeConfig.available_schedule_ids,
    available_schedule_ids = _surchargeConfig$avai2 === void 0 ? [] : _surchargeConfig$avai2;

  // 判断商品是否符合条件
  var isProductMatch = false;
  if (open_product === 0) {
    // 未开启商品限制，所有商品都符合
    isProductMatch = true;
  } else {
    // 开启了商品限制
    if (is_all === 1) {
      // 所有商品都收取附加费
      isProductMatch = true;
    } else {
      // 指定商品收取附加费
      if (isCustomItem) {
        // 自定义商品：如果是指定商品模式，自定义商品不符合条件
        // 因为自定义商品没有 product_id，无法匹配到指定商品列表
        isProductMatch = false;
      } else {
        // 普通商品：检查是否在指定商品列表中
        isProductMatch = available_product_ids.includes(product_id);
      }
    }
  }

  // 判断日程是否符合条件
  var isScheduleMatch = false;
  if (open_schedule === 0) {
    // 未开启日程限制，所有日程都符合
    isScheduleMatch = true;
  } else {
    // 开启了日程限制
    if (schedule_type === 'all') {
      // 所有日程都收取附加费
      isScheduleMatch = true;
    } else {
      // 指定日程收取附加费
      for (var j = 0; j < available_schedule_ids.length; j++) {
        var scheduleId = available_schedule_ids[j];
        var schedule = scheduleById[scheduleId];
        if (schedule) {
          var isInSchedule = isInScheduleByDate({
            date: (startDate === null || startDate === void 0 ? void 0 : startDate.format('YYYY-MM-DD HH:mm:ss')) || '',
            schedule: schedule
          });
          if (isInSchedule) {
            isScheduleMatch = true;
            break;
          }
        }
      }
    }
  }

  // 商品和日程条件都要满足（取交集）
  return isProductMatch && isScheduleMatch;
};

// bundle商品是否是原价
var getBundleItemIsOriginalPrice = function getBundleItemIsOriginalPrice(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';
};

// bundle商品是否是加价
var getBundleItemIsMarkupPrice = function getBundleItemIsMarkupPrice(item) {
  return (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));
};

// bundle商品是否是减价
var getBundleItemIsDiscountPrice = function getBundleItemIsDiscountPrice(item) {
  return (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));
};

// bundle商品是否是加价或减价
var getBundleItemIsMarkupOrDiscountPrice = function getBundleItemIsMarkupOrDiscountPrice(item) {
  return getBundleItemIsMarkupPrice(item) || getBundleItemIsDiscountPrice(item);
};
var getDiscountAmount = function getDiscountAmount(discounts) {
  return (discounts || []).reduce(function (total, discount) {
    return total.add(new Decimal(discount.amount || 0));
  }, new Decimal(0)).toNumber();
};
export var getOptionDiscountAmount = function getOptionDiscountAmount(discounts) {
  return (discounts || []).reduce(function (total, discount) {
    var _discount$metadata;
    return total.add(new Decimal((discount === null || discount === void 0 || (_discount$metadata = discount.metadata) === null || _discount$metadata === void 0 ? void 0 : _discount$metadata.optionDiscountAmount) || 0));
  }, new Decimal(0)).toNumber();
};

/**
 * 获取主商品加价减价后的总价 (主商品价格 + 子商品加价减价)
 */
var getMainProductTotal = function getMainProductTotal(item) {
  var _ref3, _ref4, _item$_extend$main_pr, _item$_extend3, _item$metadata, _item$_extend$other3, _item$_extend$other4, _item$_extend$other6;
  var total = new Decimal((_ref3 = (_ref4 = (_item$_extend$main_pr = (_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.main_product_selling_price) !== null && _item$_extend$main_pr !== void 0 ? _item$_extend$main_pr : item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.main_product_selling_price) !== null && _ref4 !== void 0 ? _ref4 : item._extend.price) !== null && _ref3 !== void 0 ? _ref3 : 0);

  // 单规格
  if ((_item$_extend$other3 = item._extend.other) !== null && _item$_extend$other3 !== void 0 && _item$_extend$other3.option && Array.isArray((_item$_extend$other4 = item._extend.other) === null || _item$_extend$other4 === void 0 ? void 0 : _item$_extend$other4.option)) {
    var _item$_extend$other5;
    total = total.add((_item$_extend$other5 = item._extend.other) === null || _item$_extend$other5 === void 0 ? void 0 : _item$_extend$other5.option.reduce(function (t, option) {
      return t.add(new Decimal(option.price || 0).mul(option.num || 1));
    }, new Decimal(0)));
    if (item.booking_id) {
      total = total.sub(getOptionDiscountAmount((item === null || item === void 0 ? void 0 : item.discount_list) || []));
    }
  }
  var _iterator13 = _createForOfIteratorHelper(((_item$_extend$other6 = item._extend.other) === null || _item$_extend$other6 === void 0 ? void 0 : _item$_extend$other6.bundle) || []),
    _step13;
  try {
    for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
      var bundleItem = _step13.value;
      if (getBundleItemIsMarkupOrDiscountPrice(bundleItem)) {
        var _ref5, _bundleItem$bundle_se2;
        // 子商品折扣金额
        var discountAmount = getDiscountAmount(bundleItem.discount_list);
        // 子商品价格
        var bundleItemPrice = new Decimal((_ref5 = (_bundleItem$bundle_se2 = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se2 !== void 0 ? _bundleItem$bundle_se2 : bundleItem.price) !== null && _ref5 !== void 0 ? _ref5 : 0);
        // todo: 套餐子商品后不需要处理 子商品价格 - 子商品折扣金额
        var bundleItemTotal = bundleItemPrice.minus(discountAmount);
        total = total.add(bundleItemTotal);
      }
    }
  } catch (err) {
    _iterator13.e(err);
  } finally {
    _iterator13.f();
  }
  return total.toNumber();
};

/**
 * 清除附加费
 */
var clearSurchargeFee = function clearSurchargeFee(state) {
  var service = state.service,
    addons = state.addons;
  if (Array.isArray(service === null || service === void 0 ? void 0 : service.value)) {
    var _iterator14 = _createForOfIteratorHelper(service.value),
      _step14;
    try {
      for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
        var _item$_extend$other7;
        var item = _step14.value;
        item._extend.surcharge_fee = 0;
        item._extend.surcharge_rounding_remainder = undefined;
        item._extend.relation_surcharge_ids = [];
        var _iterator15 = _createForOfIteratorHelper(((_item$_extend$other7 = item._extend.other) === null || _item$_extend$other7 === void 0 ? void 0 : _item$_extend$other7.bundle) || []),
          _step15;
        try {
          for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
            var bundleItem = _step15.value;
            bundleItem.surcharge_fee = 0;
            bundleItem.surcharge_rounding_remainder = undefined;
            bundleItem.relation_surcharge_ids = [];
          }
        } catch (err) {
          _iterator15.e(err);
        } finally {
          _iterator15.f();
        }
        var _iterator16 = _createForOfIteratorHelper(item._extend.relation_details || []),
          _step16;
        try {
          for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
            var relationDetail = _step16.value;
            relationDetail.surcharge_fee = 0;
            relationDetail.surcharge_rounding_remainder = undefined;
            relationDetail.relation_surcharge_ids = [];
          }
        } catch (err) {
          _iterator16.e(err);
        } finally {
          _iterator16.f();
        }
      }
    } catch (err) {
      _iterator14.e(err);
    } finally {
      _iterator14.f();
    }
  }
  if (Array.isArray(addons === null || addons === void 0 ? void 0 : addons.value)) {
    var _iterator17 = _createForOfIteratorHelper(addons.value),
      _step17;
    try {
      for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
        var _item3$_extend$other;
        var _item3 = _step17.value;
        _item3._extend.surcharge_fee = 0;
        _item3._extend.surcharge_rounding_remainder = undefined;
        _item3._extend.relation_surcharge_ids = [];
        var _iterator18 = _createForOfIteratorHelper(((_item3$_extend$other = _item3._extend.other) === null || _item3$_extend$other === void 0 ? void 0 : _item3$_extend$other.bundle) || []),
          _step18;
        try {
          for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
            var _bundleItem2 = _step18.value;
            _bundleItem2.surcharge_fee = 0;
            _bundleItem2.surcharge_rounding_remainder = undefined;
            _bundleItem2.relation_surcharge_ids = [];
          }
        } catch (err) {
          _iterator18.e(err);
        } finally {
          _iterator18.f();
        }
      }
    } catch (err) {
      _iterator17.e(err);
    } finally {
      _iterator17.f();
    }
  }
};

/**
 * 订单附加费各项信息
 * @param state
 * @param options 包含 ScheduleModule 和其他附加费计算所需参数
 */
var getSurcharge = function getSurcharge(state, options) {
  var isEdit = options.isEdit,
    ScheduleModule = options.ScheduleModule,
    surcharge_list = options.surcharge_list,
    scheduleById = options.scheduleById;
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;
  // 编辑状态, 且未修改商品时直接从详情取出
  if (!isEdit && bookingId) {
    if (Array.isArray(bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.surcharge)) {
      var _state$bookingDetail3;
      return (((_state$bookingDetail3 = state.bookingDetail) === null || _state$bookingDetail3 === void 0 ? void 0 : _state$bookingDetail3.surcharge) || []).filter(function (d) {
        return Number(d.amount) > 0;
      }).map(function (d, index) {
        return {
          key: "custom_surcharge_".concat(index),
          label: d.name[state.locale || 'en'] || d.name['en'] || d.name['original'],
          value: d.amount,
          name: d.name,
          surcharge_id: d.id,
          description: d.description,
          // 后端说这个固定传 default
          type: 'default',
          fixed: d.fixed,
          amount: d.amount,
          percentage: d.percentage
        };
      });
    }
    return [];
  }
  // 清除附加费
  clearSurchargeFee(state);

  // 新增状态
  var service = state.service,
    addons = state.addons;
  // 无附加费规则
  if (!Array.isArray(surcharge_list) || !(surcharge_list !== null && surcharge_list !== void 0 && surcharge_list.length)) return [];

  // 分别计算每种附加费总和
  var surchargeWithAmount = [];

  // 遍历每种附加费配置
  for (var i = 0; i < surcharge_list.length; i++) {
    var surchargeConfig = surcharge_list[i];
    var _surchargeConfig$perc = surchargeConfig.percentage,
      percentage = _surchargeConfig$perc === void 0 ? '0' : _surchargeConfig$perc,
      _surchargeConfig$fixe = surchargeConfig.fixed,
      fixed = _surchargeConfig$fixe === void 0 ? '0' : _surchargeConfig$fixe,
      id = surchargeConfig.id,
      type = surchargeConfig.type,
      description = surchargeConfig.description,
      open_product = surchargeConfig.open_product;

    // 收集所有符合条件的商品
    var matchedItems = [];

    // 检查service中符合条件的商品
    if (Array.isArray(service === null || service === void 0 ? void 0 : service.value)) {
      var _iterator19 = _createForOfIteratorHelper(service.value),
        _step19;
      try {
        for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
          var _item$_extend$other8;
          var item = _step19.value;
          // 主商品符合附加费条件
          if (isProductMatchSurchargeCondition({
            isCustomItem: item.isCustomItem,
            startDate: item._extend.startDate,
            product_id: item.product_id
          }, {
            surchargeConfig: surchargeConfig,
            scheduleById: scheduleById || {},
            ScheduleModule: ScheduleModule
          })) {
            // 主商品加价减价后的总价
            var total = getMainProductTotal(item);
            var mainQuantity = item._extend.quantity || 1;
            matchedItems.push({
              total: total,
              // addTimeTotal: getRelationDetailsTotal(
              //   item._extend.relation_details || []
              // ),
              isMain: true,
              quantity: mainQuantity,
              item: item,
              mainQuantity: mainQuantity // 主商品的mainQuantity等于自己的quantity
            });
          }
          // 遍历子商品 原价商品符合附加费条件
          var _iterator20 = _createForOfIteratorHelper(((_item$_extend$other8 = item._extend.other) === null || _item$_extend$other8 === void 0 ? void 0 : _item$_extend$other8.bundle) || []),
            _step20;
          try {
            for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) {
              var bundleItem = _step20.value;
              // bundle商品是原价且符合附加费条件
              if (getBundleItemIsOriginalPrice(bundleItem) && isProductMatchSurchargeCondition({
                isCustomItem: false,
                startDate: item._extend.startDate,
                product_id: bundleItem._bundle_product_id
              }, {
                surchargeConfig: surchargeConfig,
                scheduleById: scheduleById || {},
                ScheduleModule: ScheduleModule
              })) {
                var _ref6, _bundleItem$bundle_se3;
                var _mainQuantity = item._extend.quantity || 1;
                matchedItems.push({
                  isMain: false,
                  total: Number((_ref6 = (_bundleItem$bundle_se3 = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se3 !== void 0 ? _bundleItem$bundle_se3 : bundleItem.price) !== null && _ref6 !== void 0 ? _ref6 : 0),
                  quantity: bundleItem.num || bundleItem.quantity || 1,
                  item: bundleItem,
                  mainQuantity: _mainQuantity // 子商品的mainQuantity是所属主商品的quantity
                });
              }
            }

            // 加时商品符合附加费条件
          } catch (err) {
            _iterator20.e(err);
          } finally {
            _iterator20.f();
          }
          var _iterator21 = _createForOfIteratorHelper(item._extend.relation_details || []),
            _step21;
          try {
            for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) {
              var relationDetail = _step21.value;
              if (isProductMatchSurchargeCondition({
                isCustomItem: false,
                startDate: item._extend.startDate,
                product_id: relationDetail.product_id
              }, {
                surchargeConfig: surchargeConfig,
                scheduleById: scheduleById || {},
                ScheduleModule: ScheduleModule
              })) {
                var _relationDetail$metad;
                matchedItems.push({
                  isMain: false,
                  total: Number((relationDetail === null || relationDetail === void 0 ? void 0 : relationDetail.price) || (relationDetail === null || relationDetail === void 0 || (_relationDetail$metad = relationDetail.metadata) === null || _relationDetail$metad === void 0 ? void 0 : _relationDetail$metad.main_product_attached_bundle_selling_price)),
                  quantity: relationDetail.num || relationDetail.quantity || 1,
                  item: relationDetail,
                  mainQuantity: 1 // 加时商品不受主商品数量影响
                });
              }
            }
          } catch (err) {
            _iterator21.e(err);
          } finally {
            _iterator21.f();
          }
        }
      } catch (err) {
        _iterator19.e(err);
      } finally {
        _iterator19.f();
      }
    }

    // 检查addons中符合条件的商品
    if (Array.isArray(addons === null || addons === void 0 ? void 0 : addons.value)) {
      var _iterator22 = _createForOfIteratorHelper(addons.value),
        _step22;
      try {
        for (_iterator22.s(); !(_step22 = _iterator22.n()).done;) {
          var _item4 = _step22.value;
          if (isProductMatchSurchargeCondition(_item4, {
            surchargeConfig: surchargeConfig,
            scheduleById: scheduleById || {},
            ScheduleModule: ScheduleModule
          })) {
            matchedItems.push({
              isMain: true,
              total: Number(_item4._extend.total),
              quantity: _item4._extend.quantity || 1,
              item: _item4,
              mainQuantity: 1 // addons独立商品，mainQuantity为1
            });
          }
        }
      } catch (err) {
        _iterator22.e(err);
      } finally {
        _iterator22.f();
      }
    }
    var finalAmount = 0;

    // 计算商品总数：主商品和addons按quantity计算，子商品（bundle item）需要乘以主商品数量
    var productCount = matchedItems.reduce(function (total, item) {
      if (item.isMain) {
        // 主商品和addons商品
        return total + (item.quantity || 1);
      } else {
        // 子商品（bundle item）和加时商品
        // 加时商品的 mainQuantity = 1，所以不受影响
        // bundle item 的 mainQuantity = 主商品数量，需要乘以实际数量
        return total + (item.quantity || 1) * (item.mainQuantity || 1);
      }
    }, 0);

    // 追加进入的固定附加费总值
    var fixedTotal = new Decimal(0);
    // 追加到商品的附加费总值 用于追加抹平字段
    var productTotalSurcharge = new Decimal(0);
    if (matchedItems.length > 0) {
      // 基于每个商品计算附加费：max(0, 商品价格) * rate + fixed
      var configTotal = new Decimal(0);

      // 计算固定附加费 - 只加一次
      if (fixed && new Decimal(fixed).gt(0)) {
        configTotal = configTotal.plus(fixed);
      }

      // 计算百分比附加费 - 对每个商品单独计算
      if (percentage && new Decimal(percentage).gt(0) || fixed) {
        var percentageRate = new Decimal(percentage);
        var _iterator23 = _createForOfIteratorHelper(matchedItems.entries()),
          _step23;
        try {
          for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) {
            var _step23$value = _slicedToArray(_step23.value, 2),
              index = _step23$value[0],
              _item5 = _step23$value[1];
            var isLast = index === matchedItems.length - 1;
            // 对每个商品：max(0, 价格) * 数量 * 费率
            var itemPrice = new Decimal(Math.max(0, _item5.total || 0));
            var itemQuantity = new Decimal(_item5.isMain ? _item5.quantity || 1 : _item5.quantity * _item5.mainQuantity || 1);
            var addTimeTotal = new Decimal(_item5.addTimeTotal || 0);
            // 单个商品总附加费
            var itemTotalSurcharge = itemPrice.times(itemQuantity).plus(addTimeTotal).times(percentageRate);
            configTotal = configTotal.plus(itemTotalSurcharge);

            // 单个商品单数量附加费
            var itemSurcharge = itemPrice.times(percentageRate);

            // 固定附加费 = 1 / 商品数量 * 固定附加费（向下取整保留两位小数）
            // 固定附加费的平摊计算逻辑
            // 一个商品内，不管他本身有多少数量 以及他 bundle 有多少，都应该累加成为一个数量总数
            // 以这个总数为基础去平摊每个商品应该占这一笔固定附加费的多少
            var fixedSurcharge = new Decimal(1).div(productCount).times(fixed).times(100).floor().div(100).toFixed(2);
            var quantity = _item5.isMain ? _item5.quantity : _item5.quantity * _item5.mainQuantity;
            fixedTotal = fixedTotal.plus(new Decimal(fixedSurcharge).times(quantity).toNumber());

            // 如果是最后一个商品 判断fixed - fixedTotal 是否有剩余小数 如果有的话，追加抹平字段
            if (isLast && fixedTotal.gt(0)) {
              var remaining = new Decimal(fixed).minus(fixedTotal).toNumber();
              if (remaining > 0) {
                productTotalSurcharge = productTotalSurcharge.plus(remaining);
                if (_item5.isMain) {
                  _item5.item._extend.surcharge_rounding_remainder = remaining;
                } else {
                  _item5.item.surcharge_rounding_remainder = remaining;
                }
              }
            }
            // 只有当 open_product !== 0 时，才将附加费追加到商品身上
            // open_product === 0 表示商品未开启该附加费，只在订单级别累加
            if (open_product !== 0) {
              if (_item5.isMain) {
                var _item5$item$_extend;
                var originSurchargeFee = new Decimal(_item5.item._extend.surcharge_fee || 0);
                // 保留两位小数
                var surchargeFee = originSurchargeFee.plus(itemSurcharge).plus(fixedSurcharge).toDecimalPlaces(2, Decimal.ROUND_DOWN).toNumber();
                productTotalSurcharge = productTotalSurcharge.plus(new Decimal(surchargeFee).times(itemQuantity).toNumber());
                _item5.item._extend.surcharge_fee = surchargeFee;
                _item5.item._extend.relation_surcharge_ids = [].concat(_toConsumableArray(((_item5$item$_extend = _item5.item._extend) === null || _item5$item$_extend === void 0 ? void 0 : _item5$item$_extend.relation_surcharge_ids) || []), [id]);
              } else {
                var _item5$item;
                var _originSurchargeFee = new Decimal(_item5.item.surcharge_fee || 0);
                // 保留两位小数
                var _surchargeFee = _originSurchargeFee.plus(itemSurcharge).plus(fixedSurcharge).toDecimalPlaces(2, Decimal.ROUND_DOWN).toNumber();
                productTotalSurcharge = productTotalSurcharge.plus(new Decimal(_surchargeFee).times(itemQuantity).toNumber());
                _item5.item.surcharge_fee = _surchargeFee;
                _item5.item.relation_surcharge_ids = [].concat(_toConsumableArray(((_item5$item = _item5.item) === null || _item5$item === void 0 ? void 0 : _item5$item.relation_surcharge_ids) || []), [id]);
              }
            }
            // 最后一个商品 判断configTotal - productTotalSurcharge 是否有剩余小数 如果有的话，追加抹平字段
            if (isLast && configTotal.minus(productTotalSurcharge).gt(0)) {
              // 四舍五入configTotal
              var configTotalRounded = configTotal.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
              if (_item5.isMain) {
                var newRoundingRemainder = new Decimal(_item5.item._extend.surcharge_rounding_remainder || 0);
                newRoundingRemainder = newRoundingRemainder.plus(configTotalRounded.minus(productTotalSurcharge));
                _item5.item._extend.surcharge_rounding_remainder = newRoundingRemainder.toNumber();
              } else {
                var _newRoundingRemainder = new Decimal(_item5.item.surcharge_rounding_remainder || 0);
                _newRoundingRemainder = _newRoundingRemainder.plus(configTotalRounded.minus(productTotalSurcharge));
                _item5.item.surcharge_rounding_remainder = _newRoundingRemainder.toNumber();
              }
            }
          }
        } catch (err) {
          _iterator23.e(err);
        } finally {
          _iterator23.f();
        }
      }

      // 如果该配置有金额，则添加到结果中
      finalAmount = configTotal.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
    }
    var name = surchargeConfig.name || {};
    if (Number(finalAmount) <= 0) {
      continue;
    }
    surchargeWithAmount.push({
      key: "custom_surcharge_".concat(i),
      label: name[state.locale || 'en'] || name['en'] || name['original'],
      name: name,
      value: finalAmount,
      surcharge_id: id,
      description: description,
      // 后端说固定传 default
      type: 'default',
      fixed: fixed,
      amount: finalAmount,
      percentage: percentage,
      metadata: {
        open_product: open_product
      }
    });
  }
  return surchargeWithAmount;
};

/**
 * 订单附加费
 * @param state
 * @returns
 */
var getSurchargeAmount = function getSurchargeAmount(state, surcharge, options) {
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;
  var isEdit = options.isEdit;
  // 订单未变更过
  if (!isEdit) {
    // 有后端数据则直接使用后端的数据
    if (bookingDetail && bookingId) {
      return Number(bookingDetail.surcharge_fee);
    }
  }
  if (!Array.isArray(surcharge)) return 0;
  // 新增状态使用 getSurcharge 的返回值进行求和
  return surcharge.reduce(function (total, item) {
    return total + (item.value || 0);
  }, 0);
};

/**
 * 已付金额 包含手续费
 * @param state
 * @returns
 */
var getPaidAmount = function getPaidAmount(state) {
  var _state$paymentPaid, _state$bookingDetail4;
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;

  // 检测是否有 checkout 编辑订单已付金额
  if ((_state$paymentPaid = state.paymentPaid) !== null && _state$paymentPaid !== void 0 && (_state$paymentPaid = _state$paymentPaid.value) !== null && _state$paymentPaid !== void 0 && _state$paymentPaid.paidAmount) {
    var _state$paymentPaid2;
    return (_state$paymentPaid2 = state.paymentPaid) === null || _state$paymentPaid2 === void 0 || (_state$paymentPaid2 = _state$paymentPaid2.value) === null || _state$paymentPaid2 === void 0 ? void 0 : _state$paymentPaid2.paidAmount;
  }
  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  return Number((_state$bookingDetail4 = state.bookingDetail) === null || _state$bookingDetail4 === void 0 ? void 0 : _state$bookingDetail4.paid_amount) || 0;
};

/**
 * 订单已付金额  不包含手续费
 * @param state
 * @returns
 */
var getOrderPaidAmount = function getOrderPaidAmount(state) {
  var _state$paymentPaid3, _state$bookingDetail5;
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;
  // 检测是否有 checkout 编辑订单已付金额
  if ((_state$paymentPaid3 = state.paymentPaid) !== null && _state$paymentPaid3 !== void 0 && (_state$paymentPaid3 = _state$paymentPaid3.value) !== null && _state$paymentPaid3 !== void 0 && _state$paymentPaid3.paidAmountWithoutSurcharge) {
    var _state$paymentPaid4;
    return (_state$paymentPaid4 = state.paymentPaid) === null || _state$paymentPaid4 === void 0 || (_state$paymentPaid4 = _state$paymentPaid4.value) === null || _state$paymentPaid4 === void 0 ? void 0 : _state$paymentPaid4.paidAmountWithoutSurcharge;
  }
  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  return Number((_state$bookingDetail5 = state.bookingDetail) === null || _state$bookingDetail5 === void 0 ? void 0 : _state$bookingDetail5.order_paid_amount) || 0;
};
export var getIsPriceIncludeTax = function getIsPriceIncludeTax(state) {
  var _state$bookingDetail$, _state$bookingDetail6;
  return (_state$bookingDetail$ = (_state$bookingDetail6 = state.bookingDetail) === null || _state$bookingDetail6 === void 0 ? void 0 : _state$bookingDetail6.is_price_include_tax) !== null && _state$bookingDetail$ !== void 0 ? _state$bookingDetail$ : 0;
};
var getExpectAmount = function getExpectAmount(_ref7) {
  var price = _ref7.price,
    tax = _ref7.tax,
    surchargeAmount = _ref7.surchargeAmount,
    shopDiscount = _ref7.shopDiscount,
    state = _ref7.state,
    options = _ref7.options;
  var _tax = tax;
  // 如果价格含税, 则将税费改为0
  if (getIsPriceIncludeTax(state) || options !== null && options !== void 0 && options.is_price_include_tax) {
    _tax = 0;
  }
  // 商品价格 + 税费 + 附加费 - 整单折扣
  return price + _tax + surchargeAmount - shopDiscount;
};
var getTotalRefundAmount = function getTotalRefundAmount(state) {
  var _state$bookingDetail7;
  return Number((_state$bookingDetail7 = state.bookingDetail) === null || _state$bookingDetail7 === void 0 ? void 0 : _state$bookingDetail7.total_refund_amount) || 0;
};
var getShopDiscount = function getShopDiscount(state) {
  var _state$bookingDetail8;
  // 优先使用手动设置的折扣（字符串格式），否则使用bookingDetail中的折扣
  return Number(state.shop_discount) || Number((_state$bookingDetail8 = state.bookingDetail) === null || _state$bookingDetail8 === void 0 ? void 0 : _state$bookingDetail8.shop_discount) || 0;
};
var getRoundingAmount = function getRoundingAmount(state) {
  var _state$bookingDetail9;
  return Number(state === null || state === void 0 || (_state$bookingDetail9 = state.bookingDetail) === null || _state$bookingDetail9 === void 0 ? void 0 : _state$bookingDetail9.rounding_amount) || 0;
};
var getSumTotalAmount = function getSumTotalAmount(_ref8) {
  var expectAmount = _ref8.expectAmount,
    roundingAmount = _ref8.roundingAmount;
  return expectAmount + roundingAmount;
};

/**
 * 总金额
 * @param state
 * @param options isEdit: 预约信息是否发生变动
 * @returns
 */
export var getSumTotal = function getSumTotal(state, options) {
  // 商品总金额,   包含 商品折扣 报价单 子商品
  var _getProductExpectAmou = getProductExpectAmount(state, options.isEdit),
    productExpectAmount = _getProductExpectAmou.productExpectAmount,
    duration = _getProductExpectAmou.duration;

  // 整单折扣金额
  var shopDiscount = getShopDiscount(state);

  // 舍入金额, 新增时不处理, 支付后才会产生
  var roundingAmount = getRoundingAmount(state);

  // 支付手续费, 新增时不处理, 支付后才会产生
  var paySurchargeFee = getPaySurchargeFee(state);

  // 订单附加费列表
  var surcharge = getSurcharge(state, options);
  // 订单附加费金额
  var surchargeAmount = getSurchargeAmount(state, surcharge, options);

  // 算出整单折扣的百分比 shopDiscount / productExpectAmount
  var computed = {
    productExpectAmount: productExpectAmount,
    shopDiscount: shopDiscount
  };
  // 税费
  var _getTax = getTax(state, _objectSpread({
      computed: computed
    }, options)),
    tax = _getTax.tax,
    originTax = _getTax.originTax;
  var taxInfo = getTaxInfo(state, options);

  // 已付金额 (包含手续费)
  var paidAmount = getPaidAmount(state);

  // 订单实际已支付金额
  var orderPaidAmount = getOrderPaidAmount(state);

  // 退款金额
  var totalRefundAmount = getTotalRefundAmount(state);

  // 总计(总订单金额) 商品金额 + 税费 + 附加费
  var expectAmount = getExpectAmount({
    price: productExpectAmount,
    tax: tax,
    surchargeAmount: surchargeAmount,
    shopDiscount: shopDiscount,
    state: state,
    options: options
  });

  // 订单原价（不包含整单折扣的价格）
  var originExpectAmount = getExpectAmount({
    price: productExpectAmount,
    tax: originTax,
    surchargeAmount: surchargeAmount,
    shopDiscount: 0,
    state: state,
    options: options
  });

  // 商品原价 不包含折扣
  var _getProductExpectAmou2 = getProductExpectAmount(state, options.isEdit, true),
    productExpectAmountWithoutDiscount = _getProductExpectAmou2.productExpectAmount;

  // 订单原价 不包含整单折扣 不包含商品券折扣卡抵扣
  var originExpectAmountWithoutDiscount = getExpectAmount({
    price: productExpectAmountWithoutDiscount,
    tax: originTax,
    surchargeAmount: surchargeAmount,
    shopDiscount: 0,
    state: state,
    options: options
  });

  // 总支付金额  总计
  var sumTotalAmount = getSumTotalAmount({
    expectAmount: expectAmount,
    roundingAmount: roundingAmount
  });

  // 未支付的金额  负数代表着欠款
  var sumTotalAmountDecimal = new Decimal(formatAmount(sumTotalAmount, 2, '') || 0);
  var orderPaidAmountDecimal = new Decimal(orderPaidAmount || 0);
  var notPaidAmount = sumTotalAmountDecimal.sub(orderPaidAmountDecimal).toNumber();

  // 实付金额    已付金额
  var actualPaidAmount = paidAmount;

  // 欠款金额
  var dueAmount = notPaidAmount < 0 ? Number(formatAmount(new Decimal(notPaidAmount).add(new Decimal(totalRefundAmount)).toNumber(), 2, '')) : 0;
  return {
    productAmount: productExpectAmount,
    duration: duration,
    tax: tax,
    taxInfo: taxInfo,
    shopDiscount: shopDiscount,
    // 附加费详情
    surcharge: surcharge,
    // 附加费
    otherAmount: surchargeAmount,
    sumTotalAmount: sumTotalAmount,
    paidAmount: paidAmount,
    notPaidAmount: notPaidAmount,
    paySurchargeFee: paySurchargeFee,
    expectAmount: expectAmount,
    actualPaidAmount: actualPaidAmount,
    orderPaidAmount: orderPaidAmount,
    totalRefundAmount: totalRefundAmount,
    dueAmount: dueAmount,
    roundingAmount: roundingAmount,
    originExpectAmount: originExpectAmount,
    // 订单原价 不包含整单折扣 不包含商品券折扣卡抵扣
    originExpectAmountWithoutDiscount: originExpectAmountWithoutDiscount
  };
};