import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import shoppingCart from "../../../shoppingCart/index.js";
import SubTotal from "../../../subTotal/index.js";
import { useVenueBookingContext } from "../../context.js";
import VoucherCard from "../Voucher/index.js";
import VenueDeposit from "../Deposit/index.js";
import React, { useEffect, useMemo } from "react";
import { message } from "antd";
import { locales } from "@pisell/utils";
import { Button as Button$1 } from "@pisell/materials";
import "./index.less";
//#region src/components/venueBooking/components/Cart/index.tsx
/**
* venueBooking 购物车组件
* 参照 scanOrder/Cart 实现，使用系统内置 ShoppingCart + SubTotal 组件
* 支持两种模式：embedded（桌面端内嵌）和 drawer（移动端抽屉弹出）
*/
function Cart(props) {
	var _engineContext$appHel, _engineContext$appHel2, _engineContext$appHel3, _engineContext$engine, _businessUtils$getApp, _businessUtils$getApp2, _ref, _ref2, _ref3, _summary$total_amount, _summary$deposit3;
	const { open, onCancel, onNext, items, summary, embedded = false, confirmLoading = false, extraContent } = props;
	const { currentStep, runModuleAction, refreshViewModel, venueBookingModule, isAgreeDepositPolicy, setIsAgreeDepositPolicy } = useVenueBookingContext();
	const engineContext = useEngineContext();
	const businessUtils = engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 || (_engineContext$appHel = _engineContext$appHel.utils) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.businessUtils;
	const symbol = String((engineContext === null || engineContext === void 0 || (_engineContext$appHel2 = engineContext.appHelper) === null || _engineContext$appHel2 === void 0 || (_engineContext$appHel2 = _engineContext$appHel2.utils) === null || _engineContext$appHel2 === void 0 || (_engineContext$appHel3 = _engineContext$appHel2.getSymbolic) === null || _engineContext$appHel3 === void 0 ? void 0 : _engineContext$appHel3.call(_engineContext$appHel2)) || "$");
	const locale = (engineContext === null || engineContext === void 0 || (_engineContext$engine = engineContext.engine) === null || _engineContext$engine === void 0 || (_engineContext$engine = _engineContext$engine.props) === null || _engineContext$engine === void 0 ? void 0 : _engineContext$engine.locale) || "en";
	const hasGoodPassApp = !!(businessUtils === null || businessUtils === void 0 || (_businessUtils$getApp = businessUtils.getAppByModal) === null || _businessUtils$getApp === void 0 ? void 0 : _businessUtils$getApp.call(businessUtils, "goodpass"));
	const hasDiscountCardApp = !!(businessUtils === null || businessUtils === void 0 || (_businessUtils$getApp2 = businessUtils.getAppByModal) === null || _businessUtils$getApp2 === void 0 ? void 0 : _businessUtils$getApp2.call(businessUtils, "discountcard"));
	const showVoucher = hasGoodPassApp || hasDiscountCardApp;
	const isVisible = embedded || open;
	if (!isVisible) return null;
	const totalAmount = (_ref = (_ref2 = (_ref3 = (_summary$total_amount = summary === null || summary === void 0 ? void 0 : summary.total_amount) !== null && _summary$total_amount !== void 0 ? _summary$total_amount : summary === null || summary === void 0 ? void 0 : summary.expect_amount) !== null && _ref3 !== void 0 ? _ref3 : summary === null || summary === void 0 ? void 0 : summary.amount) !== null && _ref2 !== void 0 ? _ref2 : summary === null || summary === void 0 ? void 0 : summary.total) !== null && _ref !== void 0 ? _ref : "0.00";
	const cartProducts = useMemo(() => {
		return (items || []).map((item) => _objectSpread2(_objectSpread2({}, item), {}, {
			symbol: (item === null || item === void 0 ? void 0 : item.symbol) || symbol,
			is_hide_like: true
		}));
	}, [items, symbol]);
	const confirmOrderText = currentStep === "checkout" ? String(locales.getText("pisell2.venue.action.pay.now") || "立即支付") : String(locales.getText("pisell2.venue.action.next") || "下一步");
	/**
	* SubTotal 金额明细列表
	* 从 OS summary 中提取 sub_total / tax / surcharges / total
	* surcharges 为服务费列表，label 支持多语言对象，按当前 locale 取值
	*/
	const subTotalList = useMemo(() => {
		var _summary$product_amou, _summary$tax_fee, _ref4, _summary$total_amount2, _summary$deposit, _venueBookingModule$g, _tempSummary$is_price, _summary$deposit$tota, _summary$deposit2;
		const subTotal = Number((_summary$product_amou = summary === null || summary === void 0 ? void 0 : summary.product_amount) !== null && _summary$product_amou !== void 0 ? _summary$product_amou : 0);
		const totalTaxFee = Number((_summary$tax_fee = summary === null || summary === void 0 ? void 0 : summary.tax_fee) !== null && _summary$tax_fee !== void 0 ? _summary$tax_fee : 0);
		const total = Number((_ref4 = (_summary$total_amount2 = summary === null || summary === void 0 ? void 0 : summary.total_amount) !== null && _summary$total_amount2 !== void 0 ? _summary$total_amount2 : summary === null || summary === void 0 ? void 0 : summary.expect_amount) !== null && _ref4 !== void 0 ? _ref4 : 0);
		const hasDeposit = !!(summary === null || summary === void 0 || (_summary$deposit = summary.deposit) === null || _summary$deposit === void 0 ? void 0 : _summary$deposit.hasDeposit);
		const tempOrder = venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$g = venueBookingModule.getTempOrder) === null || _venueBookingModule$g === void 0 ? void 0 : _venueBookingModule$g.call(venueBookingModule);
		const tempSummary = (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.summary) || {};
		const taxTitle = String((tempSummary === null || tempSummary === void 0 ? void 0 : tempSummary.tax_title) || (summary === null || summary === void 0 ? void 0 : summary.tax_title) || "GST/Tax");
		const rawTaxRate = Number(tempSummary === null || tempSummary === void 0 ? void 0 : tempSummary.tax_rate);
		const normalizedTaxRate = Number.isNaN(rawTaxRate) ? 0 : rawTaxRate > 1 ? rawTaxRate / 100 : rawTaxRate;
		const isPriceIncludeTax = Boolean((_tempSummary$is_price = tempSummary === null || tempSummary === void 0 ? void 0 : tempSummary.is_price_include_tax) !== null && _tempSummary$is_price !== void 0 ? _tempSummary$is_price : tempSummary === null || tempSummary === void 0 ? void 0 : tempSummary.isPriceIncludeTax);
		/** 将 surcharges 数组映射为 SubTotalItem，amount > 0 才展示 */
		const surchargeItems = ((summary === null || summary === void 0 ? void 0 : summary.surcharges) || []).filter((s) => Number(s === null || s === void 0 ? void 0 : s.amount) > 0).map((s) => {
			const labelObj = (s === null || s === void 0 ? void 0 : s.label) || (s === null || s === void 0 ? void 0 : s.name) || {};
			const label = labelObj[locale] || labelObj.en || labelObj.original || (s === null || s === void 0 ? void 0 : s.key) || "";
			return {
				key: (s === null || s === void 0 ? void 0 : s.key) || `surcharge_${s === null || s === void 0 ? void 0 : s.surcharge_id}`,
				label,
				value: Number(s === null || s === void 0 ? void 0 : s.amount)
			};
		});
		return [
			{
				key: "deposit",
				value: Number((_summary$deposit$tota = summary === null || summary === void 0 || (_summary$deposit2 = summary.deposit) === null || _summary$deposit2 === void 0 ? void 0 : _summary$deposit2.total) !== null && _summary$deposit$tota !== void 0 ? _summary$deposit$tota : 0),
				label: locales.getText("pisell2.appointment.deposit") || "Deposit",
				hidden: !hasDeposit
			},
			{
				key: "sub_total",
				value: Number.isNaN(subTotal) ? 0 : subTotal
			},
			...surchargeItems,
			{
				key: "tax",
				value: Number.isNaN(totalTaxFee) ? 0 : totalTaxFee,
				hidden: Number.isNaN(totalTaxFee) ? true : totalTaxFee <= 0,
				tax: {
					title: taxTitle,
					rate: normalizedTaxRate,
					is_price_include_tax: isPriceIncludeTax
				}
			},
			{
				key: "custom_total",
				value: Number.isNaN(total) ? 0 : total,
				label: locales.getText("pisell2.event.total") || "合计",
				bold: !hasDeposit
			}
		];
	}, [
		summary,
		locale,
		venueBookingModule
	]);
	/**
	* 购物车删除操作
	* 调用 OS 模块 removeProductFromOrder 后刷新 viewModel
	*/
	const isVenueBookingCartItem = (target) => {
		if (!target || typeof target !== "object") return false;
		if ((target === null || target === void 0 ? void 0 : target.start_date) && (target === null || target === void 0 ? void 0 : target.end_date)) return true;
		if (String((target === null || target === void 0 ? void 0 : target.identity_key) || "").startsWith("venue:")) return true;
		return false;
	};
	const handleCartChange = function() {
		var _ref6 = _asyncToGenerator(function* (item, type, sourceItem) {
			var _ref5, _targetItem$product_i, _targetItem$product_v;
			if (type !== "delete") return;
			const targetItem = sourceItem && typeof sourceItem === "object" ? sourceItem : item;
			if (currentStep !== "select-venue" && isVenueBookingCartItem(targetItem)) {
				message.warning({
					content: String(locales.getText("pisell2.venue.cart.delete.venue.only.step1") || "请返回第一步后再删除场地商品"),
					duration: 2
				});
				return;
			}
			const productId = (_ref5 = (_targetItem$product_i = targetItem === null || targetItem === void 0 ? void 0 : targetItem.product_id) !== null && _targetItem$product_i !== void 0 ? _targetItem$product_i : targetItem === null || targetItem === void 0 ? void 0 : targetItem.id) !== null && _ref5 !== void 0 ? _ref5 : null;
			const productVariantId = Number((_targetItem$product_v = targetItem === null || targetItem === void 0 ? void 0 : targetItem.product_variant_id) !== null && _targetItem$product_v !== void 0 ? _targetItem$product_v : 0);
			const identityKey = targetItem === null || targetItem === void 0 ? void 0 : targetItem.identity_key;
			if (productId === null && Number.isNaN(productVariantId)) return;
			if (typeof identityKey !== "string" || identityKey.length === 0) {
				console.error("[venueBooking] removeProductFromOrder skipped: missing identity_key", { item: targetItem });
				return;
			}
			try {
				yield runModuleAction("removeProductFromOrder", {
					product_id: productId,
					product_variant_id: Number.isNaN(productVariantId) ? 0 : productVariantId,
					identity_key: identityKey
				});
				yield refreshViewModel();
			} catch (error) {
				console.error("[venueBooking] removeProductFromOrder failed", {
					error,
					item: targetItem
				});
			}
		});
		return function handleCartChange(_x, _x2, _x3) {
			return _ref6.apply(this, arguments);
		};
	}();
	useEffect(() => {
		if (!isVisible) return;
		refreshViewModel();
	}, [isVisible]);
	const cartListContent = /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-body" }, /* @__PURE__ */ React.createElement(shoppingCart, {
		productParams: {
			products: cartProducts,
			hideAddBtn: true,
			disabledEdit: false,
			isShowNote: false,
			isShowDelete: true,
			isShowPackageNote: false,
			isShowChangeHolder: false,
			isShowHolder: false,
			isShowAddHolderButton: false
		},
		platform: "h5",
		emptyText: locales.getText("pisell2.venue.cart.empty"),
		isOpenGroup: false,
		isHideClearCart: true,
		onChange: handleCartChange
	}));
	const cartSummaryContent = /* @__PURE__ */ React.createElement(React.Fragment, null, showVoucher ? /* @__PURE__ */ React.createElement(VoucherCard, null) : null, /* @__PURE__ */ React.createElement(SubTotal, {
		list: subTotalList,
		style: { padding: 0 }
	}, (summary === null || summary === void 0 || (_summary$deposit3 = summary.deposit) === null || _summary$deposit3 === void 0 ? void 0 : _summary$deposit3.hasDeposit) ? /* @__PURE__ */ React.createElement(VenueDeposit, {
		deposit: summary.deposit,
		isAgreePolicy: isAgreeDepositPolicy,
		onChange: setIsAgreeDepositPolicy,
		getProtocol: (id) => {
			var _venueBookingModule$g2;
			return venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$g2 = venueBookingModule.getProtocol) === null || _venueBookingModule$g2 === void 0 ? void 0 : _venueBookingModule$g2.call(venueBookingModule, id);
		}
	}) : null), extraContent ? /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-extra-content" }, extraContent) : null);
	if (embedded) return /* @__PURE__ */ React.createElement(React.Fragment, null, cartListContent, /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-embedded-footer" }, cartSummaryContent, /* @__PURE__ */ React.createElement(Button$1, {
		type: "primary",
		block: true,
		onClick: onNext,
		loading: confirmLoading
	}, confirmOrderText)));
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
		className: "pisell-venue-booking-cart-mask",
		onClick: onCancel
	}), /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-drawer" }, /* @__PURE__ */ React.createElement("div", {
		className: "pisell-venue-booking-cart-header",
		onClick: onCancel
	}, /* @__PURE__ */ React.createElement("span", {
		className: "pisell-venue-booking-cart-handle",
		"aria-hidden": true
	})), cartListContent, /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-drawer-summary" }, cartSummaryContent), /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-footer" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-total" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-total-label" }, locales.getText("pisell2.event.total") || "合计"), /* @__PURE__ */ React.createElement("div", { className: "pisell-venue-booking-cart-total-amount" }, symbol, Number(totalAmount || 0).toFixed(2))), /* @__PURE__ */ React.createElement(Button$1, {
		type: "primary",
		onClick: onNext,
		loading: confirmLoading
	}, currentStep === "checkout" ? confirmOrderText : locales.getText("pisell2.event.continue") || "继续"))));
}
//#endregion
export { Cart as default };
