function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 { getDiscountTime, flexibleObj } from "../../utils";
import { formatAmount } from '@pisell/utils';
import Decimal from 'decimal.js';
import { isDayBooking, isDayBookingProduct, isNormalProductByDurationSchedule } from "../../info/service2/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();
};
/**
 * 总金额
 * @param state
 * @returns
 */
var getProductExpectAmount = function getProductExpectAmount(state, isEdit) {
  var price = new Decimal(0);
  var duration = new Decimal(0);
  // 是否是跨日预约
  var isDay = isDayBooking(state);
  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)) {
              var quantity = new Decimal(item._extend.quantity || 1);
              var itemTotal = new Decimal(item._extend.total || 0);
              price = price.add(itemTotal.mul(quantity));

              // 普通商品不能加到时长上
              var _duration = isDayBookingProduct(item, state) ? new Decimal(item._extend.duration || 0) : new Decimal(0);
              duration = duration.add(_duration);
            } else {
              var _quantity = new Decimal(item._extend.quantity || 1);
              var _itemTotal = new Decimal(item._extend.total || 0);
              price = price.add(_itemTotal.mul(_quantity));

              // 附加商品
              var relationTotal = new Decimal(getRelationDetailsTotal(item._extend.relation_details || []));
              price = price.add(relationTotal);
              var itemDuration = new Decimal(flexibleObj.getValue(item._extend.duration) || 0);
              duration = duration.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);
            price = price.add(_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) {
        // 普通商品不能加到时长上
        var _duration2 = isDayBookingProduct(cur, state) ? 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);
      }
      return pre.add(current);
    }, new Decimal(0));
  }
  return {
    productExpectAmount: price.toNumber(),
    duration: getDiscountTime(duration.toNumber(), isDay)
  };
};
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);
};

/**
 * 处理商品税费计算（折扣前后）
 * @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 originTax = new Decimal(0);
  var tax = new Decimal(0);
  var _iterator4 = _createForOfIteratorHelper(items),
    _step4;
  try {
    for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
      var item = _step4.value;
      var quantity = new Decimal(item._extend.quantity || 1);
      var unitPrice = new Decimal(item._extend.total || 0);

      // 计算原始税费（折扣前）- 单个商品
      var originalTaxPerItem = getProductItemTax(_objectSpread(_objectSpread({}, item), {}, {
        total: unitPrice.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 itemDiscountedUnitPrice = unitPrice.minus(itemDiscount);

      // 计算折后税费（折扣后）- 单个商品
      var discountedTaxPerItem = getProductItemTax(_objectSpread(_objectSpread({}, item), {}, {
        total: itemDiscountedUnitPrice.toNumber(),
        price: item._extend.total,
        quantity: 1
      }), state, {
        tax_rate: tax_rate,
        is_price_include_tax: is_price_include_tax
      });

      // 保存到商品扩展信息中
      item._extend.original_tax_fee = originalTaxPerItem.toNumber();
      item._extend.tax_fee = discountedTaxPerItem.toNumber();

      // 注意：加时商品独立计算，不考虑主商品数量
      var addTimeTotalTax = new Decimal(0);
      if (Array.isArray(item._extend.relation_details)) {
        var _iterator5 = _createForOfIteratorHelper(item._extend.relation_details),
          _step5;
        try {
          for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
            var atItem = _step5.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 addTimeTaxPerItem = getProductItemTax(_objectSpread(_objectSpread({}, atItem), {}, {
              total: _discountedTotal,
              // 可能包含原有数据，或前端临时数据
              quantity: atItem.product_quantity || atItem.num || 1
            }), state, {
              tax_rate: tax_rate,
              is_price_include_tax: is_price_include_tax
            });
            addTimeTotalTax = addTimeTotalTax.plus(addTimeTaxPerItem);
          }
        } catch (err) {
          _iterator5.e(err);
        } finally {
          _iterator5.f();
        }
      }

      // 累加到总税费（乘以数量）
      originTax = originTax.plus(originalTaxPerItem.times(quantity)).plus(addTimeTotalTax);
      tax = tax.plus(discountedTaxPerItem.times(quantity)).plus(addTimeTotalTax);
    }
  } catch (err) {
    _iterator4.e(err);
  } finally {
    _iterator4.f();
  }
  return {
    originTax: originTax,
    tax: tax
  };
};

/**
 * 税费
 * @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)
    };
  }
  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 _item$_extend = item._extend,
    startDate = _item$_extend.startDate,
    other = _item$_extend.other,
    isCustomItem = _item$_extend.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 {
        // 普通商品：检查是否在指定商品列表中
        var product_id = other === null || other === void 0 ? void 0 : other.product_id;
        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;
};

/**
 * 订单附加费各项信息
 * @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) || []).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 [];
  }

  // 新增状态
  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;

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

    // 检查service中符合条件的商品
    if (Array.isArray(service === null || service === void 0 ? void 0 : service.value)) {
      var _iterator6 = _createForOfIteratorHelper(service.value),
        _step6;
      try {
        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
          var item = _step6.value;
          if (isProductMatchSurchargeCondition(item, {
            surchargeConfig: surchargeConfig,
            scheduleById: scheduleById || {},
            ScheduleModule: ScheduleModule
          })) {
            matchedItems.push({
              total: Number(item._extend.total),
              addTimeTotal: getRelationDetailsTotal(item._extend.relation_details || []),
              quantity: item._extend.quantity || 1
            });
          }
        }
      } catch (err) {
        _iterator6.e(err);
      } finally {
        _iterator6.f();
      }
    }

    // 检查addons中符合条件的商品
    if (Array.isArray(addons === null || addons === void 0 ? void 0 : addons.value)) {
      var _iterator7 = _createForOfIteratorHelper(addons.value),
        _step7;
      try {
        for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
          var _item2 = _step7.value;
          if (isProductMatchSurchargeCondition(_item2, {
            surchargeConfig: surchargeConfig,
            scheduleById: scheduleById || {},
            ScheduleModule: ScheduleModule
          })) {
            matchedItems.push({
              total: Number(_item2._extend.total),
              quantity: _item2._extend.quantity || 1
            });
          }
        }
      } catch (err) {
        _iterator7.e(err);
      } finally {
        _iterator7.f();
      }
    }
    var finalAmount = 0;
    if (matchedItems.length > 0) {
      // 基于每个商品计算附加费：max(0, 商品价格) * rate + fixed
      var configTotal = new Decimal(0);

      // 计算百分比附加费 - 对每个商品单独计算
      if (percentage && new Decimal(percentage).gt(0)) {
        var percentageRate = new Decimal(percentage);
        var _iterator8 = _createForOfIteratorHelper(matchedItems),
          _step8;
        try {
          for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
            var _item3 = _step8.value;
            // 对每个商品：max(0, 价格) * 数量 * 费率
            var itemPrice = new Decimal(Math.max(0, _item3.total || 0));
            var itemQuantity = new Decimal(_item3.quantity || 1);
            var addTimeTotal = new Decimal(_item3.addTimeTotal || 0);
            var itemSurcharge = itemPrice.times(itemQuantity).plus(addTimeTotal).times(percentageRate);
            configTotal = configTotal.plus(itemSurcharge);
          }
        } catch (err) {
          _iterator8.e(err);
        } finally {
          _iterator8.f();
        }
      }

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

      // 如果该配置有金额，则添加到结果中
      finalAmount = configTotal.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
    }
    var name = surchargeConfig.name || {};
    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
    });
  }
  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(_ref2) {
  var price = _ref2.price,
    tax = _ref2.tax,
    surchargeAmount = _ref2.surchargeAmount,
    shopDiscount = _ref2.shopDiscount,
    state = _ref2.state,
    options = _ref2.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(_ref3) {
  var expectAmount = _ref3.expectAmount,
    roundingAmount = _ref3.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 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
  };
};