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,
  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 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 getProductExpectAmount = (state, isEdit) => {
  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);
  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)) {
            const quantity = new import_decimal.default(item._extend.quantity || 1);
            const itemTotal = new import_decimal.default(item._extend.total || 0);
            price = price.add(itemTotal.mul(quantity));
            const _duration = (0, import_utils3.isDayBookingProduct)(item, state) ? new import_decimal.default(item._extend.duration || 0) : new import_decimal.default(0);
            duration = duration.add(_duration);
          } else {
            const quantity = new import_decimal.default(item._extend.quantity || 1);
            const itemTotal = new import_decimal.default(item._extend.total || 0);
            price = price.add(itemTotal.mul(quantity));
            const relationTotal = new import_decimal.default(getRelationDetailsTotal(
              item._extend.relation_details || []
            ));
            price = price.add(relationTotal);
            const itemDuration = new import_decimal.default(import_utils.flexibleObj.getValue(item._extend.duration) || 0);
            duration = duration.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);
          price = price.add(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) {
        const _duration = (0, import_utils3.isDayBookingProduct)(cur, state) ? 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);
      }
      return pre.add(current);
    }, new import_decimal.default(0));
  }
  return {
    productExpectAmount: price.toNumber(),
    duration: (0, import_utils.getDiscountTime)(duration.toNumber(), isDay)
  };
};
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) => {
  const { tax_rate, is_price_include_tax, computed } = options;
  const { shopDiscount, productExpectAmount } = computed;
  let originTax = new import_decimal.default(0);
  let tax = new import_decimal.default(0);
  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 originalTaxPerItem = getProductItemTax(
      {
        ...item,
        total: unitPrice.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);
    }
    const itemDiscountedUnitPrice = unitPrice.minus(itemDiscount);
    const discountedTaxPerItem = getProductItemTax(
      {
        ...item,
        total: itemDiscountedUnitPrice.toNumber(),
        price: item._extend.total,
        quantity: 1
      },
      state,
      { tax_rate, is_price_include_tax }
    );
    item._extend.original_tax_fee = originalTaxPerItem.toNumber();
    item._extend.tax_fee = discountedTaxPerItem.toNumber();
    let addTimeTotalTax = 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 addTimeTaxPerItem = getProductItemTax(
          {
            ...atItem,
            total: _discountedTotal,
            // 可能包含原有数据，或前端临时数据
            quantity: atItem.product_quantity || atItem.num || 1
          },
          state,
          { tax_rate, is_price_include_tax }
        );
        addTimeTotalTax = addTimeTotalTax.plus(addTimeTaxPerItem);
      }
    }
    originTax = originTax.plus(originalTaxPerItem.times(quantity)).plus(addTimeTotalTax);
    tax = tax.plus(discountedTaxPerItem.times(quantity)).plus(addTimeTotalTax);
  }
  return { originTax, tax };
};
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) };
  }
  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 || !bookingId) 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;
  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, other, isCustomItem } = item._extend;
  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 {
        const product_id = other == null ? void 0 : other.product_id;
        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: (startDate == null ? void 0 : startDate.format("YYYY-MM-DD HH:mm:ss")) || "",
            schedule
          });
          if (isInSchedule) {
            isScheduleMatch = true;
            break;
          }
        }
      }
    }
  }
  return isProductMatch && isScheduleMatch;
};
var getSurcharge = (state, options) => {
  var _a;
  const { isEdit, ScheduleModule, surcharge_list, scheduleById } = options;
  const { bookingDetail, bookingId } = state;
  if (!isEdit && bookingId) {
    if (Array.isArray(bookingDetail == null ? void 0 : bookingDetail.surcharge)) {
      return (((_a = state.bookingDetail) == null ? void 0 : _a.surcharge) || []).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 [];
  }
  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
    } = surchargeConfig;
    const matchedItems = [];
    if (Array.isArray(service == null ? void 0 : service.value)) {
      for (let item of service.value) {
        if (isProductMatchSurchargeCondition(item, {
          surchargeConfig,
          scheduleById: scheduleById || {},
          ScheduleModule
        })) {
          matchedItems.push({
            total: Number(item._extend.total),
            addTimeTotal: getRelationDetailsTotal(
              item._extend.relation_details || []
            ),
            quantity: item._extend.quantity || 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({
            total: Number(item._extend.total),
            quantity: item._extend.quantity || 1
          });
        }
      }
    }
    let finalAmount = 0;
    if (matchedItems.length > 0) {
      let configTotal = new import_decimal.default(0);
      if (percentage && new import_decimal.default(percentage).gt(0)) {
        const percentageRate = new import_decimal.default(percentage);
        for (let item of matchedItems) {
          const itemPrice = new import_decimal.default(Math.max(0, item.total || 0));
          const itemQuantity = new import_decimal.default(item.quantity || 1);
          const addTimeTotal = new import_decimal.default(item.addTimeTotal || 0);
          const itemSurcharge = itemPrice.times(itemQuantity).plus(addTimeTotal).times(percentageRate);
          configTotal = configTotal.plus(itemSurcharge);
        }
      }
      if (fixed && new import_decimal.default(fixed).gt(0)) {
        configTotal = configTotal.plus(fixed);
      }
      finalAmount = configTotal.toDecimalPlaces(2, import_decimal.default.ROUND_HALF_UP).toNumber();
    }
    const name = surchargeConfig.name || {};
    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
    });
  }
  return surchargeWithAmount;
};
var getSurchargeAmount = (state, surcharge, options) => {
  const { bookingDetail, bookingId } = state;
  const { isEdit } = options;
  if (!isEdit) {
    if (bookingDetail && bookingId) {
      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 || !bookingId) 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;
  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 || !bookingId) 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 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
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getIsPriceIncludeTax,
  getRelationDetailsTotal,
  getSumTotal
});
