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 { getClientVariantClose } from "../../info/clientVariant/utils.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { useShopDiscountModule } from "../../../ticketBooking/hooks/pisellos/useShopDiscountModule.js";
import { useActiveExecute } from "../../../ticketBooking/hooks/pisellos/useActiveExecute.js";
import { useCustomer } from "../../../ticketBooking/hooks/pisellos/useCustomer.js";
import { useIsBooking4Shop } from "../../hooks/useIsBooking4Shop.js";
import { getServiceAddons, hasEveryBookingId } from "./utils.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import { PisellGoodPassCard, PisellInput, PisellToast } from "@pisell/materials";
import classNames from "classnames";
import { useDebounceEffect, useDebounceFn, useMemoizedFn } from "ahooks";
import ChevronDown from "@pisell/icon/es/ChevronDown";
import "./index.less";
//#region src/components/booking/components/voucher/index.tsx
const VoucherCard = (props) => {
	var _context$appHelper, _state$bookingDetail2, _state$client$value, _state$pet2, _state$service3;
	const context = useEngineContext();
	const { state, dispatch, source, isInModal = false } = props;
	const [showDetail, setShowDetail] = useState(isInModal ? true : false);
	const { pisellos } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const [code, setCode] = useState("");
	const [discountList, setDisCountList] = useState([]);
	const serviceValueRef = useRef(state.service.value);
	const addonsValueRef = useRef(state.addons.value);
	const isBooking4Shop = useIsBooking4Shop(state);
	const shopDiscount = useShopDiscountModule();
	const { executeIfActive } = useActiveExecute();
	const holderChangedRef = useRef(false);
	const stateRef = useRef(state);
	stateRef.current = state;
	state.service;
	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 } = 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: [] }) })) }
		});
	}) });
	useDebounceEffect(() => {
		if (isBooking4Shop) {
			var _shopDiscount$setCust;
			shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setCust = shopDiscount.setCustomer) === null || _shopDiscount$setCust === void 0 || _shopDiscount$setCust.call(shopDiscount, state.client.value);
		}
	}, [(_state$client$value = state.client.value) === null || _state$client$value === void 0 ? void 0 : _state$client$value.id, isBooking4Shop], { wait: 200 });
	useEffect(() => {
		if (isBooking4Shop && shopDiscount) {
			var _shopDiscount$setProd;
			shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$setProd = shopDiscount.setProductList) === null || _shopDiscount$setProd === void 0 || _shopDiscount$setProd.call(shopDiscount, [...state.service.value, ...state.addons.value]);
		}
	}, [
		state.service.value,
		state.addons.value,
		isBooking4Shop
	]);
	const serviceMemo = 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 {
				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,
				quantity: value._extend.quantity,
				startDate: value._extend.startDate,
				holder_id: value === null || value === void 0 || (_value$_extend3 = value._extend) === null || _value$_extend3 === void 0 ? void 0 : _value$_extend3.holder_id
			};
		});
	}, [state.service.value]);
	const serviceTotal = useMemo(() => {
		return serviceMemo.reduce((total, item) => {
			return total + (item.total || 0);
		}, 0);
	}, [serviceMemo]);
	const onScanWallPassCode = useMemoizedFn((e) => {
		if (!e.detail.code) return;
		onScanCode(e.detail.code);
	});
	const onOriginExpectAmountWithoutDiscountChange = 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);
	});
	useEffect(() => {
		const wrappedOnScanWallPassCode = executeIfActive(onScanWallPassCode);
		window.addEventListener("onScanWallPassCode", wrappedOnScanWallPassCode);
		window.addEventListener("onOriginExpectAmountWithoutDiscountChange", onOriginExpectAmountWithoutDiscountChange);
		return () => {
			window.removeEventListener("onScanWallPassCode", wrappedOnScanWallPassCode);
			window.removeEventListener("onOriginExpectAmountWithoutDiscountChange", onOriginExpectAmountWithoutDiscountChange);
		};
	}, []);
	const addonsMemo = 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 = 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]);
	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 = useMemo(() => {
		var _state$bookingDetail3;
		if (["paid", "partially_paid"].includes((_state$bookingDetail3 = state.bookingDetail) === null || _state$bookingDetail3 === void 0 ? void 0 : _state$bookingDetail3.payment_status) && hasEveryBookingId([...state.addons.value || [], ...state.service.value || []])) return true;
		return false;
	}, [
		state,
		addonsMemo,
		serviceMemo
	]);
	const { run } = useDebounceFn(() => {
		var _state$service2, _shopDiscount$getDisc;
		if (serviceValueRef.current === state.service.value && addonsValueRef.current === state.addons.value && !holderChangedRef.current || !((_state$service2 = state.service) === null || _state$service2 === void 0 || (_state$service2 = _state$service2.value) === null || _state$service2 === void 0 ? void 0 : _state$service2.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 });
	useEffect(() => {
		run();
	}, [
		JSON.stringify(serviceMemo),
		JSON.stringify(addonsMemo),
		JSON.stringify(holdersMemo),
		isBooking4Shop
	]);
	useEffect(() => {
		if (shopDiscount) {
			const wrappedHandler = executeIfActive(fn);
			shopDiscount === null || shopDiscount === void 0 || shopDiscount.effectsOn("onSelectedDiscountListChange", wrappedHandler);
			return () => {
				shopDiscount === null || shopDiscount === void 0 || shopDiscount.effectsOff("onSelectedDiscountListChange", wrappedHandler);
			};
		}
	}, []);
	const fn = 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;
		productListToValue(result.productList);
	});
	useEffect(() => {
		if (!isBooking4Shop || !shopDiscount) return;
		const onScanCustomerChange = (customer) => {
			const clientVariantClose = 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 = useMemoizedFn((list, edit) => {
		var _props$state;
		const { serviceList, addonsList } = 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: _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: _objectSpread2({ value: addonsList }, other)
			});
		});
	});
	const onScanCode = function() {
		var _ref3 = _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 {
				const content = { time_limit: locales.getText("pisell2.text.goodpass.code-invalid-expired") };
				PisellToast({ content: val.type === "server" ? locales.getText("pisell2.text.goodpass.code-invalid") : content[val === null || val === void 0 ? void 0 : val.unavailableReason] || locales.getText("pisell2.text.goodpass.code-invalid-cart") });
			}
		});
		return function onScanCode(_x) {
			return _ref3.apply(this, arguments);
		};
	}();
	const availableData = useMemo(() => {
		if (!isBooking4Shop) return [];
		return discountList.filter((item) => !!item.isAvailable).map((discount) => {
			return _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.createElement("div", { className: "pisell-lowcode__booking-footer-voucher-container" }, /* @__PURE__ */ React.createElement("div", { className: "voucher-title" }, /* @__PURE__ */ React.createElement("span", { className: "voucher-title-left" }, locales.getText("pisell2.text.goodpass")), !isInModal && /* @__PURE__ */ React.createElement("span", {
		className: "voucher-title-right",
		onClick: () => {
			setShowDetail(!showDetail);
		}
	}, locales.getText("pisell2.text.details"), " ", /* @__PURE__ */ React.createElement(ChevronDown, { className: classNames("voucher-right-icon", { show: showDetail }) }))), /* @__PURE__ */ React.createElement("div", { className: classNames("voucher-detail", { show: showDetail || isInModal }) }, (availableData === null || availableData === void 0 ? void 0 : availableData.length) > 0 ? /* @__PURE__ */ React.createElement(PisellGoodPassCard, {
		style: { width: "100%" },
		isInModal: isInModal || false,
		dataSource: ((_state$service3 = state.service) === null || _state$service3 === void 0 || (_state$service3 = _state$service3.value) === null || _state$service3 === void 0 ? void 0 : _state$service3.length) ? availableData : [],
		mixedSort,
		onChange: (val) => {
			productListToValue(shopDiscount.setDiscountSelected({
				discountId: val.id,
				isSelected: val.isSelected
			}).productList, true);
		}
	}) : null, /* @__PURE__ */ React.createElement("div", { className: "voucher-code-input-wrapper" }, /* @__PURE__ */ React.createElement("div", { className: "voucher-code-input" }, /* @__PURE__ */ React.createElement("div", { style: { whiteSpace: "nowrap" } }, locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ React.createElement(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: locales.getText("pisell2.text.goodpass.enter-code")
	})), /* @__PURE__ */ React.createElement(Button, {
		size: "small",
		onClick: () => onScanCode(),
		disabled: !code
	}, locales.getText("pisell2.text.apply")))));
};
//#endregion
export { VoucherCard as default };
