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_utils = require("../../utils.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_utils$1 = require("../../info/clientVariant/utils.js");
const require_useActiveExecute = require("../../../ticketBooking/hooks/pisellos/useActiveExecute.js");
const require_useIsBooking4Shop = require("../../hooks/useIsBooking4Shop.js");
const require_utils$2 = require("./utils.js");
const require_useCustomer = require("../../../ticketBooking/hooks/pisellos/useCustomer.js");
const require_useShopDiscountModule = require("../../../ticketBooking/hooks/pisellos/useShopDiscountModule.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");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
let _pisell_icon_es_ChevronDown = require("@pisell/icon/es/ChevronDown");
_pisell_icon_es_ChevronDown = require_runtime.__toESM(_pisell_icon_es_ChevronDown);
require("./index.less");
//#region src/components/booking/components/voucher/index.tsx
const VoucherCard = (props) => {
	var _context$appHelper, _state$bookingDetail2, _state$client$value, _state$pet2, _state$service2;
	const context = require_useEngineContext.default();
	const { state, dispatch, source, isInModal = false } = props;
	const [showDetail, setShowDetail] = (0, react.useState)(isInModal ? true : false);
	const { pisellos } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const [code, setCode] = (0, react.useState)("");
	const [discountList, setDisCountList] = (0, react.useState)([]);
	const serviceValueRef = (0, react.useRef)(state.service.value);
	const addonsValueRef = (0, react.useRef)(state.addons.value);
	const isBooking4Shop = require_useIsBooking4Shop.useIsBooking4Shop(state);
	const shopDiscount = require_useShopDiscountModule.useShopDiscountModule();
	const { executeIfActive } = require_useActiveExecute.useActiveExecute();
	const holderChangedRef = (0, react.useRef)(false);
	const stateRef = (0, react.useRef)(state);
	stateRef.current = state;
	state.service;
	(0, react.useEffect)(() => {
		if (shopDiscount === null || shopDiscount === void 0 ? void 0 : shopDiscount.setOrderId) {
			var _shopDiscount$setOrde, _state$bookingDetail;
			(_shopDiscount$setOrde = shopDiscount.setOrderId) === null || _shopDiscount$setOrde === void 0 || _shopDiscount$setOrde.call(shopDiscount, ((_state$bookingDetail = state.bookingDetail) === null || _state$bookingDetail === void 0 ? void 0 : _state$bookingDetail.id) || state.bookingId);
		}
	}, [(_state$bookingDetail2 = state.bookingDetail) === null || _state$bookingDetail2 === void 0 ? void 0 : _state$bookingDetail2.id, state.bookingId]);
	const { selectCustomer } = require_useCustomer.useCustomer({});
	(0, ahooks.useDebounceEffect)(() => {
		if (isBooking4Shop) shopDiscount.setCustomer(state.client.value);
	}, [(_state$client$value = state.client.value) === null || _state$client$value === void 0 ? void 0 : _state$client$value.id, isBooking4Shop], { wait: 200 });
	(0, react.useEffect)(() => {
		if (isBooking4Shop && shopDiscount) shopDiscount.setProductList([...state.service.value, ...state.addons.value]);
	}, [
		state.service.value,
		state.addons.value,
		isBooking4Shop
	]);
	const serviceMemo = (0, react.useMemo)(() => {
		var _ref;
		return (_ref = state.service.value || []) === null || _ref === void 0 ? void 0 : _ref.map((value) => {
			var _value$_extend, _value$_extend2, _value$_extend3;
			return {
				booking_id: value.booking_id,
				id: value.id,
				price: value.price,
				total: value === null || value === void 0 || (_value$_extend = value._extend) === null || _value$_extend === void 0 ? void 0 : _value$_extend.total,
				discount_list: value.discount_list,
				origin_total: value === null || value === void 0 || (_value$_extend2 = value._extend) === null || _value$_extend2 === void 0 ? void 0 : _value$_extend2.origin_total,
				holder_id: value === null || value === void 0 || (_value$_extend3 = value._extend) === null || _value$_extend3 === void 0 ? void 0 : _value$_extend3.holder_id,
				quantity: value._extend.quantity,
				startDate: value._extend.startDate
			};
		});
	}, [state.service.value]);
	const serviceTotal = (0, react.useMemo)(() => {
		return serviceMemo.reduce((total, item) => {
			return total + (item.total || 0);
		}, 0);
	}, [serviceMemo]);
	const onScanWallPassCode = (0, ahooks.useMemoizedFn)((e) => {
		if (!e.detail.code) return;
		onScanCode(e.detail.code);
	});
	const onOriginExpectAmountWithoutDiscountChange = (0, ahooks.useMemoizedFn)((e) => {
		var _shopDiscount$setOrig;
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setOrig = shopDiscount.setOriginTotalAmount) === null || _shopDiscount$setOrig === void 0 || _shopDiscount$setOrig.call(shopDiscount, e.detail.originExpectAmountWithoutDiscount);
	});
	(0, react.useEffect)(() => {
		const wrappedOnScanWallPassCode = executeIfActive(onScanWallPassCode);
		window.addEventListener("onScanWallPassCode", wrappedOnScanWallPassCode);
		window.addEventListener("onOriginExpectAmountWithoutDiscountChange", onOriginExpectAmountWithoutDiscountChange);
		return () => {
			window.removeEventListener("onScanWallPassCode", wrappedOnScanWallPassCode);
			window.removeEventListener("onOriginExpectAmountWithoutDiscountChange", onOriginExpectAmountWithoutDiscountChange);
		};
	}, []);
	const addonsMemo = (0, react.useMemo)(() => {
		var _ref2;
		return (_ref2 = state.addons.value || []) === null || _ref2 === void 0 ? void 0 : _ref2.map((value) => {
			var _value$_extend4, _value$_extend5;
			return {
				booking_id: value.booking_id,
				id: value.id,
				_id: value._id,
				price: value.price,
				total: value === null || value === void 0 || (_value$_extend4 = value._extend) === null || _value$_extend4 === void 0 ? void 0 : _value$_extend4.total,
				discount_list: value.discount_list,
				_key: value._key,
				num: value === null || value === void 0 || (_value$_extend5 = value._extend) === null || _value$_extend5 === void 0 ? void 0 : _value$_extend5.quantity
			};
		});
	}, [state.addons.value]);
	const holdersMemo = (0, react.useMemo)(() => {
		if (isBooking4Shop) {
			var _state$pet, _shopDiscount$setHold;
			let list = [];
			if ((_state$pet = state.pet) === null || _state$pet === void 0 ? void 0 : _state$pet.value) {
				let entries = Object.entries(state.pet.value);
				if (entries.length === 1) list = entries[0][1];
			}
			shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setHold = shopDiscount.setHolders) === null || _shopDiscount$setHold === void 0 || _shopDiscount$setHold.call(shopDiscount, list);
			holderChangedRef.current = true;
			return list || [];
		}
	}, [(_state$pet2 = state.pet) === null || _state$pet2 === void 0 ? void 0 : _state$pet2.value, isBooking4Shop]);
	(0, react.useEffect)(() => {
		var _shopDiscount$setBook, _state$bookingConfig;
		console.log("update booking subject", state.bookingConfig);
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setBook = shopDiscount.setBookingSubject) === null || _shopDiscount$setBook === void 0 || _shopDiscount$setBook.call(shopDiscount, (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.config) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.basic) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.appointment_subject);
	}, [state.bookingConfig]);
	const disabled = (0, react.useMemo)(() => {
		var _state$bookingDetail3;
		if (((_state$bookingDetail3 = state.bookingDetail) === null || _state$bookingDetail3 === void 0 ? void 0 : _state$bookingDetail3.payment_status) === "paid" && [...addonsMemo, ...serviceMemo].every((item) => item.booking_id)) return true;
		return false;
	}, [
		state,
		addonsMemo,
		serviceMemo
	]);
	const { run } = (0, ahooks.useDebounceFn)(() => {
		var _state$service, _shopDiscount$getDisc;
		if (serviceValueRef.current === state.service.value && addonsValueRef.current === state.addons.value && !holderChangedRef.current || !((_state$service = state.service) === null || _state$service === void 0 || (_state$service = _state$service.value) === null || _state$service === void 0 ? void 0 : _state$service.length)) return;
		if (Array.isArray(shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$getDisc = shopDiscount.getDiscountList) === null || _shopDiscount$getDisc === void 0 ? void 0 : _shopDiscount$getDisc.call(shopDiscount)) && !(shopDiscount === null || shopDiscount === void 0 ? void 0 : shopDiscount.getDiscountList().length)) return;
		if (isBooking4Shop) {
			const val = shopDiscount.calcDiscount([...stateRef.current.service.value, ...stateRef.current.addons.value]);
			console.log("input: ", state.service.value);
			console.log("output: ", val);
			productListToValue(val.productList);
			holderChangedRef.current = false;
		}
	}, { wait: 1e3 });
	(0, react.useEffect)(() => {
		run();
	}, [
		JSON.stringify(serviceMemo),
		JSON.stringify(addonsMemo),
		JSON.stringify(holdersMemo),
		isBooking4Shop
	]);
	(0, react.useEffect)(() => {
		if (shopDiscount) {
			var _pisellos$effects;
			const wrappedHandler = executeIfActive(fn);
			pisellos === null || pisellos === void 0 || (_pisellos$effects = pisellos.effects) === null || _pisellos$effects === void 0 || _pisellos$effects.on("shopDiscount:onSelectedDiscountListChange", wrappedHandler);
			return () => {
				var _pisellos$effects2;
				pisellos === null || pisellos === void 0 || (_pisellos$effects2 = pisellos.effects) === null || _pisellos$effects2 === void 0 || _pisellos$effects2.off("shopDiscount:onSelectedDiscountListChange", wrappedHandler);
			};
		}
	}, []);
	const fn = (0, ahooks.useMemoizedFn)((result) => {
		var _result$productList;
		if (!(result === null || result === void 0 ? void 0 : result.productList) || (result === null || result === void 0 || (_result$productList = result.productList) === null || _result$productList === void 0 ? void 0 : _result$productList.some((item) => !item))) return;
		if (window.isPaymentModalPluginOpen && !(state === null || state === void 0 ? void 0 : state.isEditTicketMode)) return;
		productListToValue(result.productList);
	});
	(0, react.useEffect)(() => {
		if (!isBooking4Shop || !shopDiscount) return;
		const onScanCustomerChange = (customer) => {
			const clientVariantClose = require_utils$1.getClientVariantClose();
			if (clientVariantClose) clientVariantClose();
			selectCustomer(customer);
		};
		const onDiscountListChange = (discount) => {
			setDisCountList(discount);
		};
		const wrappedOnScanCustomerChangeHandler = executeIfActive(onScanCustomerChange);
		const wrappedOnDiscountListChangeHandler = executeIfActive(onDiscountListChange);
		const wrappedFn = executeIfActive(fn);
		shopDiscount.effectsOn("onScanCustomerChange", wrappedOnScanCustomerChangeHandler);
		shopDiscount.effectsOn("onLoadPrepareCalcResult", wrappedFn);
		shopDiscount.effectsOn("onDiscountListChange", wrappedOnDiscountListChangeHandler);
		return () => {
			shopDiscount.clear();
			shopDiscount.effectsOff("onScanCustomerChange", wrappedOnScanCustomerChangeHandler);
			shopDiscount.effectsOff("onLoadPrepareCalcResult", wrappedFn);
			shopDiscount.effectsOff("onDiscountListChange", wrappedOnDiscountListChangeHandler);
		};
	}, [
		state.bookingId,
		isBooking4Shop,
		fn
	]);
	const productListToValue = (0, ahooks.useMemoizedFn)((list, edit) => {
		var _props$state;
		const { serviceList, addonsList } = require_utils$2.getServiceAddons(list);
		if (serviceList.reduce((total, item) => {
			return total + (item._extend.total || 0);
		}, 0) !== serviceTotal) edit = true;
		serviceValueRef.current = serviceList;
		addonsValueRef.current = addonsList;
		let other = {};
		if (edit) other = { edit: true };
		dispatch({
			type: "setService",
			payload: require_objectSpread2._objectSpread2({ value: serviceList }, other)
		});
		if (!(props === null || props === void 0 || (_props$state = props.state) === null || _props$state === void 0 ? void 0 : _props$state.isBookingTicket2)) setTimeout(() => {
			dispatch({
				type: "setAddons",
				payload: require_objectSpread2._objectSpread2({ value: addonsList }, other)
			});
		});
	});
	const onScanCode = function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (codeParam) {
			var _state$client$value2;
			const customerId = (_state$client$value2 = state.client.value) === null || _state$client$value2 === void 0 ? void 0 : _state$client$value2.id;
			const val = yield shopDiscount.scanCode(codeParam || code, customerId);
			console.log(val);
			if (val === null || val === void 0 ? void 0 : val.isAvailable) {
				productListToValue(val.productList, true);
				setCode("");
			} else (0, _pisell_materials.PisellToast)({ content: require_utils.showDiscountScanFailMessage(val, "goodpass", _pisell_utils.locales) });
		});
		return function onScanCode(_x) {
			return _ref3.apply(this, arguments);
		};
	}();
	const availableData = (0, react.useMemo)(() => {
		if (!isBooking4Shop) return [];
		return discountList.filter((item) => !!item.isAvailable).map((discount) => {
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, {
				isDisabled: discount.isDisabled || discount.isDisabledForProductUsed || disabled,
				savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
			});
		});
	}, [
		discountList,
		isBooking4Shop,
		disabled
	]);
	if (!isBooking4Shop) return null;
	const mixedSort = (val) => {
		return [...val].sort((a, b) => {
			return Number(b === null || b === void 0 ? void 0 : b.isSelected) - Number(a === null || a === void 0 ? void 0 : a.isSelected);
		});
	};
	return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-footer-voucher-container" }, /* @__PURE__ */ react.default.createElement("div", { className: "voucher-title" }, /* @__PURE__ */ react.default.createElement("span", { className: "voucher-title-left" }, _pisell_utils.locales.getText("pisell2.text.goodpass")), !isInModal && /* @__PURE__ */ react.default.createElement("span", {
		className: "voucher-title-right",
		onClick: () => {
			setShowDetail(!showDetail);
		}
	}, _pisell_utils.locales.getText("pisell2.text.details"), " ", /* @__PURE__ */ react.default.createElement(_pisell_icon_es_ChevronDown.default, { className: (0, classnames.default)("voucher-right-icon", { show: showDetail }) }))), /* @__PURE__ */ react.default.createElement("div", { className: (0, classnames.default)("voucher-detail", { show: showDetail || isInModal }) }, (availableData === null || availableData === void 0 ? void 0 : availableData.length) > 0 ? /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellGoodPassCard, {
		style: { width: "100%" },
		isInModal: isInModal || false,
		dataSource: ((_state$service2 = state.service) === null || _state$service2 === void 0 || (_state$service2 = _state$service2.value) === null || _state$service2 === void 0 ? void 0 : _state$service2.length) ? availableData : [],
		mixedSort,
		onChange: (val) => {
			productListToValue(shopDiscount.setDiscountSelected({
				discountId: val.id,
				isSelected: val.isSelected
			}).productList, true);
		}
	}) : null, /* @__PURE__ */ react.default.createElement("div", { className: "voucher-code-input-wrapper" }, /* @__PURE__ */ react.default.createElement("div", { className: "voucher-code-input" }, /* @__PURE__ */ react.default.createElement("div", { style: { whiteSpace: "nowrap" } }, _pisell_utils.locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellInput, {
		value: code,
		onChange: (e) => {
			var _e$target;
			setCode((_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.value);
		},
		size: "small",
		allowClear: true,
		placeholder: _pisell_utils.locales.getText("pisell2.text.goodpass.enter-code")
	})), /* @__PURE__ */ react.default.createElement(antd.Button, {
		size: "small",
		onClick: () => onScanCode(),
		disabled: !code
	}, _pisell_utils.locales.getText("pisell2.text.apply")))));
};
//#endregion
exports.default = VoucherCard;
