const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_index = require("../../../../plus/productSelect/index.js");
const require_transformProductDetail = require("../../../scanOrder/utils/transformProductDetail.js");
const require_context = require("../../context.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
require("./index.less");
//#region src/components/venueBooking/components/Addons/index.tsx
/**
* venueBooking 附加商品步骤（Step 2）
* 参照 scanOrder/Menu 实现，使用系统 ProductSelect 组件展示商品列表
* 用户可通过数量加减或打开商品详情添加附加商品到订单
*/
function Addons() {
	var _scrollRef$current;
	const { utils } = require_useEngineContext.default().appHelper || {};
	const { runModuleAction, refreshViewModel, viewModel, goToStep } = require_context.useVenueBookingContext();
	const productList = viewModel.addonProductList || [];
	const scrollRef = (0, react.useRef)(null);
	const isMobileView = (0, _pisell_utils.isMobile)();
	const maxHeight = window.innerHeight - 100;
	(0, react.useEffect)(() => {
		if (productList.length > 0) return;
		(function() {
			var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					const res = yield runModuleAction("getAddonProducts");
					if (Array.isArray(res)) refreshViewModel({ addonProductList: res });
					else antd.Modal.confirm({
						title: (res === null || res === void 0 ? void 0 : res.message) || String(_pisell_utils.locales.getText("pisell2.venue.error.load.products") || "商品加载失败"),
						okText: String(_pisell_utils.locales.getText("pisell2.event.confirm") || "确认"),
						cancelButtonProps: { style: { display: "none" } },
						maskClosable: false,
						onOk: () => {
							location.replace("/");
						}
					});
				} catch (error) {
					console.error("[venueBooking] getProductList failed", error);
				}
			});
			return function fetchProductList() {
				return _ref.apply(this, arguments);
			};
		})()();
	}, []);
	const addOrderProduct = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			const { orderProduct, sourceData } = params;
			try {
				yield runModuleAction("addProductToOrder", orderProduct);
				yield refreshViewModel();
			} catch (error) {
				console.error("[venueBooking] addProductToOrder failed", {
					error,
					sourceData,
					mappedData: orderProduct
				});
			}
		});
		return function addOrderProduct(_x) {
			return _ref2.apply(this, arguments);
		};
	}();
	const removeOrderProduct = function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			const { product_id, product_variant_id, identity_key, sourceData } = params;
			try {
				yield runModuleAction("removeProductFromOrder", require_objectSpread2._objectSpread2({
					product_id,
					product_variant_id
				}, identity_key ? { identity_key } : {}));
				yield refreshViewModel();
			} catch (error) {
				console.error("[venueBooking] removeProductFromOrder failed", {
					error,
					sourceData,
					product_id,
					product_variant_id,
					identity_key
				});
			}
		});
		return function removeOrderProduct(_x2) {
			return _ref3.apply(this, arguments);
		};
	}();
	const updateOrderProduct = function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			const { product_id, product_variant_id, identity_key, updates, sourceData } = params;
			try {
				yield runModuleAction("updateProductInOrder", require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
					product_id,
					product_variant_id
				}, identity_key ? { identity_key } : {}), {}, { updates }));
				yield refreshViewModel();
			} catch (error) {
				console.error("[venueBooking] updateProductInOrder failed", {
					error,
					sourceData,
					product_id,
					product_variant_id,
					identity_key,
					updates
				});
			}
		});
		return function updateOrderProduct(_x3) {
			return _ref4.apply(this, arguments);
		};
	}();
	/**
	* ProductSelect 选品回调
	* 参照 scanOrder/Menu 的分支逻辑：
	* - meta.intent === 'quantity' → 直接增减数量
	* - 其他 → 打开商品详情弹窗
	*/
	const handleSelectProduct = function() {
		var _ref7 = require_asyncToGenerator._asyncToGenerator(function* (item, clickType, meta) {
			const sourceItem = (meta === null || meta === void 0 ? void 0 : meta.product) || item;
			if ((meta === null || meta === void 0 ? void 0 : meta.intent) === "quantity") {
				var _item$option, _item$bundle, _item$price, _item$product_id, _ref5, _meta$quantity, _orderProduct$product, _orderProduct$product4;
				const quantityData = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, {
					quantity: item === null || item === void 0 ? void 0 : item.num,
					option: (_item$option = item === null || item === void 0 ? void 0 : item.option) !== null && _item$option !== void 0 ? _item$option : item === null || item === void 0 ? void 0 : item.product_option_item,
					bundle: (_item$bundle = item === null || item === void 0 ? void 0 : item.bundle) !== null && _item$bundle !== void 0 ? _item$bundle : item === null || item === void 0 ? void 0 : item.product_bundle,
					origin: sourceItem,
					price: (_item$price = item === null || item === void 0 ? void 0 : item.price) !== null && _item$price !== void 0 ? _item$price : item === null || item === void 0 ? void 0 : item.selling_price
				});
				const orderProduct = require_transformProductDetail.transformProductDetailToOrderProduct({
					payload: quantityData,
					fallbackProductId: (_item$product_id = item === null || item === void 0 ? void 0 : item.product_id) !== null && _item$product_id !== void 0 ? _item$product_id : item === null || item === void 0 ? void 0 : item.id,
					sourceItem
				});
				if (!orderProduct) {
					console.warn("[venueBooking] quantity add missing product_id", quantityData);
					return;
				}
				const nextQuantity = Number((_ref5 = (_meta$quantity = meta === null || meta === void 0 ? void 0 : meta.quantity) !== null && _meta$quantity !== void 0 ? _meta$quantity : quantityData === null || quantityData === void 0 ? void 0 : quantityData.quantity) !== null && _ref5 !== void 0 ? _ref5 : 0);
				const productVariantId = Number((_orderProduct$product = orderProduct === null || orderProduct === void 0 ? void 0 : orderProduct.product_variant_id) !== null && _orderProduct$product !== void 0 ? _orderProduct$product : 0);
				if (Number.isNaN(productVariantId)) {
					console.warn("[venueBooking] quantity action missing product_variant_id", {
						quantityData,
						orderProduct
					});
					return;
				}
				const normalizedQuantity = Number.isNaN(nextQuantity) ? 0 : Math.max(0, Math.floor(nextQuantity));
				const existedCartItem = (Array.isArray(viewModel === null || viewModel === void 0 ? void 0 : viewModel.cartItems) ? viewModel.cartItems : []).find((cartItem) => {
					var _cartItem$product_id, _orderProduct$product2, _cartItem$product_var;
					return String((_cartItem$product_id = cartItem === null || cartItem === void 0 ? void 0 : cartItem.product_id) !== null && _cartItem$product_id !== void 0 ? _cartItem$product_id : null) === String((_orderProduct$product2 = orderProduct === null || orderProduct === void 0 ? void 0 : orderProduct.product_id) !== null && _orderProduct$product2 !== void 0 ? _orderProduct$product2 : null) && Number((_cartItem$product_var = cartItem === null || cartItem === void 0 ? void 0 : cartItem.product_variant_id) !== null && _cartItem$product_var !== void 0 ? _cartItem$product_var : 0) === productVariantId;
				});
				const existedIdentityKey = typeof (existedCartItem === null || existedCartItem === void 0 ? void 0 : existedCartItem.identity_key) === "string" && existedCartItem.identity_key.length > 0 ? existedCartItem.identity_key : void 0;
				if (normalizedQuantity <= 0) {
					var _orderProduct$product3;
					yield removeOrderProduct({
						product_id: (_orderProduct$product3 = orderProduct === null || orderProduct === void 0 ? void 0 : orderProduct.product_id) !== null && _orderProduct$product3 !== void 0 ? _orderProduct$product3 : null,
						product_variant_id: productVariantId,
						identity_key: existedIdentityKey,
						sourceData: quantityData
					});
					return;
				}
				if (!existedCartItem) {
					yield addOrderProduct({
						orderProduct: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, orderProduct), {}, { num: normalizedQuantity }),
						sourceData: quantityData
					});
					return;
				}
				yield updateOrderProduct({
					product_id: (_orderProduct$product4 = orderProduct === null || orderProduct === void 0 ? void 0 : orderProduct.product_id) !== null && _orderProduct$product4 !== void 0 ? _orderProduct$product4 : null,
					product_variant_id: productVariantId,
					identity_key: existedIdentityKey,
					updates: {
						num: normalizedQuantity,
						_origin: orderProduct === null || orderProduct === void 0 ? void 0 : orderProduct._origin
					},
					sourceData: quantityData
				});
			} else utils === null || utils === void 0 || utils.action({
				type: "pisell1.productDetail",
				data: {
					detail: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, sourceItem), {}, { open_deposit: 1 }),
					setting: {
						can_input: true,
						item_max_length: 1,
						is_detail_open: true
					}
				},
				callback: function() {
					var _ref6 = require_asyncToGenerator._asyncToGenerator(function* (data) {
						var _item$product_id2;
						if (data === null || data === void 0 ? void 0 : data.isCancel) return;
						const orderProduct = require_transformProductDetail.transformProductDetailToOrderProduct({
							payload: data,
							fallbackProductId: (_item$product_id2 = item === null || item === void 0 ? void 0 : item.product_id) !== null && _item$product_id2 !== void 0 ? _item$product_id2 : item === null || item === void 0 ? void 0 : item.id,
							sourceItem
						});
						if (!orderProduct) {
							console.warn("[venueBooking] productDetail callback missing product_id", data);
							return;
						}
						yield addOrderProduct({
							orderProduct,
							sourceData: data
						});
					});
					return function callback(_x4) {
						return _ref6.apply(this, arguments);
					};
				}()
			});
		});
		return function handleSelectProduct(_x5, _x6, _x7) {
			return _ref7.apply(this, arguments);
		};
	}();
	const productSelectNode = /* @__PURE__ */ react.default.createElement(require_index.default, {
		dataSource: productList,
		onChange: handleSelectProduct,
		loading: false,
		emptyDescription: _pisell_utils.locales.getText("pisell2.venue.addons.empty"),
		token: {
			colorPrimary: "var(--theme-color)",
			containerBg: "#FFFFFF",
			tabItemBg: "#F2F4F7",
			tabItemHoverBg: "#F2F4F7",
			tabItemActiveBg: "var(--theme-color)",
			categoryTextColor: "#1B1B1B",
			cardSelectedBg: "var(--theme-color)"
		},
		customScrollParent: ((_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.getScrollContainer()) || "",
		hideCategoryWhenOne: true,
		version: "v2",
		value: (viewModel === null || viewModel === void 0 ? void 0 : viewModel.cartItems) || [],
		productListSetting: {
			imgWidth: 80,
			imgHeight: 80
		},
		cartElementId: "#venue-booking-cart-btn"
	});
	if (isMobileView) return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-venue-booking-addons pisell-venue-booking-addons--mobile" }, productSelectNode);
	return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-venue-booking-addons" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellScrollView, {
		maxHeight,
		overflow: "y",
		ref: scrollRef
	}, productSelectNode));
}
//#endregion
exports.default = Addons;
