import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { getSumTotal } from "../footer/amount.js";
import useEngineContext, { usePisellOS } from "../../../../hooks/useEngineContext.js";
import DiscountKeyboard from "../../../../pro/priceKeyboard/components/discountKeyboard/index.js";
import { useShopDiscountModule } from "../../../ticketBooking/hooks/pisellos/useShopDiscountModule.js";
import { useBookingTicket } from "../../../ticketBooking/hooks/pisellos/bookingTicket.js";
import { useActiveExecute } from "../../../ticketBooking/hooks/pisellos/useActiveExecute.js";
import { useCustomer } from "../../../ticketBooking/hooks/pisellos/useCustomer.js";
import ClearCartModal from "../clearCartModal/index.js";
import CustomiseItemModal from "../customiseItemModal/index.js";
import VoucherModal from "../voucherModal/index.js";
import useScanManager from "../../../ticketBooking/hooks/pisellos/useScanManager.js";
import dayjs from "dayjs";
import React, { useEffect, useMemo, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import Decimal from "decimal.js";
import { useToast } from "@pisell/materials";
import { useMemoizedFn } from "ahooks";
import { Calculator, PlusCircle, Sale03, Trash01 } from "@pisell/icon";
import "./index.less";
//#region src/components/booking/components/actionButtons/index.tsx
const createToastContent = (text) => /* @__PURE__ */ React.createElement("div", { className: "action-buttons-toast-content" }, text);
const ActionButtons = ({ state, dispatch, disabled = false, source }) => {
	var _context$appHelper, _state$service3, _state$addons2, _state$service5, _state$service7, _context$appHelper3, _state$service9, _state$addons4, _context$appHelper4, _context$appHelper4$g;
	const [showClearModal, setShowClearModal] = useState(false);
	const [showPriceAdjustModal, setShowPriceAdjustModal] = useState(false);
	const [showCustomiseModal, setShowCustomiseModal] = useState(false);
	const [showVoucherModal, setShowVoucherModal] = useState(false);
	const { executeIfActive } = useActiveExecute();
	const context = useEngineContext();
	const { getData, pisellosAllModule } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const Toast = useToast();
	usePisellOS();
	const bookingTicket = useBookingTicket();
	const { ScheduleModule } = pisellosAllModule;
	const shopDiscount = useShopDiscountModule();
	const { selectCustomer } = useCustomer({ changeCustomerToGlobalState: useMemoizedFn((value) => {
		var _state$client, _state$service;
		const beforeValue = state === null || state === void 0 || (_state$client = state.client) === null || _state$client === void 0 ? void 0 : _state$client.value;
		dispatch({
			type: "setClient",
			payload: {
				value,
				edit: true
			}
		});
		if ((beforeValue === null || beforeValue === void 0 ? void 0 : beforeValue.id) === (value === null || value === void 0 ? void 0 : value.id)) return;
		if (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) dispatch({
			type: "setService",
			payload: { value: state.service.value.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { _extend: _objectSpread2(_objectSpread2({}, item._extend), {}, { holder_id: [] }) })) }
		});
	}) });
	const { clearAllScanListenersTaskQueue } = useScanManager();
	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 = useMemo(() => {
		var _state$service2, _state$addons;
		return ((state === null || state === void 0 || (_state$service2 = state.service) === null || _state$service2 === void 0 || (_state$service2 = _state$service2.value) === null || _state$service2 === void 0 ? void 0 : _state$service2.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$service3 = state.service) === null || _state$service3 === void 0 ? void 0 : _state$service3.value, state === null || state === void 0 || (_state$addons2 = state.addons) === null || _state$addons2 === void 0 ? void 0 : _state$addons2.value]);
	const isDisabledEdit = 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 = useMemo(() => {
		if (!hasCartItems) return 0;
		try {
			const { productAmount } = getSumTotal(state, _objectSpread2({
				isEdit: true,
				ScheduleModule
			}, getDataFromHost()));
			return productAmount;
		} catch (error) {
			console.error("计算总价失败:", error);
			return 0;
		}
	}, [state, hasCartItems]);
	const currentTotalPriceAfterDiscount = useMemo(() => {
		return new Decimal(currentTotalPrice).minus(state.shop_discount || 0).toNumber();
	}, [state.shop_discount, currentTotalPrice]);
	const [discountList, setDiscountList] = useState([]);
	const usedVouchersCount = useMemo(() => {
		try {
			var _state$service4;
			if (!((_state$service4 = state.service) === null || _state$service4 === void 0 || (_state$service4 = _state$service4.value) === null || _state$service4 === void 0 ? void 0 : _state$service4.length)) return 0;
			return discountList.filter((discount) => discount.isSelected).length;
		} catch (error) {
			console.error("计算已使用券数量失败:", error);
			return 0;
		}
	}, [discountList, (_state$service5 = state.service) === null || _state$service5 === void 0 ? void 0 : _state$service5.value]);
	const shouldShowWarning = useMemo(() => {
		try {
			var _state$service6;
			return ((_state$service6 = state.service) === null || _state$service6 === void 0 || (_state$service6 = _state$service6.value) === null || _state$service6 === void 0 ? void 0 : _state$service6.length) > 0 && discountList.length > 0 && !discountList.some((discount) => discount.isSelected) && discountList.some((discount) => discount.isManualSelect);
		} catch (error) {
			console.error("判断警告状态失败:", error);
			return false;
		}
	}, [discountList, (_state$service7 = state.service) === null || _state$service7 === void 0 ? void 0 : _state$service7.value]);
	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 = () => {
		clearAllScanListenersTaskQueue();
		if (!hasCartItems) {
			Toast === null || Toast === void 0 || Toast.info(createToastContent(locales.getText("pisell2.clear-cart-modal.empty-cart-tip")));
			return;
		}
		dispatch({
			type: "setService",
			payload: { value: [] }
		});
		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(locales.getText("pisell2.action-buttons.clear-success")));
	};
	const handleClearAllAndReset = () => {
		var _window, _shopDiscount$clear;
		(_window = window) === null || _window === void 0 || (_window = _window.shopApi) === null || _window === void 0 || (_window = _window.bookingTicket) === null || _window === void 0 || _window.clearAllCart();
		clearAllScanListenersTaskQueue();
		dispatch({
			type: "setService",
			payload: { value: [] }
		});
		dispatch({
			type: "setAddons",
			payload: { value: [] }
		});
		selectCustomer(null);
		dispatch({
			type: "setDate",
			payload: {
				value: dayjs(),
				end_date: dayjs().add(1, "days")
			}
		});
		dispatch({
			type: "setPet",
			payload: {
				holders: [],
				value: {}
			}
		});
		dispatch({
			type: "setNotes",
			payload: {
				value: "",
				orderNote: ""
			}
		});
		dispatch({
			type: "setPaymentPaid",
			payload: { value: {} }
		});
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$clear = shopDiscount.clear) === null || _shopDiscount$clear === void 0 || _shopDiscount$clear.call(shopDiscount);
		setShowClearModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(locales.getText("pisell2.action-buttons.clear-success")));
	};
	const handleManuelOrder = () => {
		if (!hasCartItems) {
			Toast === null || Toast === void 0 || Toast.info(createToastContent(locales.getText("pisell2.action-buttons.no-items-to-adjust")));
			return;
		}
		setShowPriceAdjustModal(true);
	};
	useEffect(() => {
		var _state$service8, _state$addons3;
		if (((_state$service8 = state.service) === null || _state$service8 === void 0 || (_state$service8 = _state$service8.value) === null || _state$service8 === void 0 ? void 0 : _state$service8.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$service9 = state.service) === null || _state$service9 === void 0 ? void 0 : _state$service9.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(discountAmount || 0).toDecimalPlaces(2, Decimal.ROUND_DOWN).toString() }
		});
		setShowPriceAdjustModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(locales.getText("pisell2.action-buttons.price-adjusted-success")));
	};
	const handleCustomiseItem = () => {
		setShowCustomiseModal(true);
	};
	const handleGoodPassClick = () => {
		setShowVoucherModal(true);
	};
	const handleCustomiseItemSave = (data) => {
		var _state$service10;
		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: dayjs(),
						endDate: dayjs(),
						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$service10 = state.service) === null || _state$service10 === void 0 ? void 0 : _state$service10.value) || []],
				changeService: false
			}
		});
		setShowCustomiseModal(false);
		Toast === null || Toast === void 0 || Toast.success(createToastContent(locales.getText("pisell2.customise-item.save-success")));
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__action-buttons" }, /* @__PURE__ */ React.createElement(Button, {
		className: "action-button clear-button",
		icon: /* @__PURE__ */ React.createElement(Trash01, { size: 22 }),
		onClick: handleClear,
		type: "text",
		disabled: isDisabledEdit
	}), /* @__PURE__ */ React.createElement(Button, {
		className: "action-button customise-button",
		icon: /* @__PURE__ */ React.createElement(PlusCircle, { size: 22 }),
		onClick: handleCustomiseItem,
		type: "text",
		disabled: isDisabledEdit
	}, locales.getText("pisell2.action-buttons.customise-item")), /* @__PURE__ */ React.createElement(Button, {
		className: "action-button manuel-button",
		icon: /* @__PURE__ */ React.createElement(Calculator, { size: 22 }),
		onClick: handleManuelOrder,
		type: "text",
		disabled: isDisabledEdit
	}, locales.getText("pisell2.action-buttons.manuel-order")), /* @__PURE__ */ React.createElement("div", { className: "action-button-wrapper" }, /* @__PURE__ */ React.createElement(Button, {
		className: "action-button goodpass-button",
		icon: /* @__PURE__ */ React.createElement(Sale03, { size: 22 }),
		onClick: handleGoodPassClick,
		type: "text"
	}, locales.getText("pisell2.text.goodpass")), usedVouchersCount > 0 && /* @__PURE__ */ React.createElement("div", { className: "voucher-badge" }, usedVouchersCount), shouldShowWarning && /* @__PURE__ */ React.createElement("div", { className: "voucher-warning-icon" }, "!"))), /* @__PURE__ */ React.createElement(ClearCartModal, {
		visible: showClearModal,
		onCancel: () => setShowClearModal(false),
		onClearItemsOnly: handleClearItemsOnly,
		onClearAllAndReset: handleClearAllAndReset
	}), /* @__PURE__ */ React.createElement(DiscountKeyboard, {
		containerProps: {
			renderType: "modal",
			open: showPriceAdjustModal,
			onCancel: () => setShowPriceAdjustModal(false)
		},
		selectType: "dark",
		originalValue: currentTotalPrice,
		defaultValue: currentTotalPriceAfterDiscount,
		onEnter: handlePriceAdjustConfirm
	}), /* @__PURE__ */ React.createElement(CustomiseItemModal, {
		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.createElement(VoucherModal, {
		visible: showVoucherModal,
		onClose: () => setShowVoucherModal(false),
		state,
		dispatch,
		source
	}));
};
//#endregion
export { ActionButtons as default };
