import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { isMultiDayProduct } from "../../info2/service/addService/utils.js";
import { getBundleDiscountList } from "./utils.js";
import { isDayBooking, isNormalProductByDurationSchedule } from "../../info/service2/utils.js";
import { flexibleObj, getDiscountTimeByDayMinutes } from "../../utils.js";
import { formatAmount } from "@pisell/utils";
import Decimal from "decimal.js";
//#region src/components/booking/components/footer/amount.ts
const getRelationDetailsTotal = (relation_details) => {
	let total = new Decimal(0);
	for (let item of relation_details) {
		const number = new Decimal(item.product_quantity || item.num || 0);
		const price = new Decimal(item.selling_price || item.payment_price || item.price || 0);
		total = total.add(price.mul(number));
	}
	return total.toNumber();
};
const getProductDiscountProductDiscountDifference = (product) => {
	var _product$_extend;
	const mainDiscountList = product.discount_list || [];
	const bundleDiscountList = getBundleDiscountList(((_product$_extend = product._extend) === null || _product$_extend === void 0 || (_product$_extend = _product$_extend.other) === null || _product$_extend === void 0 ? void 0 : _product$_extend.bundle) || []);
	return [...mainDiscountList, ...bundleDiscountList].reduce((pre, cur) => {
		var _cur$metadata;
		return pre + ((cur === null || cur === void 0 || (_cur$metadata = cur.metadata) === null || _cur$metadata === void 0 ? void 0 : _cur$metadata.product_discount_difference) || 0);
	}, 0);
};
/**
* 总金额
* @param state
* @returns
*/
const getProductExpectAmount = (state, isEdit, isOriginTotal) => {
	let price = new Decimal(0);
	let duration = new Decimal(0);
	const isDay = isDayBooking(state);
	let dayDuration = new Decimal(0);
	let minuteDuration = new Decimal(0);
	if (isEdit) {
		if ((state === null || state === void 0 ? void 0 : state.service) || (state === null || state === void 0 ? 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)) for (let item of state.service.value) if (isDay || isNormalProductByDurationSchedule(item) || isMultiDayProduct(item)) {
				const quantity = new Decimal(item._extend.quantity || 1);
				const itemTotal = new Decimal(item._extend.total || 0);
				const itemOriginTotal = new Decimal(item._extend.origin_total || 0);
				price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));
				price = price.sub(getProductDiscountProductDiscountDifference(item));
				const _duration = !isNormalProductByDurationSchedule(item) ? new Decimal(item._extend.duration || 0) : new Decimal(0);
				if (isDay || isMultiDayProduct(item)) dayDuration = dayDuration.add(_duration);
				else minuteDuration = minuteDuration.add(_duration);
			} else {
				const quantity = new Decimal(item._extend.quantity || 1);
				const itemTotal = new Decimal(item._extend.total || 0);
				const itemOriginTotal = new Decimal(item._extend.origin_total || 0);
				price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));
				const relationTotal = new Decimal(getRelationDetailsTotal(item._extend.relation_details || []));
				price = price.add(relationTotal);
				price = price.sub(getProductDiscountProductDiscountDifference(item));
				const itemDuration = new Decimal(flexibleObj.getValue(item._extend.duration) || 0);
				duration = duration.add(itemDuration);
				if (isMultiDayProduct(item)) dayDuration = dayDuration.add(itemDuration);
				else minuteDuration = minuteDuration.add(itemDuration);
			}
			if (!isDay && Array.isArray((_state$addons = state.addons) === null || _state$addons === void 0 ? void 0 : _state$addons.value)) for (let item of state.addons.value) {
				const quantity = new Decimal(item._extend.quantity || 1);
				const itemTotal = new Decimal(item._extend.total || 0);
				const itemOriginTotal = new Decimal(item._extend.origin_total || 0);
				price = price.add((isOriginTotal ? itemOriginTotal : itemTotal).mul(quantity));
			}
		}
	} 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);
		duration = ((state === null || state === void 0 || (_state$service2 = state.service) === null || _state$service2 === void 0 ? void 0 : _state$service2.value) || []).reduce((pre, cur) => {
			let current = new Decimal(0);
			if (isDay || isMultiDayProduct(cur)) current = !isNormalProductByDurationSchedule(cur) ? new Decimal(cur._extend.duration || 0) : new Decimal(0);
			else {
				var _cur$_extend;
				current = new Decimal(flexibleObj.getValue(((_cur$_extend = cur._extend) === null || _cur$_extend === void 0 ? void 0 : _cur$_extend.duration) || 0) || 0);
			}
			if (isDay || isMultiDayProduct(cur)) dayDuration = dayDuration.add(current);
			else minuteDuration = minuteDuration.add(current);
			return pre.add(current);
		}, new Decimal(0));
	}
	return {
		productExpectAmount: price.toNumber(),
		duration: getDiscountTimeByDayMinutes(dayDuration.toNumber(), minuteDuration.toNumber())
	};
};
/**
* 计算单个商品的税费（返回精确值，不四舍五入）
* @param item 商品信息
* @param state 状态
* @param options 选项
* @returns 精确的税费值（Decimal类型）
*/
const getProductItemTax = (item, state, options) => {
	var _bookingDetail$tax_ra, _ref, _bookingDetail$is_pri;
	const { bookingDetail } = state;
	const { tax_rate, is_price_include_tax } = options;
	const productDiscountPrice = new Decimal(item.total || 0);
	const quantity = new Decimal(item.quantity || 1);
	if (productDiscountPrice.lte(0)) return new Decimal(0);
	const 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);
	const 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;
	let singleItemTax = new Decimal(0);
	if (item.is_charge_tax === 0 || !item.is_charge_tax) singleItemTax = new Decimal(0);
	else if (currentIsPriceIncludeTax === 0) singleItemTax = productDiscountPrice.times(currentTaxRate);
	else {
		const divisor = new Decimal(1).plus(currentTaxRate);
		if (divisor.lte(0)) singleItemTax = new Decimal(0);
		else singleItemTax = productDiscountPrice.dividedBy(divisor).times(currentTaxRate);
	}
	return singleItemTax.times(quantity);
};
/**
* 处理商品税费计算（折扣前后）
* 支持税费舍入差值追加到最后一个含税商品的 tax_fee_rounding_remainder / original_tax_fee_rounding_remainder 字段
* @param items 商品数组
* @param state 状态
* @param options 选项
* @param computed 计算结果
* @returns 累积的税费信息
*/
const processItemsTax = (items, state, options) => {
	const { tax_rate, is_price_include_tax, computed } = options;
	const { shopDiscount, productExpectAmount } = computed;
	let preciseOriginTax = new Decimal(0);
	let preciseTax = new Decimal(0);
	let roundedOriginTax = new Decimal(0);
	let roundedTax = new Decimal(0);
	/**
	* 最后一个含税商品的引用（按物理位置）
	* 用于追加税费舍入差值
	*/
	let lastTaxableItem = null;
	for (let item of items) {
		var _item$_extend, _item$_extend2, _item$_extend$other;
		const quantity = new Decimal(item._extend.quantity || 1);
		const unitPrice = new Decimal(item._extend.total || 0);
		const mainProductPrice = new Decimal(getMainProductTotal(item) || 0);
		let originalTaxPerItemPrecise = getProductItemTax(_objectSpread2(_objectSpread2({}, item), {}, {
			total: mainProductPrice.add(((_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.surcharge_fee) || 0).toNumber(),
			quantity: 1
		}), state, {
			tax_rate,
			is_price_include_tax
		});
		new Decimal(0);
		if (productExpectAmount > 0) unitPrice.dividedBy(productExpectAmount).times(shopDiscount);
		let mainItemDiscount = new Decimal(0);
		if (unitPrice.greaterThan(0)) mainItemDiscount = mainProductPrice.dividedBy(productExpectAmount).times(shopDiscount);
		const mainItemDiscountedUnitPrice = mainProductPrice.minus(mainItemDiscount).add(((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.surcharge_fee) || 0);
		const maxDiscountedTaxPerItemPrecise = getProductItemTax(_objectSpread2(_objectSpread2({}, item), {}, {
			total: mainItemDiscountedUnitPrice.toNumber(),
			price: item._extend.total,
			quantity: 1
		}), state, {
			tax_rate,
			is_price_include_tax
		});
		const maxDiscountedTaxPerItemRounded = maxDiscountedTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
		item._extend.main_product_attached_bundle_tax_fee = maxDiscountedTaxPerItemRounded.toNumber();
		if (maxDiscountedTaxPerItemPrecise.gt(0)) lastTaxableItem = {
			type: "main",
			item
		};
		let addTimePreciseTax = new Decimal(0);
		let addTimeRoundedTax = new Decimal(0);
		if (Array.isArray(item._extend.relation_details)) for (let atItem of item._extend.relation_details) {
			const _originTotal = new Decimal(atItem.selling_price || atItem.price || 0);
			let _discountedTotal = _originTotal;
			if (productExpectAmount > 0) _discountedTotal = _originTotal.minus(_originTotal.dividedBy(productExpectAmount).times(shopDiscount));
			const addTimeTaxPerItemPrecise = getProductItemTax(_objectSpread2(_objectSpread2({}, atItem), {}, {
				total: _discountedTotal.add((atItem === null || atItem === void 0 ? void 0 : atItem.surcharge_fee) || 0).toNumber(),
				quantity: atItem.product_quantity || atItem.num || 1
			}), state, {
				tax_rate,
				is_price_include_tax
			});
			const addTimeTaxPerItemRounded = addTimeTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
			atItem.tax_fee = addTimeTaxPerItemRounded.toNumber();
			addTimePreciseTax = addTimePreciseTax.plus(addTimeTaxPerItemPrecise);
			addTimeRoundedTax = addTimeRoundedTax.plus(addTimeTaxPerItemRounded);
			if (addTimeTaxPerItemPrecise.gt(0)) lastTaxableItem = {
				type: "addTime",
				item: atItem
			};
		}
		let bundlePreciseOriginTax = new Decimal(0);
		let bundlePreciseTax = new Decimal(0);
		let bundleRoundedOriginTax = new Decimal(0);
		let bundleRoundedTax = new Decimal(0);
		if (Array.isArray((_item$_extend$other = item._extend.other) === null || _item$_extend$other === void 0 ? void 0 : _item$_extend$other.bundle)) {
			for (let bundleItem of item._extend.other.bundle) if (getBundleItemIsOriginalPrice(bundleItem)) {
				var _ref2, _bundleItem$bundle_se;
				const bundleQuantity = new Decimal(bundleItem.quantity || 1);
				const bundleUnitPrice = new Decimal((_ref2 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref2 !== void 0 ? _ref2 : 0);
				const bundleOriginalTaxPerItemPrecise = getProductItemTax(_objectSpread2(_objectSpread2({}, bundleItem), {}, {
					total: bundleUnitPrice.add((bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.surcharge_fee) || 0).toNumber(),
					quantity: 1
				}), state, {
					tax_rate,
					is_price_include_tax
				});
				let bundleItemDiscount = new Decimal(0);
				if (productExpectAmount > 0) bundleItemDiscount = bundleUnitPrice.dividedBy(productExpectAmount).times(shopDiscount);
				const bundleDiscountedUnitPrice = bundleUnitPrice.minus(bundleItemDiscount).add((bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.surcharge_fee) || 0);
				const bundleDiscountedTaxPerItemPrecise = getProductItemTax(_objectSpread2(_objectSpread2({}, bundleItem), {}, {
					total: bundleDiscountedUnitPrice.toNumber(),
					quantity: 1
				}), state, {
					tax_rate,
					is_price_include_tax
				});
				const bundleOriginalTaxPerItemRounded = bundleOriginalTaxPerItemPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
				const bundleDiscountedTaxPerItemRounded = bundleDiscountedTaxPerItemPrecise.toDecimalPlaces(2, Decimal.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, Decimal.ROUND_HALF_UP).plus(bundleRoundedOriginTax);
		const taxFeeRounded = maxDiscountedTaxPerItemRounded.plus(bundleRoundedTax);
		item._extend.original_tax_fee = originalTaxFeeRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
		item._extend.tax_fee = taxFeeRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
		preciseOriginTax = preciseOriginTax.plus(originalTaxFeePrecise.times(quantity)).plus(addTimePreciseTax);
		preciseTax = preciseTax.plus(taxFeePrecise.times(quantity)).plus(addTimePreciseTax);
		roundedOriginTax = roundedOriginTax.plus(originalTaxFeeRounded.times(quantity)).plus(addTimeRoundedTax);
		roundedTax = roundedTax.plus(taxFeeRounded.times(quantity)).plus(addTimeRoundedTax);
	}
	const expectedOriginTax = preciseOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
	const expectedTax = preciseTax.toDecimalPlaces(2, Decimal.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,
		taxDecimal: preciseTax
	};
};
/**
* 清除税费相关字段
* 在重新计算税费之前调用，避免残留数据影响计算结果
*/
const clearTaxFee = (state) => {
	const { service, addons } = state;
	if (Array.isArray(service === null || service === void 0 ? void 0 : service.value)) for (let item of service.value) {
		var _item$_extend$other2;
		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 ((_item$_extend$other2 = item._extend.other) === null || _item$_extend$other2 === void 0 ? void 0 : _item$_extend$other2.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 || addons === void 0 ? void 0 : addons.value)) for (let item of addons.value) {
		var _item$_extend$other3;
		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 ((_item$_extend$other3 = item._extend.other) === null || _item$_extend$other3 === void 0 ? void 0 : _item$_extend$other3.bundle) || []) {
			bundleItem.tax_fee = 0;
			bundleItem.original_tax_fee = 0;
			bundleItem.tax_fee_rounding_remainder = void 0;
		}
	}
};
/**
* 税费
* @param state
* @param options 包含 isEdit、computed 和其他税费计算所需参数
* @returns
*/
const getTax = (state, options) => {
	const { isEdit, computed, tax_rate, is_price_include_tax } = options;
	if (!isEdit) {
		var _state$bookingDetail2;
		return { tax: Number((_state$bookingDetail2 = state.bookingDetail) === null || _state$bookingDetail2 === void 0 ? void 0 : _state$bookingDetail2.tax_fee) || 0 };
	}
	clearTaxFee(state);
	let totalOriginTax = new Decimal(0);
	let totalTax = new Decimal(0);
	if ((state === null || state === void 0 ? void 0 : state.service) || (state === null || state === void 0 ? void 0 : state.addons)) {
		var _state$service3, _state$addons2;
		if (state === null || state === void 0 || (_state$service3 = state.service) === null || _state$service3 === void 0 ? void 0 : _state$service3.value) {
			const serviceResult = processItemsTax(state.service.value, state, {
				tax_rate,
				is_price_include_tax,
				computed
			});
			totalOriginTax = totalOriginTax.plus(serviceResult.originTax);
			totalTax = totalTax.plus(serviceResult.taxDecimal);
		}
		if (state === null || state === void 0 || (_state$addons2 = state.addons) === null || _state$addons2 === void 0 ? void 0 : _state$addons2.value) {
			const addonsResult = processItemsTax(state.addons.value, state, {
				tax_rate,
				is_price_include_tax,
				computed
			});
			totalOriginTax = totalOriginTax.plus(addonsResult.originTax);
			totalTax = totalTax.plus(addonsResult.taxDecimal);
		}
	}
	return {
		originTax: totalOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber(),
		tax: totalTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber()
	};
};
/**
* 税费信息
* @param state
* @returns
*/
const getTaxInfo = (state, options) => {
	const { bookingDetail } = state;
	const { tax_rate, tax_title, is_price_include_tax } = options;
	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
	};
};
const getPaySurchargeFee = (state) => {
	const { bookingDetail, bookingId } = state;
	if (!bookingDetail || !bookingId) return 0;
	const processingFee = new Decimal(bookingDetail.pay_processing_fee || 0);
	const gatewayFee = new Decimal(bookingDetail.gateway_fee || 0);
	return processingFee.add(gatewayFee).toNumber();
};
/**
* 判断商品是否符合附加费条件
*/
const isProductMatchSurchargeCondition = (item, options) => {
	var _options$ScheduleModu;
	if (!options.ScheduleModule) {
		console.warn("ScheduleModule not found!");
		return false;
	}
	const isInScheduleByDate = (_options$ScheduleModu = options.ScheduleModule) === null || _options$ScheduleModu === void 0 ? void 0 : _options$ScheduleModu.isInScheduleByDate;
	const { surchargeConfig, scheduleById = {} } = options;
	const { startDate, product_id, isCustomItem } = item;
	const { open_product = 0, is_all = 0, available_product_ids = [], open_schedule = 0, schedule_type, 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 schedule = scheduleById[available_schedule_ids[j]];
		if (schedule) {
			if (isInScheduleByDate({
				date: (startDate === null || startDate === void 0 ? void 0 : startDate.format("YYYY-MM-DD HH:mm:ss")) || "",
				schedule
			})) {
				isScheduleMatch = true;
				break;
			}
		}
	}
	return isProductMatch && isScheduleMatch;
};
const getBundleItemIsOriginalPrice = (item) => {
	return (item === null || item === void 0 ? void 0 : item.price_type) === "markup" && (item === null || item === void 0 ? void 0 : item.price_type_ext) === "product_price";
};
const getBundleItemIsMarkupPrice = (item) => {
	return (item === null || item === void 0 ? void 0 : item.price_type) === "markup" && ((item === null || item === void 0 ? void 0 : item.price_type_ext) === "" || !(item === null || item === void 0 ? void 0 : item.price_type_ext));
};
const getBundleItemIsDiscountPrice = (item) => {
	return (item === null || item === void 0 ? void 0 : item.price_type) === "markdown" && ((item === null || item === void 0 ? void 0 : item.price_type_ext) === "" || !(item === null || item === void 0 ? void 0 : item.price_type_ext));
};
const getBundleItemIsMarkupOrDiscountPrice = (item) => {
	return getBundleItemIsMarkupPrice(item) || getBundleItemIsDiscountPrice(item);
};
const getDiscountAmount = (discounts) => {
	return (discounts || []).reduce((total, discount) => {
		return total.add(new Decimal(discount.amount || 0));
	}, new Decimal(0)).toNumber();
};
const getOptionDiscountAmount = (discounts) => {
	return (discounts || []).reduce((total, discount) => {
		var _discount$metadata;
		return total.add(new Decimal((discount === null || discount === void 0 || (_discount$metadata = discount.metadata) === null || _discount$metadata === void 0 ? void 0 : _discount$metadata.optionDiscountAmount) || 0));
	}, new Decimal(0)).toNumber();
};
/**
* 获取主商品加价减价后的总价 (主商品价格 + 子商品加价减价)
*/
const getMainProductTotal = (item) => {
	var _ref3, _ref4, _item$_extend$main_pr, _item$_extend3, _item$metadata, _item$_extend$other4, _item$_extend$other5, _item$_extend$other7;
	let total = new Decimal((_ref3 = (_ref4 = (_item$_extend$main_pr = (_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.main_product_selling_price) !== null && _item$_extend$main_pr !== void 0 ? _item$_extend$main_pr : item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.main_product_selling_price) !== null && _ref4 !== void 0 ? _ref4 : item._extend.price) !== null && _ref3 !== void 0 ? _ref3 : 0);
	if (((_item$_extend$other4 = item._extend.other) === null || _item$_extend$other4 === void 0 ? void 0 : _item$_extend$other4.option) && Array.isArray((_item$_extend$other5 = item._extend.other) === null || _item$_extend$other5 === void 0 ? void 0 : _item$_extend$other5.option)) {
		var _item$_extend$other6;
		total = total.add((_item$_extend$other6 = item._extend.other) === null || _item$_extend$other6 === void 0 ? void 0 : _item$_extend$other6.option.reduce((t, option) => {
			return t.add(new Decimal(option.price || 0).mul(option.num || 1));
		}, new Decimal(0)));
		if (item.booking_id) total = total.sub(getOptionDiscountAmount((item === null || item === void 0 ? void 0 : item.discount_list) || []));
	}
	for (let bundleItem of ((_item$_extend$other7 = item._extend.other) === null || _item$_extend$other7 === void 0 ? void 0 : _item$_extend$other7.bundle) || []) if (getBundleItemIsMarkupOrDiscountPrice(bundleItem)) {
		var _ref5, _bundleItem$bundle_se2;
		const discountAmount = getDiscountAmount(bundleItem.discount_list);
		const bundleItemTotal = new Decimal((_ref5 = (_bundleItem$bundle_se2 = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se2 !== void 0 ? _bundleItem$bundle_se2 : bundleItem.price) !== null && _ref5 !== void 0 ? _ref5 : 0).minus(discountAmount);
		total = total.add(bundleItemTotal);
	}
	return total.toNumber();
};
/**
* 清除附加费
*/
const clearSurchargeFee = (state) => {
	const { service, addons } = state;
	if (Array.isArray(service === null || service === void 0 ? void 0 : service.value)) for (let item of service.value) {
		var _item$_extend$other8;
		item._extend.surcharge_fee = 0;
		item._extend.surcharge_rounding_remainder = void 0;
		item._extend.relation_surcharge_ids = [];
		for (let bundleItem of ((_item$_extend$other8 = item._extend.other) === null || _item$_extend$other8 === void 0 ? void 0 : _item$_extend$other8.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 || addons === void 0 ? void 0 : addons.value)) for (let item of addons.value) {
		var _item$_extend$other9;
		item._extend.surcharge_fee = 0;
		item._extend.surcharge_rounding_remainder = void 0;
		item._extend.relation_surcharge_ids = [];
		for (let bundleItem of ((_item$_extend$other9 = item._extend.other) === null || _item$_extend$other9 === void 0 ? void 0 : _item$_extend$other9.bundle) || []) {
			bundleItem.surcharge_fee = 0;
			bundleItem.surcharge_rounding_remainder = void 0;
			bundleItem.relation_surcharge_ids = [];
		}
	}
};
/**
* 订单附加费各项信息
* @param state
* @param options 包含 ScheduleModule 和其他附加费计算所需参数
*/
const getSurcharge = (state, options) => {
	const { isEdit, ScheduleModule, surcharge_list, scheduleById } = options;
	const { bookingDetail, bookingId } = state;
	if (!isEdit && bookingId) {
		if (Array.isArray(bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.surcharge)) {
			var _state$bookingDetail3;
			return (((_state$bookingDetail3 = state.bookingDetail) === null || _state$bookingDetail3 === void 0 ? void 0 : _state$bookingDetail3.surcharge) || []).filter((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,
					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 || surcharge_list === void 0 ? 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 || service === void 0 ? void 0 : service.value)) for (let item of service.value) {
			var _item$_extend$other10;
			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,
					isMain: true,
					quantity: mainQuantity,
					item,
					mainQuantity
				});
			}
			for (let bundleItem of ((_item$_extend$other10 = item._extend.other) === null || _item$_extend$other10 === void 0 ? void 0 : _item$_extend$other10.bundle) || []) if (getBundleItemIsOriginalPrice(bundleItem) && isProductMatchSurchargeCondition({
				isCustomItem: false,
				startDate: item._extend.startDate,
				product_id: bundleItem._bundle_product_id
			}, {
				surchargeConfig,
				scheduleById: scheduleById || {},
				ScheduleModule
			})) {
				var _ref6, _bundleItem$bundle_se3;
				const mainQuantity = item._extend.quantity || 1;
				matchedItems.push({
					isMain: false,
					total: Number((_ref6 = (_bundleItem$bundle_se3 = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se3 !== void 0 ? _bundleItem$bundle_se3 : bundleItem.price) !== null && _ref6 !== void 0 ? _ref6 : 0),
					quantity: bundleItem.num || bundleItem.quantity || 1,
					item: bundleItem,
					mainQuantity
				});
			}
			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
			})) {
				var _relationDetail$metad;
				matchedItems.push({
					isMain: false,
					total: Number((relationDetail === null || relationDetail === void 0 ? void 0 : relationDetail.price) || (relationDetail === null || relationDetail === void 0 || (_relationDetail$metad = relationDetail.metadata) === null || _relationDetail$metad === void 0 ? void 0 : _relationDetail$metad.main_product_attached_bundle_selling_price)),
					quantity: relationDetail.num || relationDetail.quantity || 1,
					item: relationDetail,
					mainQuantity: 1
				});
			}
		}
		if (Array.isArray(addons === null || addons === void 0 ? 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
			});
		}
		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 Decimal(0);
		let productTotalSurcharge = new Decimal(0);
		if (matchedItems.length > 0) {
			let configTotal = new Decimal(0);
			if (fixed && new Decimal(fixed).gt(0)) configTotal = configTotal.plus(fixed);
			if (percentage && new Decimal(percentage).gt(0) || fixed) {
				const percentageRate = new Decimal(percentage);
				for (let [index, item] of matchedItems.entries()) {
					const isLast = index === matchedItems.length - 1;
					const itemPrice = new Decimal(Math.max(0, item.total || 0));
					const itemQuantity = new Decimal(item.isMain ? item.quantity || 1 : item.quantity * item.mainQuantity || 1);
					const addTimeTotal = new Decimal(item.addTimeTotal || 0);
					const itemTotalSurcharge = itemPrice.times(itemQuantity).plus(addTimeTotal).times(percentageRate);
					configTotal = configTotal.plus(itemTotalSurcharge);
					const itemSurcharge = itemPrice.times(percentageRate);
					const fixedSurcharge = new Decimal(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 Decimal(fixedSurcharge).times(quantity).toNumber());
					if (isLast && fixedTotal.gt(0)) {
						const remaining = new Decimal(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) {
						var _item$item$_extend;
						const surchargeFee = new Decimal(item.item._extend.surcharge_fee || 0).plus(itemSurcharge).plus(fixedSurcharge).toDecimalPlaces(2, Decimal.ROUND_DOWN).toNumber();
						productTotalSurcharge = productTotalSurcharge.plus(new Decimal(surchargeFee).times(itemQuantity).toNumber());
						item.item._extend.surcharge_fee = surchargeFee;
						item.item._extend.relation_surcharge_ids = [...((_item$item$_extend = item.item._extend) === null || _item$item$_extend === void 0 ? void 0 : _item$item$_extend.relation_surcharge_ids) || [], id];
					} else {
						var _item$item;
						const surchargeFee = new Decimal(item.item.surcharge_fee || 0).plus(itemSurcharge).plus(fixedSurcharge).toDecimalPlaces(2, Decimal.ROUND_DOWN).toNumber();
						productTotalSurcharge = productTotalSurcharge.plus(new Decimal(surchargeFee).times(itemQuantity).toNumber());
						item.item.surcharge_fee = surchargeFee;
						item.item.relation_surcharge_ids = [...((_item$item = item.item) === null || _item$item === void 0 ? void 0 : _item$item.relation_surcharge_ids) || [], id];
					}
					if (isLast && configTotal.minus(productTotalSurcharge).gt(0)) {
						const configTotalRounded = configTotal.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
						if (item.isMain) {
							let newRoundingRemainder = new Decimal(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 Decimal(item.item.surcharge_rounding_remainder || 0);
							newRoundingRemainder = newRoundingRemainder.plus(configTotalRounded.minus(productTotalSurcharge));
							item.item.surcharge_rounding_remainder = newRoundingRemainder.toNumber();
						}
					}
				}
			}
			finalAmount = configTotal.toDecimalPlaces(2, Decimal.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,
			type: "default",
			fixed,
			amount: finalAmount,
			percentage,
			metadata: { open_product }
		});
	}
	return surchargeWithAmount;
};
/**
* 订单附加费
* @param state
* @returns
*/
const 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);
};
/**
* 已付金额 包含手续费
* @param state
* @returns
*/
const getPaidAmount = (state) => {
	var _state$paymentPaid, _state$bookingDetail4;
	const { bookingDetail, bookingId } = state;
	if ((_state$paymentPaid = state.paymentPaid) === null || _state$paymentPaid === void 0 || (_state$paymentPaid = _state$paymentPaid.value) === null || _state$paymentPaid === void 0 ? 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;
	}
	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
*/
const getOrderPaidAmount = (state) => {
	var _state$paymentPaid3, _state$bookingDetail5;
	const { bookingDetail, bookingId } = state;
	if ((_state$paymentPaid3 = state.paymentPaid) === null || _state$paymentPaid3 === void 0 || (_state$paymentPaid3 = _state$paymentPaid3.value) === null || _state$paymentPaid3 === void 0 ? 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;
	}
	if (!bookingDetail || !bookingId) return 0;
	return Number((_state$bookingDetail5 = state.bookingDetail) === null || _state$bookingDetail5 === void 0 ? void 0 : _state$bookingDetail5.order_paid_amount) || 0;
};
const 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;
};
const getExpectAmount = ({ price, tax, surchargeAmount, shopDiscount, state, options }) => {
	let _tax = tax;
	if (getIsPriceIncludeTax(state) || (options === null || options === void 0 ? void 0 : options.is_price_include_tax)) _tax = 0;
	return price + _tax + surchargeAmount - shopDiscount;
};
const getTotalRefundAmount = (state) => {
	var _state$bookingDetail7;
	return Number((_state$bookingDetail7 = state.bookingDetail) === null || _state$bookingDetail7 === void 0 ? void 0 : _state$bookingDetail7.total_refund_amount) || 0;
};
const getShopDiscount = (state) => {
	var _state$bookingDetail8;
	return Number(state.shop_discount) || Number((_state$bookingDetail8 = state.bookingDetail) === null || _state$bookingDetail8 === void 0 ? void 0 : _state$bookingDetail8.shop_discount) || 0;
};
const 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;
};
const getSumTotalAmount = ({ expectAmount, roundingAmount }) => {
	return expectAmount + roundingAmount;
};
/**
* 总金额
* @param state
* @param options isEdit: 预约信息是否发生变动
* @returns
*/
const 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 { tax, originTax } = getTax(state, _objectSpread2({ computed: {
		productExpectAmount,
		shopDiscount
	} }, 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 Decimal(formatAmount(sumTotalAmount, 2, "") || 0);
	const orderPaidAmountDecimal = new Decimal(orderPaidAmount || 0);
	const notPaidAmount = sumTotalAmountDecimal.sub(orderPaidAmountDecimal).toNumber();
	return {
		productAmount: productExpectAmount,
		duration,
		tax,
		taxInfo,
		shopDiscount,
		surcharge,
		otherAmount: surchargeAmount,
		sumTotalAmount,
		paidAmount,
		notPaidAmount,
		paySurchargeFee,
		expectAmount,
		actualPaidAmount: paidAmount,
		orderPaidAmount,
		totalRefundAmount,
		dueAmount: notPaidAmount < 0 ? Number(formatAmount(new Decimal(notPaidAmount).add(new Decimal(totalRefundAmount)).toNumber(), 2, "")) : 0,
		roundingAmount,
		originExpectAmount,
		originExpectAmountWithoutDiscount
	};
};
//#endregion
export { getOptionDiscountAmount, getProductDiscountProductDiscountDifference, getRelationDetailsTotal, getSumTotal };
