const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_amount = require("../footer/amount.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_index = require("../../../../pro/priceKeyboard/components/discountKeyboard/index.js");
const require_bookingTicket = require("../../../ticketBooking/hooks/pisellos/bookingTicket.js");
const require_useActiveExecute = require("../../../ticketBooking/hooks/pisellos/useActiveExecute.js");
const require_useCartChangeEffect = require("../../../ticketBooking/hooks/pisellos/useCartChangeEffect.js");
const require_useLogger = require("../../../../hooks/useLogger.js");
const require_useShopDiscountModule = require("../../../ticketBooking/hooks/pisellos/useShopDiscountModule.js");
const require_index$1 = require("../clearCartModal/index.js");
const require_index$2 = require("../customiseItemModal/index.js");
const require_index$3 = require("../voucherModal/index.js");
const require_useScanManager = require("../../../ticketBooking/hooks/pisellos/useScanManager.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let decimal_js = require("decimal.js");
decimal_js = require_runtime.__toESM(decimal_js);
let _pisell_materials = require("@pisell/materials");
let _pisell_icon = require("@pisell/icon");
require("./index.less");
//#region src/components/booking/components/actionButtons/index.tsx
const createToastContent = (text) => /* @__PURE__ */ react.default.createElement("div", { className: "action-buttons-toast-content" }, text);
const ActionButtons = ({ state, dispatch, disabled = false, source }) => {
	var _context$appHelper, _state$service2, _state$addons2, _state$service4, _state$service6, _context$appHelper3, _state$service8, _state$addons4, _context$appHelper4, _context$appHelper4$g;
	const [showClearModal, setShowClearModal] = (0, react.useState)(false);
	const [showPriceAdjustModal, setShowPriceAdjustModal] = (0, react.useState)(false);
	const [showCustomiseModal, setShowCustomiseModal] = (0, react.useState)(false);
	const [showVoucherModal, setShowVoucherModal] = (0, react.useState)(false);
	const { onCartChange } = require_useCartChangeEffect.default();
	const { executeIfActive } = require_useActiveExecute.useActiveExecute();
	const context = require_useEngineContext.default();
	const { getData, pisellosAllModule } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const Toast = (0, _pisell_materials.useToast)();
	require_useEngineContext.usePisellOS();
	const bookingTicket = require_bookingTicket.useBookingTicket();
	const { ScheduleModule } = pisellosAllModule;
	const shopDiscount = require_useShopDiscountModule.useShopDiscountModule();
	const logger = require_useLogger.default();
	const { clearAllScanListenersTaskQueue } = require_useScanManager.default();
	(0, react.useEffect)(() => {
		if (!bookingTicket) return;
		const handleCustomerSelected = () => {
			dispatch({
				type: "setState",
				payload: { shop_discount: "0" }
			});
		};
		const wrappedHandleCustomerSelected = executeIfActive(handleCustomerSelected);
		bookingTicket.effectsOn("onCustomerSelected", wrappedHandleCustomerSelected);
		return () => {
			bookingTicket.effectsOff("onCustomerSelected", wrappedHandleCustomerSelected);
		};
	}, [dispatch, bookingTicket]);
	const getDataFromHost = () => {
		try {
			const is_price_include_tax = getData("is_price_include_tax");
			const tax_rate = getData("tax_rate") || "10";
			const tax_title = getData("tax_title") || "GST";
			const surcharge_list = getData("surcharge_list");
			const schedule_list = getData("schedule_list");
			let scheduleById = {};
			if (Array.isArray(schedule_list)) for (let item of schedule_list) scheduleById[item.id] = item;
			return {
				is_price_include_tax,
				tax_rate,
				tax_title,
				surcharge_list,
				schedule_list,
				scheduleById
			};
		} catch (error) {
			console.error(error);
			return {};
		}
	};
	const hasCartItems = (0, react.useMemo)(() => {
		var _state$service, _state$addons;
		return ((state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 || (_state$service = _state$service.value) === null || _state$service === void 0 ? void 0 : _state$service.length) || 0) + ((state === null || state === void 0 || (_state$addons = state.addons) === null || _state$addons === void 0 || (_state$addons = _state$addons.value) === null || _state$addons === void 0 ? void 0 : _state$addons.length) || 0) > 0;
	}, [state === null || state === void 0 || (_state$service2 = state.service) === null || _state$service2 === void 0 ? void 0 : _state$service2.value, state === null || state === void 0 || (_state$addons2 = state.addons) === null || _state$addons2 === void 0 ? void 0 : _state$addons2.value]);
	const isDisabledEdit = (0, react.useMemo)(() => {
		return disabled || (state === null || state === void 0 ? void 0 : state.disabledEdit) || (state === null || state === void 0 ? void 0 : state.channelDisabledEdit);
	}, [
		disabled,
		state === null || state === void 0 ? void 0 : state.disabledEdit,
		state === null || state === void 0 ? void 0 : state.channelDisabledEdit
	]);
	const currentTotalPrice = (0, react.useMemo)(() => {
		if (!hasCartItems) return 0;
		try {
			const { productAmount } = require_amount.getSumTotal(state, require_objectSpread2._objectSpread2({
				isEdit: true,
				ScheduleModule
			}, getDataFromHost()));
			return productAmount;
		} catch (error) {
			console.error("计算总价失败:", error);
			return 0;
		}
	}, [state, hasCartItems]);
	const currentTotalPriceAfterDiscount = (0, react.useMemo)(() => {
		return new decimal_js.default(currentTotalPrice).minus(state.shop_discount || 0).toNumber();
	}, [state.shop_discount, currentTotalPrice]);
	const [discountList, setDiscountList] = (0, react.useState)([]);
	const usedVouchersCount = (0, react.useMemo)(() => {
		try {
			var _state$service3;
			if (!((_state$service3 = state.service) === null || _state$service3 === void 0 || (_state$service3 = _state$service3.value) === null || _state$service3 === void 0 ? void 0 : _state$service3.length)) return 0;
			return discountList.filter((discount) => discount.isSelected).length;
		} catch (error) {
			console.error("计算已使用券数量失败:", error);
			return 0;
		}
	}, [discountList, (_state$service4 = state.service) === null || _state$service4 === void 0 ? void 0 : _state$service4.value]);
	const shouldShowWarning = (0, react.useMemo)(() => {
		try {
			var _state$service5;
			return ((_state$service5 = state.service) === null || _state$service5 === void 0 || (_state$service5 = _state$service5.value) === null || _state$service5 === void 0 ? void 0 : _state$service5.length) > 0 && discountList.length > 0 && !discountList.some((discount) => discount.isSelected) && discountList.some((discount) => discount.isManualSelect);
		} catch (error) {
			console.error("判断警告状态失败:", error);
			return false;
		}
	}, [discountList, (_state$service6 = state.service) === null || _state$service6 === void 0 ? void 0 : _state$service6.value]);
	(0, react.useEffect)(() => {
		var _context$appHelper2;
		const { pisellos } = ((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils) || {};
		if (!pisellos || !shopDiscount) return;
		const onDiscountListChange = (discount) => {
			setDiscountList(discount);
		};
		const wrappedHandler = executeIfActive(onDiscountListChange);
		shopDiscount.effectsOn("onDiscountListChange", wrappedHandler);
		return () => {
			shopDiscount.effectsOff("onDiscountListChange", wrappedHandler);
		};
	}, [(_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.utils]);
	const handleClear = () => {
		setShowClearModal(true);
	};
	const handleClearItemsOnly = () => {
		logger.addLog({
			title: "ActionButtons: handleClearItemsOnly 调用",
			metadata: {}
		});
		clearAllScanListenersTaskQueue();
		if (!hasCartItems) {
			Toast === null || Toast === void 0 || Toast.info(createToastContent(_pisell_utils.locales.getText("pisell2.clear-cart-modal.empty-cart-tip")));
			return;
		}
		dispatch({
			type: "setService",
			payload: { value: [] }
		});
		onCartChange("clearAll", []);
		dispatch({
			type: "setAddons",
			payload: { value: [] }
		});
		dispatch({
			type: "setState",
			payload: { shop_discount: "0" }
		});
		dispatch({
			type: "setPaymentPaid",
			payload: { value: {} }
		});
		setShowClearModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(_pisell_utils.locales.getText("pisell2.action-buttons.clear-success")));
	};
	const handleClearAllAndReset = () => {
		var _window;
		logger.addLog({
			title: "ActionButtons: handleClearAllAndReset 调用",
			metadata: {}
		});
		clearAllScanListenersTaskQueue();
		(_window = window) === null || _window === void 0 || (_window = _window.shopApi) === null || _window === void 0 || (_window = _window.bookingTicket) === null || _window === void 0 || _window.clearAllCart();
		onCartChange("clearAll", []);
		setShowClearModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(_pisell_utils.locales.getText("pisell2.action-buttons.clear-success")));
	};
	const handleManuelOrder = () => {
		if (!hasCartItems) {
			Toast === null || Toast === void 0 || Toast.info(createToastContent(_pisell_utils.locales.getText("pisell2.action-buttons.no-items-to-adjust")));
			return;
		}
		setShowPriceAdjustModal(true);
	};
	(0, react.useEffect)(() => {
		var _state$service7, _state$addons3;
		if (((_state$service7 = state.service) === null || _state$service7 === void 0 || (_state$service7 = _state$service7.value) === null || _state$service7 === void 0 ? void 0 : _state$service7.length) === 0 && ((_state$addons3 = state.addons) === null || _state$addons3 === void 0 || (_state$addons3 = _state$addons3.value) === null || _state$addons3 === void 0 ? void 0 : _state$addons3.length) === 0) dispatch({
			type: "setState",
			payload: { shop_discount: 0 }
		});
	}, [(_state$service8 = state.service) === null || _state$service8 === void 0 ? void 0 : _state$service8.value, (_state$addons4 = state.addons) === null || _state$addons4 === void 0 ? void 0 : _state$addons4.value]);
	const handlePriceAdjustConfirm = (discountAmount) => {
		dispatch({
			type: "setState",
			payload: { shop_discount: new decimal_js.default(discountAmount || 0).toDecimalPlaces(2, decimal_js.default.ROUND_DOWN).toString() }
		});
		setShowPriceAdjustModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(_pisell_utils.locales.getText("pisell2.action-buttons.price-adjusted-success")));
	};
	const handleCustomiseItem = () => {
		setShowCustomiseModal(true);
	};
	const handleGoodPassClick = () => {
		setShowVoucherModal(true);
	};
	const handleCustomiseItemSave = (data) => {
		var _state$service9;
		console.log("保存自定义商品:", data);
		dispatch({
			type: "setService",
			payload: {
				value: [{
					id: `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
					_id: `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
					title: data.productName,
					name: data.productName,
					price: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
					total: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
					num: data.quantity,
					is_bundle: 0,
					isCustomItem: true,
					vouchersApplicable: data.vouchersApplicable,
					_extend: {
						num: data.quantity,
						price: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
						product_id: 0,
						discount_amount: 0,
						product_discount_reason: "",
						name: data.productName,
						note: "",
						discountway: "num",
						discount_type: data.priceType === "deduction" ? "discount" : "normal",
						order_detail_id: 0,
						startDate: (0, dayjs.default)(),
						endDate: (0, dayjs.default)(),
						quantity: data.quantity,
						total: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1),
						origin_total: parseFloat(data.priceValue) * (data.priceType === "deduction" ? -1 : 1)
					},
					new: 1
				}, ...(state === null || state === void 0 || (_state$service9 = state.service) === null || _state$service9 === void 0 ? void 0 : _state$service9.value) || []],
				changeService: false
			}
		});
		setShowCustomiseModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(_pisell_utils.locales.getText("pisell2.customise-item.save-success")));
	};
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__action-buttons" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
		className: "action-button clear-button",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Trash01, { size: 22 }),
		onClick: handleClear,
		type: "text",
		disabled: isDisabledEdit
	}), /* @__PURE__ */ react.default.createElement(antd.Button, {
		className: "action-button customise-button",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.PlusCircle, { size: 22 }),
		onClick: handleCustomiseItem,
		type: "text",
		disabled: isDisabledEdit
	}, _pisell_utils.locales.getText("pisell2.action-buttons.customise-item")), /* @__PURE__ */ react.default.createElement(antd.Button, {
		className: "action-button manuel-button",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Calculator, { size: 22 }),
		onClick: handleManuelOrder,
		type: "text",
		disabled: isDisabledEdit
	}, _pisell_utils.locales.getText("pisell2.action-buttons.manuel-order")), /* @__PURE__ */ react.default.createElement("div", { className: "action-button-wrapper" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
		className: "action-button goodpass-button",
		icon: /* @__PURE__ */ react.default.createElement(_pisell_icon.Sale03, { size: 22 }),
		onClick: handleGoodPassClick,
		type: "text"
	}, _pisell_utils.locales.getText("pisell2.text.goodpass")), usedVouchersCount > 0 && /* @__PURE__ */ react.default.createElement("div", { className: "voucher-badge" }, usedVouchersCount), shouldShowWarning && /* @__PURE__ */ react.default.createElement("div", { className: "voucher-warning-icon" }, "!"))), /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		visible: showClearModal,
		onCancel: () => setShowClearModal(false),
		onClearItemsOnly: handleClearItemsOnly,
		onClearAllAndReset: handleClearAllAndReset
	}), /* @__PURE__ */ react.default.createElement(require_index.default, {
		containerProps: {
			renderType: "modal",
			open: showPriceAdjustModal,
			onCancel: () => setShowPriceAdjustModal(false)
		},
		selectType: "dark",
		originalValue: currentTotalPrice,
		defaultValue: currentTotalPriceAfterDiscount,
		onEnter: handlePriceAdjustConfirm
	}), /* @__PURE__ */ react.default.createElement(require_index$2.default, {
		visible: showCustomiseModal,
		onClose: () => setShowCustomiseModal(false),
		onSave: handleCustomiseItemSave,
		currencySymbol: ((_context$appHelper4 = context.appHelper) === null || _context$appHelper4 === void 0 || (_context$appHelper4 = _context$appHelper4.utils) === null || _context$appHelper4 === void 0 || (_context$appHelper4$g = _context$appHelper4.getSymbolic) === null || _context$appHelper4$g === void 0 ? void 0 : _context$appHelper4$g.call(_context$appHelper4)) || "$",
		disabled: isDisabledEdit
	}), /* @__PURE__ */ react.default.createElement(require_index$3.default, {
		visible: showVoucherModal,
		onClose: () => setShowVoucherModal(false),
		state,
		dispatch,
		source
	}));
};
//#endregion
exports.default = ActionButtons;
