import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { setProductPrice } from "../../../components/booking/info2/service/editService/utils.js";
import { genHolderKey, genServiceKey } from "../../../components/ticketBooking/utils/index.js";
import { getServiceTimes } from "../../../components/booking/utils.js";
import { mergeFormIntoExtend } from "./mergeFormIntoExtend.js";
import { resolveCacheItemForResourceCheck } from "./resolveCacheItemForResourceCheck.js";
import { getUniqueId } from "@pisell/utils";
import Decimal from "decimal.js";
//#region src/plus/salesSdk/bookingEditService/buildEditedCacheItem.ts
/** 手动改价时剔除旧 type=product 项；新项由 OS transform 根据 origin/total/reason 合成 */
function stripManualProductDiscountFromList(discountList) {
	return (discountList || []).filter((item) => (item === null || item === void 0 ? void 0 : item.type) !== "product");
}
/**
* 将编辑抽屉表单值合并为可交给 `cart.confirmBookingEdit` 的 cacheItem。
* 对齐 Info2 editService `onFinish` 的核心合并逻辑，不写 miniRedux / 不拆 service 列表。
*/
function buildEditedCacheItem(options) {
	var _item$_extend2;
	const { values, cacheItem: sourceItem, isEditGroup, isChangeTotal, isPriceIncludeTax } = options;
	let item = _objectSpread2(_objectSpread2({ is_price_include_tax: isPriceIncludeTax }, sourceItem), {}, { autoClose: false });
	let extend = mergeFormIntoExtend(item._extend, values);
	if (values.quantity !== void 0) extend.other = _objectSpread2(_objectSpread2({}, extend.other || {}), {}, { quantity: values.quantity });
	if (isEditGroup) {
		extend.quantity = 1;
		extend.startDate = extend === null || extend === void 0 ? void 0 : extend.start_date;
		extend.endDate = extend === null || extend === void 0 ? void 0 : extend.end_date;
	} else {
		const { startDate, endDate } = getServiceTimes({ _extend: extend });
		extend.startDate = startDate;
		extend.endDate = endDate;
	}
	if (isChangeTotal) {
		var _ref, _extend$origin_total, _item$_extend;
		const originTotal = (_ref = (_extend$origin_total = extend.origin_total) !== null && _extend$origin_total !== void 0 ? _extend$origin_total : (_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.origin_total) !== null && _ref !== void 0 ? _ref : values.origin_total;
		applyManualDiscountToExtend(extend, values.total, originTotal);
		extend.priceOverride = values.total;
		if (extend.origin_total == null || extend.origin_total === "") extend.origin_total = originTotal;
	}
	if (extend.bundle_edit !== void 0) extend.bundle_edit = 1;
	item._extend = extend;
	item._time = (/* @__PURE__ */ new Date()).getTime();
	item._serviceKey = genServiceKey(item);
	item._holderKey = genHolderKey(item);
	item = applyHolderSplit(item);
	item = setProductPrice(item, {
		newTotal: values.total,
		origin_total: (_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.origin_total
	});
	if (isChangeTotal) item.discount_list = stripManualProductDiscountFromList(item.discount_list);
	return resolveCacheItemForResourceCheck(_objectSpread2(_objectSpread2({}, item), {}, { new: 0 }));
}
function applyManualDiscountToExtend(extend, total, originTotal) {
	var _extend$other, _extend$other2;
	const discountRatio = new Decimal(total).div(originTotal);
	const bundles = (extend === null || extend === void 0 || (_extend$other = extend.other) === null || _extend$other === void 0 ? void 0 : _extend$other.bundle) || [];
	let childProductsTotal = new Decimal(0);
	if (bundles.length > 0) bundles.forEach((bundle) => {
		const discountedPrice = new Decimal(bundle.original_price).mul(discountRatio).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
		bundle.bundle_selling_price = discountedPrice.toNumber();
		childProductsTotal = childProductsTotal.add(discountedPrice.mul(bundle.quantity));
	});
	const mainProductTotal = new Decimal(total).sub(childProductsTotal);
	const mainProductQuantity = ((_extend$other2 = extend.other) === null || _extend$other2 === void 0 ? void 0 : _extend$other2.quantity) || extend.quantity || 1;
	extend.main_product_selling_price = mainProductTotal.div(mainProductQuantity).toNumber();
}
/** 多持有人拆行：SalesSdk 加车仍回传主行 cacheItem（与 Info2 列表拆行区分）。 */
function applyHolderSplit(item) {
	var _item$_extend3, _item$_extend4;
	const holderIds = (_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.holder_id;
	if ((holderIds === null || holderIds === void 0 ? void 0 : holderIds.length) > 1 || ((_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.quantity) > 1 && (holderIds === null || holderIds === void 0 ? void 0 : holderIds.length) >= 1) {
		const ids = [...holderIds];
		item._extend.holder_id = ids[0];
		if (item._extend.quantity > 1) item._extend.quantity = 1;
		item._holderKey = genHolderKey(item);
		item._splitHolderRemainder = ids.slice(1).map((holder_id) => ({
			_id: getUniqueId(),
			holder_id: [holder_id],
			quantity: 1
		}));
	}
	return item;
}
//#endregion
export { buildEditedCacheItem };
