var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/booking/components/footer/amount.ts
var amount_exports = {};
__export(amount_exports, {
  getIsPriceIncludeTax: () => getIsPriceIncludeTax,
  getOptionDiscountAmount: () => getOptionDiscountAmount,
  getProductDiscountProductDiscountDifference: () => getProductDiscountProductDiscountDifference,
  getRelationDetailsTotal: () => getRelationDetailsTotal,
  getSumTotal: () => getSumTotal
});
module.exports = __toCommonJS(amount_exports);
var import_utils = require("../../utils");
var import_utils2 = require("@pisell/utils");
var import_decimal = __toESM(require("decimal.js"));
var import_utils3 = require("../../info/service2/utils");
var import_utils4 = require("../../info2/service/addService/utils");
var import_utils5 = require("./utils");
var import_dayjs = __toESM(require("dayjs"));
var getRelationDetailsTotal = (relation_details) => {
  let total = new import_decimal.default(0);
  for (let item of relation_details) {
    const number = new import_decimal.default(item.product_quantity || item.num || 0);
    const price = new import_decimal.default(item.selling_price || item.payment_price || item.price || 0);
    total = total.add(price.mul(number));
  }
  return total.toNumber();
};
var getProductDiscountProductDiscountDifference = (product) => {
  var _a, _b;
  const mainDiscountList = product.discount_list || [];
  const bundleDiscountList = (0, import_utils5.getBundleDiscountList)(((_b = (_a = product._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.bundle) || []);
  const discountList = [...mainDiscountList, ...bundleDiscountList];
  return discountList.reduce((pre, cur) => {
    var _a2;
    return pre + (((_a2 = cur == null ? void 0 : cur.metadata) == null ? void 0 : _a2.product_discount_difference) || 0);
  }, 0);
};
var getProductExpectAmount = (state, isEdit, isOriginTotal) => {
  var _a, _b, _c, _d;
  let price = new import_decimal.default(0);
  let duration = new import_decimal.default(0);
  const isDay = (0, import_utils3.isDayBooking)(state);
  let dayDuration = new import_decimal.default(0);
  let minuteDuration = new import_decimal.default(0);
  if (isEdit) {
    if ((state == null ? void 0 : state.service) || (state == null ? void 0 : state.addons)) {
      if (Array.isArray((_a = state == null ? void 0 : state.service) == null ? void 0 : _a.value)) {
        for (let item of state.service.value) {
          if (isDay || (0, import_utils3.isNormalProductByDurationSchedule)(item) || (0, import_utils4.isMultiDayProduct)(item)) {
            const quantity = new import_decimal.default(item._extend.quantity || 1);
            const itemTotal = new import_decimal.default(item._extend.total || 0);
            const itemOriginTotal = new import_decimal.default(item._extend.origin_total || 0);
            price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));
            price = price.sub(getProductDiscountProductDiscountDifference(item));
            const _duration = !(0, import_utils3.isNormalProductByDurationSchedule)(item) ? new import_decimal.default(item._extend.duration || 0) : new import_decimal.default(0);
            if (isDay || (0, import_utils4.isMultiDayProduct)(item)) {
              dayDuration = dayDuration.add(_duration);
            } else {
              minuteDuration = minuteDuration.add(_duration);
            }
          } else {
            const quantity = new import_decimal.default(item._extend.quantity || 1);
            const itemTotal = new import_decimal.default(item._extend.total || 0);
            const itemOriginTotal = new import_decimal.default(item._extend.origin_total || 0);
            price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));
            const relationTotal = new import_decimal.default(getRelationDetailsTotal(
              item._extend.relation_details || []
            ));
            price = price.add(relationTotal);
            price = price.sub(getProductDiscountProductDiscountDifference(item));
            const itemDuration = new import_decimal.default(import_utils.flexibleObj.getValue(item._extend.duration) || 0);
            duration = duration.add(itemDuration);
            if ((0, import_utils4.isMultiDayProduct)(item)) {
              dayDuration = dayDuration.add(itemDuration);
            } else {
              minuteDuration = minuteDuration.add(itemDuration);
            }
          }
        }
      }
      if (!isDay && Array.isArray((_b = state.addons) == null ? void 0 : _b.value)) {
        for (let item of state.addons.value) {
          const quantity = new import_decimal.default(item._extend.quantity || 1);
          const itemTotal = new import_decimal.default(item._extend.total || 0);
          const itemOriginTotal = new import_decimal.default(item._extend.origin_total || 0);
          price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));
        }
      }
    }
  } else {
    price = new import_decimal.default(((_c = state.bookingDetail) == null ? void 0 : _c.product_expect_amount) || 0);
    let services = ((_d = state == null ? void 0 : state.service) == null ? void 0 : _d.value) || [];
    duration = services.reduce((pre, cur) => {
      var _a2;
      let current = new import_decimal.default(0);
      if (isDay || (0, import_utils4.isMultiDayProduct)(cur)) {
        const _duration = !(0, import_utils3.isNormalProductByDurationSchedule)(cur) ? new import_decimal.default(cur._extend.duration || 0) : new import_decimal.default(0);
        current = _duration;
      } else {
        current = new import_decimal.default(import_utils.flexibleObj.getValue(((_a2 = cur._extend) == null ? void 0 : _a2.duration) || 0) || 0);
      }
      if (isDay || (0, import_utils4.isMultiDayProduct)(cur)) {
        dayDuration = dayDuration.add(current);
      } else {
        minuteDuration = minuteDuration.add(current);
      }
      return pre.add(current);
    }, new import_decimal.default(0));
  }
  return {
    productExpectAmount: price.toNumber(),
    duration: (0, import_utils.getDiscountTimeByDayMinutes)(dayDuration.toNumber(), minuteDuration.toNumber())
  };
};
var getProductItemTax = (item, state, options) => {
  const { bookingDetail } = state;
  const { tax_rate, is_price_include_tax } = options;
  const productDiscountPrice = new import_decimal.default(item.total || 0);
  const quantity = new import_decimal.default(item.quantity || 1);
  if (productDiscountPrice.lte(0)) {
    return new import_decimal.default(0);
  }
  const currentTaxRate = new import_decimal.default(
    (bookingDetail == null ? void 0 : bookingDetail.tax_rate) ?? (tax_rate ? tax_rate / 100 : 0)
  );
  const currentIsPriceIncludeTax = (bookingDetail == null ? void 0 : bookingDetail.is_price_include_tax) ?? is_price_include_tax ?? 0;
  let singleItemTax = new import_decimal.default(0);
  if (item.is_charge_tax === 0 || !item.is_charge_tax) {
    singleItemTax = new import_decimal.default(0);
  } else {
    if (currentIsPriceIncludeTax === 0) {
      singleItemTax = productDiscountPrice.times(currentTaxRate);
    } else {
      const divisor = new import_decimal.default(1).plus(currentTaxRate);
      if (divisor.lte(0)) {
        singleItemTax = new import_decimal.default(0);
      } else {
        singleItemTax = productDiscountPrice.dividedBy(divisor).times(currentTaxRate);
      }
    }
  }
  return singleItemTax.times(quantity);
};
var processItemsTax = (items, state, options) => {
  var _a, _b, _c;
  const { tax_rate, is_price_include_tax, computed } = options;
  const { shopDiscount, productExpectAmount } = computed;
  let preciseOriginTax = new import_decimal.default(0);
  let preciseTax = new import_decimal.default(0);
  let roundedOriginTax = new import_decimal.default(0);
  let roundedTax = new import_decimal.default(0);
  let lastTaxableItem = null;
  for (let item of items) {
    const quantity = new import_decimal.default(item._extend.quantity || 1);
    const unitPrice = new import_decimal.default(item._extend.total || 0);
    const mainProductPrice = new import_decimal.default(getMainProductTotal(item) || 0);
    let originalTaxPerItemPrecise = getProductItemTax(
      {
        ...item,
        total: mainProductPrice.add(((_a = item._extend) == null ? void 0 : _a.surcharge_fee) || 0).toNumber(),
        quantity: 1
      },
      state,
      { tax_rate, is_price_include_tax }
    );
    let itemDiscount = new import_decimal.default(0);
    if (productExpectAmount > 0) {
      itemDiscount = unitPrice.dividedBy(productExpectAmount).times(shopDiscount);
    }
    let mainItemDiscount = new import_decimal.default(0);
    if (unitPrice.greaterThan(0)) {
      mainItemDiscount = mainProductPrice.dividedBy(productExpectAmount).times(shopDiscount);
    }
    const mainItemDiscountedUnitPrice = mainProductPrice.minus(mainItemDiscount).add(((_b = item._extend) == null ? void 0 : _b.surcharge_fee) || 0);
    const maxDiscountedTaxPerItemPrecise = getProductItemTax(
      {
        ...item,
        total: mainItemDiscountedUnitPrice.toNumber(),
        price: item._extend.total,
        quantity: 1
      },
      state,
      { tax_rate, is_price_include_tax }
    );
    const maxDiscountedTaxPerItemRounded = maxDiscountedTaxPerItemPrecise.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP);
    item._extend.main_product_attached_bundle_tax_fee = maxDiscountedTaxPerItemRounded.toNumber();
    if (maxDiscountedTaxPerItemPrecise.gt(0)) {
      lastTaxableItem = { type: "main", item };
    }
    let addTimePreciseTax = new import_decimal.default(0);
    let addTimeRoundedTax = new import_decimal.default(0);
    if (Array.isArray(item._extend.relation_details)) {
      for (let atItem of item._extend.relation_details) {
        const _originTotal = new import_decimal.default(
          atItem.selling_price || atItem.price || 0
        );
        let _discountedTotal = _originTotal;
        if (productExpectAmount > 0) {
          _discountedTotal = _originTotal.minus(
            _originTotal.dividedBy(productExpectAmount).times(shopDiscount)
          );
        }
        const addTimeTaxPerItemPrecise = getProductItemTax(
          {
            ...atItem,
            total: _discountedTotal.add((atItem == null ? void 0 : atItem.surcharge_fee) || 0).toNumber(),
            quantity: atItem.product_quantity || atItem.num || 1
          },
          state,
          { tax_rate, is_price_include_tax }
        );
        const addTimeTaxPerItemRounded = addTimeTaxPerItemPrecise.toDecimalPlaces(2, import_decimal.default.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 };
        }
      }
    }
    let bundlePreciseOriginTax = new import_decimal.default(0);
    let bundlePreciseTax = new import_decimal.default(0);
    let bundleRoundedOriginTax = new import_decimal.default(0);
    let bundleRoundedTax = new import_decimal.default(0);
    if (Array.isArray((_c = item._extend.other) == null ? void 0 : _c.bundle)) {
      for (let bundleItem of item._extend.other.bundle) {
        if (getBundleItemIsOriginalPrice(bundleItem)) {
          const bundleQuantity = new import_decimal.default(bundleItem.quantity || 1);
          const bundleUnitPrice = new import_decimal.default(
            bundleItem.bundle_selling_price ?? bundleItem.price ?? 0
          );
          const bundleOriginalTaxPerItemPrecise = getProductItemTax(
            {
              ...bundleItem,
              total: bundleUnitPrice.add((bundleItem == null ? void 0 : bundleItem.surcharge_fee) || 0).toNumber(),
              quantity: 1
            },
            state,
            { tax_rate, is_price_include_tax }
          );
          let bundleItemDiscount = new import_decimal.default(0);
          if (productExpectAmount > 0) {
            bundleItemDiscount = bundleUnitPrice.dividedBy(productExpectAmount).times(shopDiscount);
          }
          const bundleDiscountedUnitPrice = bundleUnitPrice.minus(bundleItemDiscount).add((bundleItem == null ? void 0 : bundleItem.surcharge_fee) || 0);
          const bundleDiscountedTaxPerItemPrecise = getProductItemTax(
            {
              ...bundleItem,
              total: bundleDiscountedUnitPrice.toNumber(),
              quantity: 1
            },
            state,
            { tax_rate, is_price_include_tax }
          );
          const bundleOriginalTaxPerItemRounded = bundleOriginalTaxPerItemPrecise.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP);
          const bundleDiscountedTaxPerItemRounded = bundleDiscountedTaxPerItemPrecise.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP);
          bundleItem.original_tax_fee = bundleOriginalTaxPerItemRounded.toNumber();
          bundleItem.tax_fee = bundleDiscountedTaxPerItemRounded.toNumber();
          bundlePreciseOriginTax = bundlePreciseOriginTax.plus(bundleOriginalTaxPerItemPrecise.times(bundleQuantity));
          bundlePreciseTax = bundlePreciseTax.plus(bundleDiscountedTaxPerItemPrecise.times(bundleQuantity));
          bundleRoundedOriginTax = bundleRoundedOriginTax.plus(bundleOriginalTaxPerItemRounded.times(bundleQuantity));
          bundleRoundedTax = bundleRoundedTax.plus(bundleDiscountedTaxPerItemRounded.times(bundleQuantity));
          if (bundleDiscountedTaxPerItemPrecise.gt(0)) {
            lastTaxableItem = { type: "bundle", item: bundleItem };
          }
        }
      }
    }
    const originalTaxFeePrecise = originalTaxPerItemPrecise.plus(bundlePreciseOriginTax);
    const taxFeePrecise = maxDiscountedTaxPerItemPrecise.plus(bundlePreciseTax);
    const originalTaxFeeRounded = originalTaxPerItemPrecise.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).plus(bundleRoundedOriginTax);
    const taxFeeRounded = maxDiscountedTaxPerItemRounded.plus(bundleRoundedTax);
    item._extend.original_tax_fee = originalTaxFeeRounded.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
    item._extend.tax_fee = taxFeeRounded.toDecimalPlaces(2, import_decimal.default.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);
  }
  const expectedOriginTax = preciseOriginTax.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP);
  const expectedTax = preciseTax.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP);
  const originTaxRemainder = expectedOriginTax.minus(roundedOriginTax).toNumber();
  const 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 = (state) => {
  var _a, _b;
  const { service, addons } = state;
  if (Array.isArray(service == null ? void 0 : service.value)) {
    for (let item of service.value) {
      item._extend.tax_fee = 0;
      item._extend.original_tax_fee = 0;
      item._extend.tax_fee_rounding_remainder = void 0;
      item._extend.main_product_attached_bundle_tax_fee = 0;
      for (let bundleItem of ((_a = item._extend.other) == null ? void 0 : _a.bundle) || []) {
        bundleItem.tax_fee = 0;
        bundleItem.original_tax_fee = 0;
        bundleItem.tax_fee_rounding_remainder = void 0;
      }
      for (let relationDetail of item._extend.relation_details || []) {
        relationDetail.tax_fee = 0;
        relationDetail.tax_fee_rounding_remainder = void 0;
      }
    }
  }
  if (Array.isArray(addons == null ? void 0 : addons.value)) {
    for (let item of addons.value) {
      item._extend.tax_fee = 0;
      item._extend.original_tax_fee = 0;
      item._extend.tax_fee_rounding_remainder = void 0;
      item._extend.main_product_attached_bundle_tax_fee = 0;
      for (let bundleItem of ((_b = item._extend.other) == null ? void 0 : _b.bundle) || []) {
        bundleItem.tax_fee = 0;
        bundleItem.original_tax_fee = 0;
        bundleItem.tax_fee_rounding_remainder = void 0;
      }
    }
  }
};
var getTax = (state, options) => {
  var _a, _b, _c;
  const { isEdit, computed, tax_rate, is_price_include_tax } = options;
  if (!isEdit) {
    return { tax: Number((_a = state.bookingDetail) == null ? void 0 : _a.tax_fee) || 0 };
  }
  clearTaxFee(state);
  let totalOriginTax = new import_decimal.default(0);
  let totalTax = new import_decimal.default(0);
  if ((state == null ? void 0 : state.service) || (state == null ? void 0 : state.addons)) {
    if ((_b = state == null ? void 0 : state.service) == null ? void 0 : _b.value) {
      const serviceResult = processItemsTax(state.service.value, state, {
        tax_rate,
        is_price_include_tax,
        computed
      });
      totalOriginTax = totalOriginTax.plus(serviceResult.originTax);
      totalTax = totalTax.plus(serviceResult.tax);
    }
    if ((_c = state == null ? void 0 : state.addons) == null ? void 0 : _c.value) {
      const addonsResult = processItemsTax(state.addons.value, state, {
        tax_rate,
        is_price_include_tax,
        computed
      });
      totalOriginTax = totalOriginTax.plus(addonsResult.originTax);
      totalTax = totalTax.plus(addonsResult.tax);
    }
  }
  return {
    originTax: totalOriginTax.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber(),
    tax: totalTax.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber()
  };
};
var getTaxInfo = (state, options) => {
  const { bookingDetail } = state;
  const { tax_rate, tax_title, is_price_include_tax } = options;
  return {
    title: (bookingDetail == null ? void 0 : bookingDetail.tax_title) || tax_title,
    rate: (bookingDetail == null ? void 0 : bookingDetail.tax_rate) || tax_rate / 100,
    is_price_include_tax: getIsPriceIncludeTax(state) || is_price_include_tax
  };
};
var getPaySurchargeFee = (state) => {
  const { bookingDetail, bookingId } = state;
  if (!bookingDetail) return 0;
  const processingFee = new import_decimal.default(bookingDetail.pay_processing_fee || 0);
  const gatewayFee = new import_decimal.default(bookingDetail.gateway_fee || 0);
  return processingFee.add(gatewayFee).toNumber();
};
var isProductMatchSurchargeCondition = (item, options) => {
  var _a, _b;
  if (!options.ScheduleModule) {
    console.warn("ScheduleModule not found!");
    return false;
  }
  const isInScheduleByDate = (_a = options.ScheduleModule) == null ? void 0 : _a.isInScheduleByDate;
  const { surchargeConfig, scheduleById = {} } = options;
  const { startDate, product_id, isCustomItem } = item;
  const {
    open_product = 0,
    // 1 | 0
    is_all = 0,
    // 0 | 1（所有商品）
    available_product_ids = [],
    // 指定商品
    open_schedule = 0,
    // 1 | 0
    schedule_type,
    // custom | all(所有日程)
    available_schedule_ids = []
  } = surchargeConfig;
  let isProductMatch = false;
  if (open_product === 0) {
    isProductMatch = true;
  } else {
    if (is_all === 1) {
      isProductMatch = true;
    } else {
      if (isCustomItem) {
        isProductMatch = false;
      } else {
        isProductMatch = available_product_ids.includes(product_id);
      }
    }
  }
  let isScheduleMatch = false;
  if (open_schedule === 0) {
    isScheduleMatch = true;
  } else {
    if (schedule_type === "all") {
      isScheduleMatch = true;
    } else {
      for (let j = 0; j < available_schedule_ids.length; j++) {
        const scheduleId = available_schedule_ids[j];
        const schedule = scheduleById[scheduleId];
        if (schedule) {
          const isInSchedule = isInScheduleByDate({
            date: ((_b = startDate || (0, import_dayjs.default)()) == null ? void 0 : _b.format("YYYY-MM-DD HH:mm:ss")) || "",
            schedule
          });
          if (isInSchedule) {
            isScheduleMatch = true;
            break;
          }
        }
      }
    }
  }
  return isProductMatch && isScheduleMatch;
};
var getBundleItemIsOriginalPrice = (item) => {
  return (item == null ? void 0 : item.price_type) === "markup" && (item == null ? void 0 : item.price_type_ext) === "product_price";
};
var getBundleItemIsMarkupPrice = (item) => {
  return (item == null ? void 0 : item.price_type) === "markup" && ((item == null ? void 0 : item.price_type_ext) === "" || !(item == null ? void 0 : item.price_type_ext));
};
var getBundleItemIsDiscountPrice = (item) => {
  return (item == null ? void 0 : item.price_type) === "markdown" && ((item == null ? void 0 : item.price_type_ext) === "" || !(item == null ? void 0 : item.price_type_ext));
};
var getBundleItemIsMarkupOrDiscountPrice = (item) => {
  return getBundleItemIsMarkupPrice(item) || getBundleItemIsDiscountPrice(item);
};
var getDiscountAmount = (discounts) => {
  return (discounts || []).reduce((total, discount) => {
    return total.add(new import_decimal.default(discount.amount || 0));
  }, new import_decimal.default(0)).toNumber();
};
var getOptionDiscountAmount = (discounts) => {
  return (discounts || []).reduce((total, discount) => {
    var _a;
    return total.add(new import_decimal.default(((_a = discount == null ? void 0 : discount.metadata) == null ? void 0 : _a.optionDiscountAmount) || 0));
  }, new import_decimal.default(0)).toNumber();
};
var getMainProductTotal = (item) => {
  var _a, _b, _c, _d, _e, _f;
  let total = new import_decimal.default(((_a = item._extend) == null ? void 0 : _a.main_product_selling_price) ?? ((_b = item == null ? void 0 : item.metadata) == null ? void 0 : _b.main_product_selling_price) ?? item._extend.price ?? 0);
  if (((_c = item._extend.other) == null ? void 0 : _c.option) && Array.isArray((_d = item._extend.other) == null ? void 0 : _d.option)) {
    total = total.add((_e = item._extend.other) == null ? void 0 : _e.option.reduce((t, option) => {
      return t.add(new import_decimal.default(option.price || 0).mul(option.num || 1));
    }, new import_decimal.default(0)));
    if (item.booking_id) {
      total = total.sub(getOptionDiscountAmount((item == null ? void 0 : item.discount_list) || []));
    }
  }
  for (let bundleItem of ((_f = item._extend.other) == null ? void 0 : _f.bundle) || []) {
    if (getBundleItemIsMarkupOrDiscountPrice(bundleItem)) {
      const discountAmount = getDiscountAmount(bundleItem.discount_list);
      const bundleItemPrice = new import_decimal.default(bundleItem.bundle_selling_price ?? bundleItem.price ?? 0);
      const bundleItemTotal = bundleItemPrice;
      total = total.add(bundleItemTotal);
    }
  }
  return total.toNumber();
};
var clearSurchargeFee = (state) => {
  var _a, _b;
  const { service, addons } = state;
  if (Array.isArray(service == null ? void 0 : service.value)) {
    for (let item of service.value) {
      item._extend.surcharge_fee = 0;
      item._extend.surcharge_rounding_remainder = void 0;
      item._extend.relation_surcharge_ids = [];
      for (let bundleItem of ((_a = item._extend.other) == null ? void 0 : _a.bundle) || []) {
        bundleItem.surcharge_fee = 0;
        bundleItem.surcharge_rounding_remainder = void 0;
        bundleItem.relation_surcharge_ids = [];
      }
      for (let relationDetail of item._extend.relation_details || []) {
        relationDetail.surcharge_fee = 0;
        relationDetail.surcharge_rounding_remainder = void 0;
        relationDetail.relation_surcharge_ids = [];
      }
    }
  }
  if (Array.isArray(addons == null ? void 0 : addons.value)) {
    for (let item of addons.value) {
      item._extend.surcharge_fee = 0;
      item._extend.surcharge_rounding_remainder = void 0;
      item._extend.relation_surcharge_ids = [];
      for (let bundleItem of ((_b = item._extend.other) == null ? void 0 : _b.bundle) || []) {
        bundleItem.surcharge_fee = 0;
        bundleItem.surcharge_rounding_remainder = void 0;
        bundleItem.relation_surcharge_ids = [];
      }
    }
  }
};
var getSurcharge = (state, options) => {
  var _a, _b, _c, _d, _e;
  const { isEdit, ScheduleModule, surcharge_list, scheduleById } = options;
  const { bookingDetail, bookingId } = state;
  if (!isEdit && bookingDetail) {
    if (Array.isArray(bookingDetail == null ? void 0 : bookingDetail.surcharge)) {
      return (((_a = state.bookingDetail) == null ? void 0 : _a.surcharge) || []).filter((d) => Number(d.amount) > 0).map(
        (d, index) => {
          return {
            key: `custom_surcharge_${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);
  const { service, addons } = state;
  if (!Array.isArray(surcharge_list) || !(surcharge_list == null ? void 0 : surcharge_list.length)) return [];
  const surchargeWithAmount = [];
  for (let i = 0; i < surcharge_list.length; i++) {
    const surchargeConfig = surcharge_list[i];
    const {
      percentage = "0",
      fixed = "0",
      id,
      type,
      description,
      open_product
    } = surchargeConfig;
    const matchedItems = [];
    if (Array.isArray(service == null ? void 0 : service.value)) {
      for (let item of service.value) {
        if (isProductMatchSurchargeCondition(
          {
            isCustomItem: item.isCustomItem,
            startDate: item._extend.startDate,
            product_id: item.product_id
          },
          {
            surchargeConfig,
            scheduleById: scheduleById || {},
            ScheduleModule
          }
        )) {
          const total = getMainProductTotal(item);
          const mainQuantity = item._extend.quantity || 1;
          matchedItems.push({
            total,
            // addTimeTotal: getRelationDetailsTotal(
            //   item._extend.relation_details || []
            // ),
            isMain: true,
            quantity: mainQuantity,
            item,
            mainQuantity
            // 主商品的mainQuantity等于自己的quantity
          });
        }
        for (let bundleItem of ((_b = item._extend.other) == null ? void 0 : _b.bundle) || []) {
          if (getBundleItemIsOriginalPrice(bundleItem) && isProductMatchSurchargeCondition(
            {
              isCustomItem: false,
              startDate: item._extend.startDate,
              product_id: bundleItem._bundle_product_id
            },
            {
              surchargeConfig,
              scheduleById: scheduleById || {},
              ScheduleModule
            }
          )) {
            const mainQuantity = item._extend.quantity || 1;
            matchedItems.push({
              isMain: false,
              total: Number(
                bundleItem.bundle_selling_price ?? bundleItem.price ?? 0
              ),
              quantity: bundleItem.num || bundleItem.quantity || 1,
              item: bundleItem,
              mainQuantity
              // 子商品的mainQuantity是所属主商品的quantity
            });
          }
        }
        for (let relationDetail of item._extend.relation_details || []) {
          if (isProductMatchSurchargeCondition(
            {
              isCustomItem: false,
              startDate: item._extend.startDate,
              product_id: relationDetail.product_id
            },
            {
              surchargeConfig,
              scheduleById: scheduleById || {},
              ScheduleModule
            }
          )) {
            matchedItems.push({
              isMain: false,
              total: Number(
                (relationDetail == null ? void 0 : relationDetail.price) || ((_c = relationDetail == null ? void 0 : relationDetail.metadata) == null ? void 0 : _c.main_product_attached_bundle_selling_price)
              ),
              quantity: relationDetail.num || relationDetail.quantity || 1,
              item: relationDetail,
              mainQuantity: 1
              // 加时商品不受主商品数量影响
            });
          }
        }
      }
    }
    if (Array.isArray(addons == null ? void 0 : addons.value)) {
      for (let item of addons.value) {
        if (isProductMatchSurchargeCondition(item, {
          surchargeConfig,
          scheduleById: scheduleById || {},
          ScheduleModule
        })) {
          matchedItems.push({
            isMain: true,
            total: Number(item._extend.total),
            quantity: item._extend.quantity || 1,
            item,
            mainQuantity: 1
            // addons独立商品，mainQuantity为1
          });
        }
      }
    }
    let finalAmount = 0;
    const productCount = matchedItems.reduce((total, item) => {
      if (item.isMain) {
        return total + (item.quantity || 1);
      } else {
        return total + (item.quantity || 1) * (item.mainQuantity || 1);
      }
    }, 0);
    let fixedTotal = new import_decimal.default(0);
    let productTotalSurcharge = new import_decimal.default(0);
    if (matchedItems.length > 0) {
      let configTotal = new import_decimal.default(0);
      if (fixed && new import_decimal.default(fixed).gt(0)) {
        configTotal = configTotal.plus(fixed);
      }
      if (percentage && new import_decimal.default(percentage).gt(0) || fixed) {
        const percentageRate = new import_decimal.default(percentage);
        for (let [index, item] of matchedItems.entries()) {
          const isLast = index === matchedItems.length - 1;
          const itemPrice = new import_decimal.default(Math.max(0, item.total || 0));
          const itemQuantity = new import_decimal.default(item.isMain ? item.quantity || 1 : item.quantity * item.mainQuantity || 1);
          const addTimeTotal = new import_decimal.default(item.addTimeTotal || 0);
          const itemTotalSurcharge = itemPrice.times(itemQuantity).plus(addTimeTotal).times(percentageRate);
          configTotal = configTotal.plus(itemTotalSurcharge);
          const itemSurcharge = itemPrice.times(percentageRate);
          const fixedSurcharge = new import_decimal.default(1).div(productCount).times(fixed).times(100).floor().div(100).toFixed(2);
          const quantity = item.isMain ? item.quantity : item.quantity * item.mainQuantity;
          fixedTotal = fixedTotal.plus(new import_decimal.default(fixedSurcharge).times(quantity).toNumber());
          if (isLast && fixedTotal.gt(0)) {
            const remaining = new import_decimal.default(fixed).minus(fixedTotal).toNumber();
            if (remaining > 0) {
              productTotalSurcharge = productTotalSurcharge.plus(remaining);
              if (item.isMain) {
                item.item._extend.surcharge_rounding_remainder = remaining;
              } else {
                item.item.surcharge_rounding_remainder = remaining;
              }
            }
          }
          if (open_product !== 0) {
            if (item.isMain) {
              const originSurchargeFee = new import_decimal.default(item.item._extend.surcharge_fee || 0);
              const surchargeFee = originSurchargeFee.plus(itemSurcharge).plus(fixedSurcharge).toDecimalPlaces(2, import_decimal.default.ROUND_DOWN).toNumber();
              productTotalSurcharge = productTotalSurcharge.plus(new import_decimal.default(surchargeFee).times(itemQuantity).toNumber());
              item.item._extend.surcharge_fee = surchargeFee;
              item.item._extend.relation_surcharge_ids = [...((_d = item.item._extend) == null ? void 0 : _d.relation_surcharge_ids) || [], id];
            } else {
              const originSurchargeFee = new import_decimal.default(item.item.surcharge_fee || 0);
              const surchargeFee = originSurchargeFee.plus(itemSurcharge).plus(fixedSurcharge).toDecimalPlaces(2, import_decimal.default.ROUND_DOWN).toNumber();
              productTotalSurcharge = productTotalSurcharge.plus(new import_decimal.default(surchargeFee).times(itemQuantity).toNumber());
              item.item.surcharge_fee = surchargeFee;
              item.item.relation_surcharge_ids = [...((_e = item.item) == null ? void 0 : _e.relation_surcharge_ids) || [], id];
            }
          }
          if (isLast && configTotal.minus(productTotalSurcharge).gt(0)) {
            const configTotalRounded = configTotal.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP);
            if (item.isMain) {
              let newRoundingRemainder = new import_decimal.default(item.item._extend.surcharge_rounding_remainder || 0);
              newRoundingRemainder = newRoundingRemainder.plus(configTotalRounded.minus(productTotalSurcharge));
              item.item._extend.surcharge_rounding_remainder = newRoundingRemainder.toNumber();
            } else {
              let newRoundingRemainder = new import_decimal.default(item.item.surcharge_rounding_remainder || 0);
              newRoundingRemainder = newRoundingRemainder.plus(configTotalRounded.minus(productTotalSurcharge));
              item.item.surcharge_rounding_remainder = newRoundingRemainder.toNumber();
            }
          }
        }
      }
      finalAmount = configTotal.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
    }
    const name = surchargeConfig.name || {};
    if (Number(finalAmount) <= 0) {
      continue;
    }
    surchargeWithAmount.push({
      key: `custom_surcharge_${i}`,
      label: name[state.locale || "en"] || name["en"] || name["original"],
      name,
      value: finalAmount,
      surcharge_id: id,
      description,
      // 后端说固定传 default
      type: "default",
      fixed,
      amount: finalAmount,
      percentage,
      metadata: {
        open_product
      }
    });
  }
  return surchargeWithAmount;
};
var getSurchargeAmount = (state, surcharge, options) => {
  const { bookingDetail, bookingId } = state;
  const { isEdit } = options;
  if (!isEdit) {
    if (bookingDetail) {
      return Number(bookingDetail.surcharge_fee);
    }
  }
  if (!Array.isArray(surcharge)) return 0;
  return surcharge.reduce((total, item) => {
    return total + (item.value || 0);
  }, 0);
};
var getPaidAmount = (state) => {
  var _a, _b, _c, _d, _e;
  const { bookingDetail, bookingId } = state;
  if ((_b = (_a = state.paymentPaid) == null ? void 0 : _a.value) == null ? void 0 : _b.paidAmount) {
    return (_d = (_c = state.paymentPaid) == null ? void 0 : _c.value) == null ? void 0 : _d.paidAmount;
  }
  if (!bookingDetail) return 0;
  return Number((_e = state.bookingDetail) == null ? void 0 : _e.paid_amount) || 0;
};
var getOrderPaidAmount = (state) => {
  var _a, _b, _c, _d, _e;
  const { bookingDetail, bookingId } = state;
  console.log("getOrderPaidAmount", state.paymentPaid);
  if ((_b = (_a = state.paymentPaid) == null ? void 0 : _a.value) == null ? void 0 : _b.paidAmountWithoutSurcharge) {
    return (_d = (_c = state.paymentPaid) == null ? void 0 : _c.value) == null ? void 0 : _d.paidAmountWithoutSurcharge;
  }
  if (!bookingDetail) return 0;
  return Number((_e = state.bookingDetail) == null ? void 0 : _e.order_paid_amount) || 0;
};
var getIsPriceIncludeTax = (state) => {
  var _a;
  return ((_a = state.bookingDetail) == null ? void 0 : _a.is_price_include_tax) ?? 0;
};
var getExpectAmount = ({
  price,
  tax,
  surchargeAmount,
  shopDiscount,
  state,
  options
}) => {
  let _tax = tax;
  if (getIsPriceIncludeTax(state) || (options == null ? void 0 : options.is_price_include_tax)) {
    _tax = 0;
  }
  return price + _tax + surchargeAmount - shopDiscount;
};
var getTotalRefundAmount = (state) => {
  var _a;
  return Number((_a = state.bookingDetail) == null ? void 0 : _a.total_refund_amount) || 0;
};
var getShopDiscount = (state) => {
  var _a;
  return Number(state.shop_discount) || Number((_a = state.bookingDetail) == null ? void 0 : _a.shop_discount) || 0;
};
var getRoundingAmount = (state) => {
  var _a;
  return Number((_a = state == null ? void 0 : state.bookingDetail) == null ? void 0 : _a.rounding_amount) || 0;
};
var getSumTotalAmount = ({
  expectAmount,
  roundingAmount
}) => {
  return expectAmount + roundingAmount;
};
var getSumTotal = (state, options) => {
  const { productExpectAmount, duration } = getProductExpectAmount(
    state,
    options.isEdit
  );
  const shopDiscount = getShopDiscount(state);
  const roundingAmount = getRoundingAmount(state);
  const paySurchargeFee = getPaySurchargeFee(state);
  const surcharge = getSurcharge(state, options);
  const surchargeAmount = getSurchargeAmount(state, surcharge, options);
  const computed = {
    productExpectAmount,
    shopDiscount
  };
  const { tax, originTax } = getTax(state, {
    computed,
    ...options
  });
  const taxInfo = getTaxInfo(state, options);
  const paidAmount = getPaidAmount(state);
  const orderPaidAmount = getOrderPaidAmount(state);
  const totalRefundAmount = getTotalRefundAmount(state);
  const expectAmount = getExpectAmount({
    price: productExpectAmount,
    tax,
    surchargeAmount,
    shopDiscount,
    state,
    options
  });
  const originExpectAmount = getExpectAmount({
    price: productExpectAmount,
    tax: originTax,
    surchargeAmount,
    shopDiscount: 0,
    state,
    options
  });
  const { productExpectAmount: productExpectAmountWithoutDiscount } = getProductExpectAmount(
    state,
    options.isEdit,
    true
  );
  const originExpectAmountWithoutDiscount = getExpectAmount({
    price: productExpectAmountWithoutDiscount,
    tax: originTax,
    surchargeAmount,
    shopDiscount: 0,
    state,
    options
  });
  const sumTotalAmount = getSumTotalAmount({ expectAmount, roundingAmount });
  const sumTotalAmountDecimal = new import_decimal.default((0, import_utils2.formatAmount)(sumTotalAmount, 2, "") || 0);
  const orderPaidAmountDecimal = new import_decimal.default(orderPaidAmount || 0);
  const notPaidAmount = sumTotalAmountDecimal.sub(orderPaidAmountDecimal).toNumber();
  const actualPaidAmount = paidAmount;
  const dueAmount = notPaidAmount < 0 ? Number((0, import_utils2.formatAmount)(new import_decimal.default(notPaidAmount).add(new import_decimal.default(totalRefundAmount)).toNumber(), 2, "")) : 0;
  return {
    productAmount: productExpectAmount,
    duration,
    tax,
    taxInfo,
    shopDiscount,
    // 附加费详情
    surcharge,
    // 附加费
    otherAmount: surchargeAmount,
    sumTotalAmount,
    paidAmount,
    notPaidAmount,
    paySurchargeFee,
    expectAmount,
    actualPaidAmount,
    orderPaidAmount,
    totalRefundAmount,
    dueAmount,
    roundingAmount,
    originExpectAmount,
    // 订单原价 不包含整单折扣 不包含商品券折扣卡抵扣
    originExpectAmountWithoutDiscount
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getIsPriceIncludeTax,
  getOptionDiscountAmount,
  getProductDiscountProductDiscountDifference,
  getRelationDetailsTotal,
  getSumTotal
});
