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 _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); }
import Decimal from 'decimal.js';
import { getSurcharge, getSurchargeAmount } from "../Summary/utils";
function toDecimal(value) {
  return new Decimal(value || 0);
}
function toFixed2(value) {
  return new Decimal(value || 0).toFixed(2);
}
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 _ref, _item$original_price, _item$bundle_selling_;
    var quantity = getSafeNum(item === null || item === void 0 ? void 0 : item.num);
    var price = useOriginal ? toDecimal((_ref = (_item$original_price = item === null || item === void 0 ? void 0 : item.original_price) !== null && _item$original_price !== void 0 ? _item$original_price : item === null || item === void 0 ? void 0 : item.product_price) !== null && _ref !== void 0 ? _ref : item === null || item === void 0 ? void 0 : item.price) : toDecimal((_item$bundle_selling_ = item === null || item === void 0 ? void 0 : item.bundle_selling_price) !== null && _item$bundle_selling_ !== void 0 ? _item$bundle_selling_ : item === null || item === void 0 ? void 0 : item.price);
    return sum.plus(price.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 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);
    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_option_item: product.product_option_item || []
        }
      },
      bundle: product.product_bundle || [],
      option: product.product_option_item || [],
      options: product.product_option_item || [],
      relation_details: [],
      metadata: product.metadata || {},
      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 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 _iterator = _createForOfIteratorHelper(products),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var product = _step.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 _iterator3 = _createForOfIteratorHelper(collectDepositPolicyIds(depositData)),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var id = _step3.value;
          policyIds.add(id);
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
      var _iterator4 = _createForOfIteratorHelper(collectDepositPolicyData(depositData)),
        _step4;
      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var policy = _step4.value;
          if (!policyDataMap.has(policy.id)) {
            policyDataMap.set(policy.id, policy);
          }
          policyIds.add(policy.id);
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  if (!hasDeposit) return undefined;
  var _iterator2 = _createForOfIteratorHelper(policyIds),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var _id = _step2.value;
      if (!policyDataMap.has(_id)) {
        policyDataMap.set(_id, {
          id: _id,
          title: ''
        });
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.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、含主商品折扣、含加价/减价 bundle）。
 *
 * 新语义 v2 下：
 * - `metadata.main_product_selling_price` 已是"含 option、含折扣"的主价，直接读即可；
 * - 无需再 `minus(mainDiscountAmount)` 或 `plus(getOptionUnitPrice)`；
 * - 仅需叠加 `markup` / `markdown` 类 bundle（原价 bundle 已由 `calculateProductsTax` 独立处理）。
 */
function getMainProductPaymentTotal(product) {
  var _ref2, _product$metadata$mai, _product$metadata7, _product$metadata8;
  var mainSelling = (_ref2 = (_product$metadata$mai = (_product$metadata7 = product.metadata) === null || _product$metadata7 === void 0 ? void 0 : _product$metadata7.main_product_selling_price) !== null && _product$metadata$mai !== void 0 ? _product$metadata$mai : (_product$metadata8 = product.metadata) === null || _product$metadata8 === void 0 ? void 0 : _product$metadata8.main_product_original_price) !== null && _ref2 !== void 0 ? _ref2 : 0;
  var total = toDecimal(mainSelling);
  var bundleItems = product.product_bundle || [];
  var _iterator5 = _createForOfIteratorHelper(bundleItems),
    _step5;
  try {
    for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
      var bundleItem = _step5.value;
      if (isBundleMarkupOrDiscount(bundleItem)) {
        var _ref3, _bundleItem$bundle_se, _bundleItem$num;
        var unit = toDecimal((_ref3 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref3 !== void 0 ? _ref3 : 0);
        var qty = getSafeNum((_bundleItem$num = bundleItem.num) !== null && _bundleItem$num !== void 0 ? _bundleItem$num : bundleItem.quantity);
        total = total.plus(unit.times(qty));
      }
    }
  } catch (err) {
    _iterator5.e(err);
  } finally {
    _iterator5.f();
  }
  return Decimal.max(total, 0);
}

/**
 * 遍历所有商品计算税费，回写 tax_fee 到每个商品及 bundle 原价子商品，处理舍入差值。
 * 参照 Summary/utils.ts 的 processItemsTax，适配 SalesSummaryProduct 结构。
 */
function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
  var rate = new Decimal(taxRate);
  var preciseTax = new Decimal(0);
  var roundedTax = new Decimal(0);
  var preciseOriginTax = new Decimal(0);
  var roundedOriginTax = new Decimal(0);
  var lastTaxableItem = null;
  var _iterator6 = _createForOfIteratorHelper(products),
    _step6;
  try {
    for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
      var _product$is_charge_ta2, _product$is_charge_ta3;
      var product = _step6.value;
      var quantity = new Decimal(getSafeNum(product.num));

      // --- 主商品折后税费 ---
      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 = mainTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
      if (mainTaxPrecise.gt(0)) {
        lastTaxableItem = {
          type: 'main',
          item: product
        };
      }

      // --- 主商品原价税费 ---
      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
      });

      // --- bundle 原价子商品独立计税 ---
      var bundlePreciseTax = new Decimal(0);
      var bundleRoundedTax = new Decimal(0);
      var bundlePreciseOriginTax = new Decimal(0);
      var bundleRoundedOriginTax = new Decimal(0);
      var bundleItems = product.product_bundle || [];
      var _iterator7 = _createForOfIteratorHelper(bundleItems),
        _step7;
      try {
        for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
          var _bundleItem$num2, _ref4, _bundleItem$bundle_se2, _ref5, _ref6, _bundleItem$original_, _ref7, _bundleItem$is_charge, _ref8, _bundleItem$is_charge2;
          var bundleItem = _step7.value;
          if (!isBundleOriginalPrice(bundleItem)) continue;
          var bundleQuantity = new Decimal(getSafeNum((_bundleItem$num2 = bundleItem.num) !== null && _bundleItem$num2 !== void 0 ? _bundleItem$num2 : bundleItem.quantity));
          var bundlePrice = toDecimal((_ref4 = (_bundleItem$bundle_se2 = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se2 !== void 0 ? _bundleItem$bundle_se2 : bundleItem.price) !== null && _ref4 !== void 0 ? _ref4 : 0);
          var bundleOriginalPrice = toDecimal((_ref5 = (_ref6 = (_bundleItem$original_ = bundleItem.original_price) !== null && _bundleItem$original_ !== void 0 ? _bundleItem$original_ : bundleItem.product_price) !== null && _ref6 !== void 0 ? _ref6 : bundleItem.price) !== null && _ref5 !== void 0 ? _ref5 : 0);
          var bundleTaxPrecise = calculateSingleItemTax({
            price: bundlePrice,
            taxRate: rate,
            isPriceIncludeTax: isPriceIncludeTax,
            isChargeTax: (_ref7 = (_bundleItem$is_charge = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge !== void 0 ? _bundleItem$is_charge : product.is_charge_tax) !== null && _ref7 !== void 0 ? _ref7 : 0
          });
          var bundleTaxRounded = bundleTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
          var bundleOrigTaxPrecise = calculateSingleItemTax({
            price: bundleOriginalPrice,
            taxRate: rate,
            isPriceIncludeTax: isPriceIncludeTax,
            isChargeTax: (_ref8 = (_bundleItem$is_charge2 = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge2 !== void 0 ? _bundleItem$is_charge2 : product.is_charge_tax) !== null && _ref8 !== void 0 ? _ref8 : 0
          });
          var bundleOrigTaxRounded = bundleOrigTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
          bundleItem.tax_fee = bundleTaxRounded.toNumber();
          bundleItem.original_tax_fee = bundleOrigTaxRounded.toNumber();
          bundlePreciseTax = bundlePreciseTax.plus(bundleTaxPrecise.times(bundleQuantity));
          bundleRoundedTax = bundleRoundedTax.plus(bundleTaxRounded.times(bundleQuantity));
          bundlePreciseOriginTax = bundlePreciseOriginTax.plus(bundleOrigTaxPrecise.times(bundleQuantity));
          bundleRoundedOriginTax = bundleRoundedOriginTax.plus(bundleOrigTaxRounded.times(bundleQuantity));
          if (bundleTaxPrecise.gt(0)) {
            lastTaxableItem = {
              type: 'bundle',
              item: bundleItem
            };
          }
        }

        // --- 汇总到商品级 ---
      } catch (err) {
        _iterator7.e(err);
      } finally {
        _iterator7.f();
      }
      var itemTaxPrecise = mainTaxPrecise.plus(bundlePreciseTax);
      var itemTaxRounded = mainTaxRounded.plus(bundleRoundedTax);
      var itemOriginTaxPrecise = originalTaxPrecise.plus(bundlePreciseOriginTax);
      var itemOriginTaxRounded = originalTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).plus(bundleRoundedOriginTax);
      product.tax_fee = itemTaxRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
      product.original_tax_fee = itemOriginTaxRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
      preciseTax = preciseTax.plus(itemTaxPrecise.times(quantity));
      roundedTax = roundedTax.plus(itemTaxRounded.times(quantity));
      preciseOriginTax = preciseOriginTax.plus(itemOriginTaxPrecise.times(quantity));
      roundedOriginTax = roundedOriginTax.plus(itemOriginTaxRounded.times(quantity));
    }

    // --- 舍入差值处理 ---
  } catch (err) {
    _iterator6.e(err);
  } finally {
    _iterator6.f();
  }
  var expectedTax = preciseTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
  var expectedOriginTax = preciseOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
  var taxRemainder = expectedTax.minus(roundedTax).toNumber();
  var originTaxRemainder = expectedOriginTax.minus(roundedOriginTax).toNumber();
  if (lastTaxableItem) {
    if (taxRemainder !== 0) {
      lastTaxableItem.item.tax_fee_rounding_remainder = taxRemainder;
    }
    if (originTaxRemainder !== 0) {
      lastTaxableItem.item.original_tax_fee_rounding_remainder = originTaxRemainder;
    }
  }
  return {
    tax: expectedTax,
    originTax: expectedOriginTax
  };
}
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 productQuantity = products.reduce(function (sum, item) {
    return sum + getSafeNum(item.num);
  }, 0);
  var productOriginalAmount = products.reduce(function (sum, item) {
    return sum.plus(getUnitOriginalTotal(item).times(getSafeNum(item.num)));
  }, new Decimal(0));
  var productAmount = products.reduce(function (sum, item) {
    return sum.plus(getUnitPaymentTotal(item).times(getSafeNum(item.num)));
  }, new Decimal(0));
  var surchargeServiceItems = buildSurchargeServiceItems(products);
  var surcharge = getSurcharge({
    service: surchargeServiceItems,
    addons: [],
    bookingDetail: null,
    bookingId: undefined
  }, {
    isEdit: false,
    isInScheduleByDate: isInScheduleByDate,
    surcharge_list: surchargeList,
    scheduleById: scheduleById
  });
  var surchargeAmount = new Decimal(getSurchargeAmount({
    bookingDetail: null,
    bookingId: undefined
  }, surcharge, {
    isEdit: false
  }) || 0);
  for (var i = 0; i < products.length; i++) {
    var _surchargeServiceItem;
    products[i].surcharge_fee = ((_surchargeServiceItem = surchargeServiceItems[i]) === null || _surchargeServiceItem === void 0 ? void 0 : _surchargeServiceItem.surcharge_fee) || 0;
  }
  var hasTaxRate = taxRate !== undefined && taxRate !== null && taxRate > 0;
  var productTaxFee;
  if (hasTaxRate) {
    var taxResult = calculateProductsTax(products, taxRate, isPriceIncludeTax);
    productTaxFee = taxResult.tax;
  } else {
    productTaxFee = products.reduce(function (sum, item) {
      return sum.plus(toDecimal(item.tax_fee).times(getSafeNum(item.num)));
    }, new Decimal(0));
  }
  var shopDiscountAmount = Decimal.max(new Decimal(Number(shopDiscount) || 0), 0);
  var expectAmount = Decimal.max(0, productAmount.plus(surchargeAmount).minus(shopDiscountAmount));
  var totalAmount = isPriceIncludeTax === 1 ? expectAmount : expectAmount.plus(productTaxFee);
  var deposit = calculateProductsDeposit(products);
  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(Decimal.max(productOriginalAmount.minus(productAmount), 0).plus(shopDiscountAmount)),
    deposit_amount: deposit ? deposit.total : '0.00',
    deposit: deposit,
    expect_amount: toFixed2(expectAmount),
    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
  };
}