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("../../booking/utils.js");
const require_utils$1 = require("../components/WalletPassModule/utils.js");
const require_usePaymentLogger = require("./usePaymentLogger.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
//#region src/components/checkout/hooks/useWalletPass.ts
function getBaseSalesDiscountKey(discount) {
	var _discount$discount;
	return (discount === null || discount === void 0 || (_discount$discount = discount.discount) === null || _discount$discount === void 0 ? void 0 : _discount$discount.resource_id) || (discount === null || discount === void 0 ? void 0 : discount.id);
}
function isBaseSalesEditOrderProduct(product) {
	return !!(product === null || product === void 0 ? void 0 : product.order_detail_id);
}
function getBaseSalesHistoryDiscountIdSet(products = []) {
	const historyDiscountIds = /* @__PURE__ */ new Set();
	products.forEach((product) => {
		if (!isBaseSalesEditOrderProduct(product)) return;
		(product.discount_list || []).forEach((discount) => {
			const discountId = getBaseSalesDiscountKey(discount);
			if (!discountId || !["good_pass", "discount_card"].includes(discount.type)) return;
			historyDiscountIds.add(String(discountId));
		});
	});
	return historyDiscountIds;
}
function normalizeBaseSalesDiscountHistory(discountList = [], products = [], fallbackHistoryDiscountIds) {
	const productHistoryDiscountIds = getBaseSalesHistoryDiscountIdSet(products);
	const historyDiscountIds = productHistoryDiscountIds.size > 0 ? productHistoryDiscountIds : fallbackHistoryDiscountIds || productHistoryDiscountIds;
	return discountList.map((discount) => {
		const discountId = (discount === null || discount === void 0 ? void 0 : discount.id) || getBaseSalesDiscountKey(discount);
		if (discountId && historyDiscountIds.has(String(discountId))) return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, {
			isEditMode: true,
			isSelected: true
		});
		if (!(discount === null || discount === void 0 ? void 0 : discount.isEditMode)) return discount;
		return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, {
			isEditMode: false,
			isSelected: false
		});
	});
}
function normalizeBaseSalesCurrentDiscountList(baseSales, products = [], fallbackHistoryDiscountIds) {
	var _baseSales$getDiscoun;
	return normalizeBaseSalesDiscountHistory((baseSales === null || baseSales === void 0 || (_baseSales$getDiscoun = baseSales.getDiscountList) === null || _baseSales$getDiscoun === void 0 ? void 0 : _baseSales$getDiscoun.call(baseSales)) || [], products, fallbackHistoryDiscountIds);
}
function mergeBaseSalesHistoryDiscounts(discountList = [], products = []) {
	const historyDiscounts = [];
	products.forEach((product) => {
		const isEditMode = isBaseSalesEditOrderProduct(product);
		(product.discount_list || []).forEach((discount) => {
			var _discount$metadata, _discount$discount2, _discount$discount3, _discount$discount4;
			const discountId = getBaseSalesDiscountKey(discount);
			if (!discountId || !["good_pass", "discount_card"].includes(discount.type)) return;
			const quantity = product.quantity || product.num || product.product_quantity || 1;
			const savedAmount = Number(discount.amount || 0) * Number(quantity || 1) + Number((discount === null || discount === void 0 || (_discount$metadata = discount.metadata) === null || _discount$metadata === void 0 ? void 0 : _discount$metadata.product_discount_difference) || 0);
			const existingIndex = historyDiscounts.findIndex((item) => item.id === discountId);
			if (existingIndex !== -1) {
				historyDiscounts[existingIndex] = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, historyDiscounts[existingIndex]), {}, {
					amount: Number(historyDiscounts[existingIndex].amount || 0) + Number(discount.amount || 0),
					savedAmount: Number(historyDiscounts[existingIndex].savedAmount || 0) + savedAmount
				});
				return;
			}
			historyDiscounts.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, {
				id: discountId,
				tag: discount.tag || discount.type,
				name: discount.name || ((_discount$discount2 = discount.discount) === null || _discount$discount2 === void 0 || (_discount$discount2 = _discount$discount2.title) === null || _discount$discount2 === void 0 ? void 0 : _discount$discount2.auto),
				format_title: ((_discount$discount3 = discount.discount) === null || _discount$discount3 === void 0 ? void 0 : _discount$discount3.title) || discount.format_title,
				isEditMode,
				isAvailable: true,
				isDisabled: true,
				isSelected: true,
				limited_relation_product_data: {},
				savedAmount,
				product_id: ((_discount$discount4 = discount.discount) === null || _discount$discount4 === void 0 ? void 0 : _discount$discount4.product_id) || discount.product_id
			}));
		});
	});
	const historyIds = new Set(historyDiscounts.map((discount) => discount.id));
	return [...historyDiscounts, ...discountList.filter((discount) => !historyIds.has(discount.id))];
}
/**
* 自定义Hook：使用WalletPass功能
*/
const useWalletPass = (props) => {
	const { onSelectChange, customAmount, clientId, totalAmount } = props;
	const logger = require_usePaymentLogger.default();
	const [walletRecommendList, setWalletRecommendList] = (0, react.useState)([]);
	const [userIdentificationCodes, setUserIdentificationCodes] = (0, react.useState)([]);
	const [transformList, setTransformList] = (0, react.useState)([]);
	const [noApplicableVoucher, setNoApplicableVoucher] = (0, react.useState)([]);
	const initialOrderedDataRef = (0, react.useRef)([]);
	const initialDiscountOrderRef = (0, react.useRef)([]);
	const confirmedEditAmountIdsRef = (0, react.useRef)([]);
	const prepareDiscountKeyRef = (0, react.useRef)("");
	const prepareDiscountPromiseRef = (0, react.useRef)(null);
	const walletInitKeyRef = (0, react.useRef)("");
	const walletInitPromiseRef = (0, react.useRef)(null);
	const historyDiscountIdsRef = (0, react.useRef)(/* @__PURE__ */ new Set());
	const historyDiscountOrderKeyRef = (0, react.useRef)("");
	const [searchIdentificationCodeList, setSearchIdentificationCodeList] = (0, react.useState)([]);
	const [orderInfo, setOrderInfo] = (0, react.useState)({});
	const [selectedWallet, setSelectedWallet] = (0, react.useState)([]);
	const selectedWalletRef = (0, react.useRef)([]);
	const [selectedVoucherIds, setSelectedVoucherIds] = (0, react.useState)([]);
	const [disabledWalletData, setDisabledWalletData] = (0, react.useState)([]);
	const notSetWalletSelectRef = (0, react.useRef)(false);
	const preserveManualWalletSelectionRef = (0, react.useRef)(false);
	const showBestToastRef = (0, react.useRef)(false);
	const [products, setProducts] = (0, react.useState)([]);
	const selectedWalletIds = (0, react.useMemo)(() => {
		return selectedWallet.map((item) => item.id);
	}, [selectedWallet]);
	const Toast = (0, _pisell_materials.useToast)();
	const [loading, setLoading] = (0, react.useState)(false);
	const [error, setError] = (0, react.useState)(null);
	const [discountList, setDiscountList] = (0, react.useState)([]);
	const baseSales = props.baseSales;
	const paymentModule = baseSales === null || baseSales === void 0 ? void 0 : baseSales.payment;
	const walletApi = paymentModule === null || paymentModule === void 0 ? void 0 : paymentModule.wallet;
	const getBaseSalesCustomerId = (0, ahooks.useMemoizedFn)(() => {
		var _baseSales$getTempOrd, _baseSales$getOrderSn, _tempOrder$_extend, _baseSales$getOrderSn2;
		const tempOrder = (baseSales === null || baseSales === void 0 || (_baseSales$getTempOrd = baseSales.getTempOrder) === null || _baseSales$getTempOrd === void 0 ? void 0 : _baseSales$getTempOrd.call(baseSales)) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderSn = baseSales.getOrderSnapshot) === null || _baseSales$getOrderSn === void 0 || (_baseSales$getOrderSn = _baseSales$getOrderSn.call(baseSales)) === null || _baseSales$getOrderSn === void 0 ? void 0 : _baseSales$getOrderSn.tempOrder) || {};
		const customerSnapshot = (tempOrder === null || tempOrder === void 0 || (_tempOrder$_extend = tempOrder._extend) === null || _tempOrder$_extend === void 0 ? void 0 : _tempOrder$_extend.customerSnapshot) || (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.customer) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderSn2 = baseSales.getOrderSnapshot) === null || _baseSales$getOrderSn2 === void 0 || (_baseSales$getOrderSn2 = _baseSales$getOrderSn2.call(baseSales)) === null || _baseSales$getOrderSn2 === void 0 ? void 0 : _baseSales$getOrderSn2.customer) || {};
		return clientId || tempOrder.customer_id || customerSnapshot.id || customerSnapshot.customer_id;
	});
	const getWalletCalculationProducts = (0, ahooks.useMemoizedFn)(() => {
		var _baseSales$getOrderPr, _baseSales$getTempOrd2, _baseSales$getOrderSn3;
		if (products.length > 0) return products;
		const baseSalesProducts = (baseSales === null || baseSales === void 0 || (_baseSales$getOrderPr = baseSales.getOrderProducts) === null || _baseSales$getOrderPr === void 0 ? void 0 : _baseSales$getOrderPr.call(baseSales)) || [];
		if (baseSalesProducts.length > 0) return baseSalesProducts;
		return (baseSales === null || baseSales === void 0 || (_baseSales$getTempOrd2 = baseSales.getTempOrder) === null || _baseSales$getTempOrd2 === void 0 || (_baseSales$getTempOrd2 = _baseSales$getTempOrd2.call(baseSales)) === null || _baseSales$getTempOrd2 === void 0 ? void 0 : _baseSales$getTempOrd2.products) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderSn3 = baseSales.getOrderSnapshot) === null || _baseSales$getOrderSn3 === void 0 || (_baseSales$getOrderSn3 = _baseSales$getOrderSn3.call(baseSales)) === null || _baseSales$getOrderSn3 === void 0 || (_baseSales$getOrderSn3 = _baseSales$getOrderSn3.tempOrder) === null || _baseSales$getOrderSn3 === void 0 ? void 0 : _baseSales$getOrderSn3.products) || [];
	});
	const prepareBaseSalesDiscounts = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		var _baseSales$getTempOrd3, _baseSales$getOrderSn4, _baseSales$getOrderPr2, _baseSales$getOrderId, _baseSales$getOrderId2;
		const tempOrder = (baseSales === null || baseSales === void 0 || (_baseSales$getTempOrd3 = baseSales.getTempOrder) === null || _baseSales$getTempOrd3 === void 0 ? void 0 : _baseSales$getTempOrd3.call(baseSales)) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderSn4 = baseSales.getOrderSnapshot) === null || _baseSales$getOrderSn4 === void 0 || (_baseSales$getOrderSn4 = _baseSales$getOrderSn4.call(baseSales)) === null || _baseSales$getOrderSn4 === void 0 ? void 0 : _baseSales$getOrderSn4.tempOrder);
		const products = (baseSales === null || baseSales === void 0 || (_baseSales$getOrderPr2 = baseSales.getOrderProducts) === null || _baseSales$getOrderPr2 === void 0 ? void 0 : _baseSales$getOrderPr2.call(baseSales)) || (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.products) || [];
		const customerId = Number(getBaseSalesCustomerId() || 0);
		if (!baseSales) return;
		const currentHistoryDiscountIds = getBaseSalesHistoryDiscountIdSet(products);
		const historyOrderKey = String((tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id) || ((_baseSales$getOrderId = baseSales.getOrderIdentity) === null || _baseSales$getOrderId === void 0 || (_baseSales$getOrderId = _baseSales$getOrderId.call(baseSales)) === null || _baseSales$getOrderId === void 0 ? void 0 : _baseSales$getOrderId.orderId) || "");
		if (historyDiscountOrderKeyRef.current !== historyOrderKey) {
			historyDiscountOrderKeyRef.current = historyOrderKey;
			historyDiscountIdsRef.current = /* @__PURE__ */ new Set();
		}
		if (currentHistoryDiscountIds.size > 0 && historyDiscountIdsRef.current.size === 0) historyDiscountIdsRef.current = currentHistoryDiscountIds;
		const prepareKey = JSON.stringify({
			orderId: (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id) || ((_baseSales$getOrderId2 = baseSales.getOrderIdentity) === null || _baseSales$getOrderId2 === void 0 || (_baseSales$getOrderId2 = _baseSales$getOrderId2.call(baseSales)) === null || _baseSales$getOrderId2 === void 0 ? void 0 : _baseSales$getOrderId2.orderId),
			customerId,
			productDiscounts: products.map((product) => ({
				productId: product.product_id || product.id,
				discounts: (product.discount_list || []).map((discount) => ({
					id: getBaseSalesDiscountKey(discount),
					amount: discount.amount,
					type: discount.type
				}))
			}))
		});
		if (prepareDiscountKeyRef.current === prepareKey && discountList.length > 0) return;
		if (prepareDiscountPromiseRef.current && prepareDiscountKeyRef.current === prepareKey) return prepareDiscountPromiseRef.current;
		prepareDiscountKeyRef.current = prepareKey;
		const loadDiscountConfigFromBaseSales = function() {
			var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
				var _baseSales$store, _baseSales$getOrderId3, _orderModule$getDisco2, _orderModule$store, _orderModule$store$se, _orderModule$getOrder;
				if (typeof (baseSales === null || baseSales === void 0 ? void 0 : baseSales.loadDiscountConfig) === "function") {
					const result = yield baseSales.loadDiscountConfig({
						customerId,
						action: (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id) ? "edit" : "create"
					});
					return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, result), {}, { discountList: normalizeBaseSalesDiscountHistory((result === null || result === void 0 ? void 0 : result.discountList) || [], products, historyDiscountIdsRef.current) });
				}
				const orderModule = baseSales === null || baseSales === void 0 || (_baseSales$store = baseSales.store) === null || _baseSales$store === void 0 ? void 0 : _baseSales$store.order;
				if (!(orderModule === null || orderModule === void 0 ? void 0 : orderModule.loadDiscountConfig)) {
					var _orderModule$getDisco, _baseSales$getDiscoun2;
					return {
						productList: products,
						discountList: mergeBaseSalesHistoryDiscounts((orderModule === null || orderModule === void 0 || (_orderModule$getDisco = orderModule.getDiscountList) === null || _orderModule$getDisco === void 0 ? void 0 : _orderModule$getDisco.call(orderModule)) || (baseSales === null || baseSales === void 0 || (_baseSales$getDiscoun2 = baseSales.getDiscountList) === null || _baseSales$getDiscoun2 === void 0 ? void 0 : _baseSales$getDiscoun2.call(baseSales)) || [], products)
					};
				}
				const discountList = mergeBaseSalesHistoryDiscounts((yield orderModule.loadDiscountConfig({
					customerId,
					action: (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id) ? "edit" : "create",
					orderId: Number((tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.order_id) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderId3 = baseSales.getOrderIdentity) === null || _baseSales$getOrderId3 === void 0 || (_baseSales$getOrderId3 = _baseSales$getOrderId3.call(baseSales)) === null || _baseSales$getOrderId3 === void 0 ? void 0 : _baseSales$getOrderId3.orderId)) || void 0,
					apply: false
				})) || ((_orderModule$getDisco2 = orderModule.getDiscountList) === null || _orderModule$getDisco2 === void 0 ? void 0 : _orderModule$getDisco2.call(orderModule)) || [], products);
				yield orderModule === null || orderModule === void 0 || (_orderModule$store = orderModule.store) === null || _orderModule$store === void 0 || (_orderModule$store = _orderModule$store.discount) === null || _orderModule$store === void 0 || (_orderModule$store$se = _orderModule$store.setDiscountList) === null || _orderModule$store$se === void 0 ? void 0 : _orderModule$store$se.call(_orderModule$store, discountList);
				return {
					productList: ((_orderModule$getOrder = orderModule.getOrderProducts) === null || _orderModule$getOrder === void 0 ? void 0 : _orderModule$getOrder.call(orderModule)) || products,
					discountList
				};
			});
			return function loadDiscountConfigFromBaseSales() {
				return _ref.apply(this, arguments);
			};
		}();
		const prepareTask = require_asyncToGenerator._asyncToGenerator(function* () {
			const result = yield loadDiscountConfigFromBaseSales();
			const sortedDiscountList = sortDiscountListWithInitialOrder((result === null || result === void 0 ? void 0 : result.discountList) || normalizeBaseSalesCurrentDiscountList(baseSales, products, historyDiscountIdsRef.current));
			initialDiscountOrderRef.current = sortedDiscountList;
			setDiscountList(sortedDiscountList);
		})();
		prepareDiscountPromiseRef.current = prepareTask;
		try {
			return yield prepareTask;
		} finally {
			if (prepareDiscountPromiseRef.current === prepareTask) prepareDiscountPromiseRef.current = null;
		}
	}));
	const walletPassEvaluator = (0, react.useMemo)(() => {
		var _paymentModule$window, _paymentModule$window2;
		return paymentModule === null || paymentModule === void 0 || (_paymentModule$window = paymentModule.window) === null || _paymentModule$window === void 0 || (_paymentModule$window2 = _paymentModule$window.getWalletPassEvaluator) === null || _paymentModule$window2 === void 0 ? void 0 : _paymentModule$window2.call(_paymentModule$window);
	}, [paymentModule]);
	const setWalletSelect = (0, ahooks.useMemoizedFn)((data) => {
		setSelectedWallet(data);
		selectedWalletRef.current = data;
	});
	const getSelectedWalletDeductionAmount = (0, ahooks.useMemoizedFn)(() => {
		return selectedWalletRef.current.reduce((sum, item) => {
			var _ref2, _ref3, _ref4, _ref5, _item$actualDeduction;
			const amount = Number((_ref2 = (_ref3 = (_ref4 = (_ref5 = (_item$actualDeduction = item === null || item === void 0 ? void 0 : item.actualDeduction) !== null && _item$actualDeduction !== void 0 ? _item$actualDeduction : item === null || item === void 0 ? void 0 : item._available_max_amount) !== null && _ref5 !== void 0 ? _ref5 : item === null || item === void 0 ? void 0 : item.available_max_amount) !== null && _ref4 !== void 0 ? _ref4 : item === null || item === void 0 ? void 0 : item.recommended_usage_amount) !== null && _ref3 !== void 0 ? _ref3 : item === null || item === void 0 ? void 0 : item.amount) !== null && _ref2 !== void 0 ? _ref2 : 0);
			return sum + (Number.isFinite(amount) ? amount : 0);
		}, 0);
	});
	const getManualEditAmountMap = (0, ahooks.useMemoizedFn)(() => {
		const manualEditAmountMap = /* @__PURE__ */ new Map();
		const collectManualAmount = (item) => {
			if (typeof (item === null || item === void 0 ? void 0 : item.edit_current_amount) !== "number") return;
			manualEditAmountMap.set(item.id, item.edit_current_amount);
		};
		[
			selectedWalletRef.current,
			selectedWallet,
			transformList,
			walletRecommendList,
			userIdentificationCodes,
			searchIdentificationCodeList
		].forEach((list) => {
			(list || []).forEach(collectManualAmount);
		});
		return manualEditAmountMap;
	});
	const mergeManualEditAmount = (0, ahooks.useMemoizedFn)((list = []) => {
		const manualEditAmountMap = getManualEditAmountMap();
		if (!manualEditAmountMap.size) return list;
		return list.map((item) => {
			if (!manualEditAmountMap.has(item.id)) return item;
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, { edit_current_amount: manualEditAmountMap.get(item.id) });
		});
	});
	const mergeSelectedWalletAmount = (0, ahooks.useMemoizedFn)((list = []) => {
		const selectedWalletAmountMap = /* @__PURE__ */ new Map();
		selectedWalletRef.current.forEach((item) => {
			if (!selectedVoucherIds.includes(item.id)) return;
			selectedWalletAmountMap.set(item.id, {
				actualDeduction: item.actualDeduction,
				_available_max_amount: item._available_max_amount,
				recommended_usage_amount: item.recommended_usage_amount,
				recommended_usage_par_value: item.recommended_usage_par_value,
				available_max_amount: item.available_max_amount
			});
		});
		if (!selectedWalletAmountMap.size) return list;
		return list.map((item) => {
			const selectedAmount = selectedWalletAmountMap.get(item.id);
			if (!selectedAmount) return item;
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), selectedAmount);
		});
	});
	(0, react.useEffect)(() => {
		if (require_utils.isWalkIn(clientId) && searchIdentificationCodeList.length === 0) {
			if (!baseSales) {
				setUserIdentificationCodes([]);
				setWalletRecommendList([]);
				setDiscountList([]);
			}
		}
	}, [clientId]);
	const availableDiscountList = (0, react.useMemo)(() => {
		return require_utils$1.formatDiscountWalletData(discountList.filter((item) => !!item.isAvailable).map((discount) => {
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, discount), {}, {
				isDisabled: discount.isDisabled || discount.isDisabledForProductUsed,
				savedAmount: discount.savedAmount || 0
			});
		}));
	}, [discountList]);
	const selectedDiscountList = (0, react.useMemo)(() => {
		return availableDiscountList.filter((item) => item.isSelected && !item.isEditMode).map((item) => item.id);
	}, [availableDiscountList]);
	const mergeDataWithInitialOrder = (0, ahooks.useMemoizedFn)((newData) => {
		if (initialOrderedDataRef.current.length === 0) return newData;
		const newDataMap = new Map(newData.map((item) => [item.id, item]));
		const orderedResult = [];
		const addedIds = /* @__PURE__ */ new Set();
		if (searchIdentificationCodeList.length > 0) {
			const reversedSearchOrder = [...searchIdentificationCodeList].reverse();
			for (const searchItem of reversedSearchOrder) {
				const foundItem = newDataMap.get(searchItem.id);
				if (foundItem && !addedIds.has(searchItem.id)) {
					orderedResult.push(foundItem);
					addedIds.add(searchItem.id);
				}
			}
		}
		for (const newItem of newData) if (!initialOrderedDataRef.current.some((initialItem) => initialItem.id === newItem.id) && !addedIds.has(newItem.id)) {
			orderedResult.push(newItem);
			addedIds.add(newItem.id);
		}
		for (const initialItem of initialOrderedDataRef.current) if (newDataMap.has(initialItem.id) && !addedIds.has(initialItem.id)) {
			orderedResult.push(newDataMap.get(initialItem.id));
			addedIds.add(initialItem.id);
		}
		return orderedResult;
	});
	const sortDiscountListWithInitialOrder = (0, ahooks.useMemoizedFn)((newDiscountList) => {
		const sortBySelected = (list) => {
			return list.sort((a, b) => {
				if (a.isSelected && !b.isSelected) return -1;
				if (!a.isSelected && b.isSelected) return 1;
				return 0;
			});
		};
		if (initialDiscountOrderRef.current.length === 0 || newDiscountList.length === 0) {
			const historyItems = newDiscountList.filter((item) => item.isEditMode);
			const normalItems = newDiscountList.filter((item) => !item.isEditMode);
			return [...historyItems, ...sortBySelected(normalItems)];
		}
		const newDataBucketMap = /* @__PURE__ */ new Map();
		for (const item of newDiscountList) {
			var _newDataBucketMap$get;
			if (!newDataBucketMap.has(item.id)) newDataBucketMap.set(item.id, []);
			(_newDataBucketMap$get = newDataBucketMap.get(item.id)) === null || _newDataBucketMap$get === void 0 || _newDataBucketMap$get.push(item);
		}
		const consumeItemByRef = (targetItem) => {
			const bucket = newDataBucketMap.get(targetItem.id);
			if (!(bucket === null || bucket === void 0 ? void 0 : bucket.length)) return null;
			const targetIndex = bucket.indexOf(targetItem);
			if (targetIndex === -1) return null;
			return bucket.splice(targetIndex, 1)[0];
		};
		const consumeItemByInitial = (initialItem, matcher) => {
			const bucket = newDataBucketMap.get(initialItem.id);
			if (!(bucket === null || bucket === void 0 ? void 0 : bucket.length)) return null;
			const targetIndex = bucket.findIndex((candidate) => matcher(candidate, initialItem));
			if (targetIndex === -1) return null;
			return bucket.splice(targetIndex, 1)[0];
		};
		const historyItems = [];
		const normalItemsByInitialOrder = [];
		const remainingNormalItems = [];
		const initialHistoryItems = initialDiscountOrderRef.current.filter((item) => item.isEditMode);
		for (const initialItem of initialHistoryItems) {
			const matchedHistoryItem = consumeItemByInitial(initialItem, (candidate) => !!candidate.isEditMode);
			if (matchedHistoryItem) historyItems.push(matchedHistoryItem);
		}
		for (const item of newDiscountList) {
			if (!item.isEditMode) continue;
			const remainingHistoryItem = consumeItemByRef(item);
			if (remainingHistoryItem) historyItems.push(remainingHistoryItem);
		}
		for (const initialItem of initialDiscountOrderRef.current) {
			if (initialItem.isEditMode) continue;
			const matchedNormalItem = consumeItemByInitial(initialItem, (candidate) => !candidate.isEditMode);
			if (matchedNormalItem) normalItemsByInitialOrder.push(matchedNormalItem);
		}
		for (const item of newDiscountList) {
			if (item.isEditMode) continue;
			const remainingNormalItem = consumeItemByRef(item);
			if (remainingNormalItem) remainingNormalItems.push(remainingNormalItem);
		}
		return [
			...historyItems,
			...normalItemsByInitialOrder,
			...sortBySelected(remainingNormalItems)
		];
	});
	const allVouchersForCalculation = (0, react.useMemo)(() => {
		return [...transformList || [], ...searchIdentificationCodeList || []];
	}, [transformList, searchIdentificationCodeList]);
	const selectedVouchers = (0, react.useMemo)(() => {
		return selectedVoucherIds.map((id) => allVouchersForCalculation.find((v) => v.id === id)).filter(Boolean);
	}, [selectedVoucherIds, allVouchersForCalculation]);
	const { displayVouchers, displayOtherVouchers, selectedWithDetails, totalDeduction } = (0, react.useMemo)(() => {
		if (!walletPassEvaluator || !allVouchersForCalculation.length || !totalAmount) return {
			displayVouchers: [...transformList || [], ...noApplicableVoucher || []],
			displayOtherVouchers: searchIdentificationCodeList || [],
			selectedWithDetails: [],
			totalDeduction: 0
		};
		const calculationProducts = getWalletCalculationProducts();
		const result = walletPassEvaluator.recalculateVouchers(allVouchersForCalculation, selectedVouchers, totalAmount, calculationProducts);
		const currentCustomerVouchers = [];
		const otherCustomerVouchers = [];
		result.allWithUpdatedStatus.forEach((voucher) => {
			if (searchIdentificationCodeList.some((item) => item.id === voucher.id)) otherCustomerVouchers.push(voucher);
			else currentCustomerVouchers.push(voucher);
		});
		return {
			displayVouchers: [...currentCustomerVouchers, ...noApplicableVoucher || []],
			displayOtherVouchers: otherCustomerVouchers,
			selectedWithDetails: result.selectedWithDetails,
			totalDeduction: result.selectedWithDetails.reduce((sum, v) => sum + (v.actualDeduction || 0), 0)
		};
	}, [
		selectedVouchers,
		allVouchersForCalculation,
		transformList,
		searchIdentificationCodeList,
		noApplicableVoucher,
		totalAmount,
		products,
		baseSales
	]);
	(0, ahooks.useDebounceEffect)(() => {
		notifySelectChange(selectedWithDetails);
		setWalletSelect(selectedWithDetails);
		setLoading(false);
	}, [selectedWithDetails], { wait: 200 });
	const data = (0, react.useMemo)(() => {
		return require_utils$1.formatMachineCodeServer2CardList((0, _pisell_utils.uniqueByKey)(mergeDataWithInitialOrder([
			...selectedWithDetails,
			...displayVouchers,
			...displayOtherVouchers
		]), "id"), selectedVoucherIds);
	}, [
		displayVouchers,
		displayOtherVouchers,
		selectedVoucherIds,
		selectedWithDetails
	]);
	const fetchUserIdentificationCodes = (0, ahooks.useMemoizedFn)(function() {
		var _ref6 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			setLoading(true);
			setError(null);
			try {
				var _walletApi$getUserIde;
				const result = yield walletApi === null || walletApi === void 0 || (_walletApi$getUserIde = walletApi.getUserIdentificationCodeListAsync) === null || _walletApi$getUserIde === void 0 ? void 0 : _walletApi$getUserIde.call(walletApi, params);
				if (!result) return [];
				setUserIdentificationCodes((0, _pisell_utils.uniqueByKey)([...result, ...selectedWalletRef.current], "id"));
				return result;
			} catch (err) {
				setError(err instanceof Error ? err.message : "获取用户识别码列表失败");
				throw err;
			} finally {
				setLoading(false);
			}
		});
		return function(_x) {
			return _ref6.apply(this, arguments);
		};
	}());
	const getCachedWalletRecommendList = (0, ahooks.useMemoizedFn)(() => {
		var _walletApi$getWalletR;
		return (walletApi === null || walletApi === void 0 || (_walletApi$getWalletR = walletApi.getWalletRecommendList) === null || _walletApi$getWalletR === void 0 ? void 0 : _walletApi$getWalletR.call(walletApi)) || [];
	});
	const getCachedUserIdentificationCodes = (0, ahooks.useMemoizedFn)(() => {
		var _walletApi$getUserIde2;
		return (walletApi === null || walletApi === void 0 || (_walletApi$getUserIde2 = walletApi.getUserIdentificationCodes) === null || _walletApi$getUserIde2 === void 0 ? void 0 : _walletApi$getUserIde2.call(walletApi)) || [];
	});
	const clearWalletRecommendList = (0, ahooks.useMemoizedFn)(() => {
		var _walletApi$clearWalle;
		walletApi === null || walletApi === void 0 || (_walletApi$clearWalle = walletApi.clearWalletRecommendList) === null || _walletApi$clearWalle === void 0 || _walletApi$clearWalle.call(walletApi);
		setWalletRecommendList([]);
	});
	const clearUserIdentificationCodes = (0, ahooks.useMemoizedFn)(() => {
		var _walletApi$clearUserI;
		walletApi === null || walletApi === void 0 || (_walletApi$clearUserI = walletApi.clearUserIdentificationCodes) === null || _walletApi$clearUserI === void 0 || _walletApi$clearUserI.call(walletApi);
		setUserIdentificationCodes([]);
	});
	const clearAllCache = (0, ahooks.useMemoizedFn)(() => {
		var _walletApi$clearAllCa;
		walletApi === null || walletApi === void 0 || (_walletApi$clearAllCa = walletApi.clearAllCache) === null || _walletApi$clearAllCa === void 0 || _walletApi$clearAllCa.call(walletApi);
		setWalletRecommendList([]);
		setUserIdentificationCodes([]);
		setSearchIdentificationCodeList([]);
		setDisabledWalletData([]);
		setNoApplicableVoucher([]);
		setTransformList([]);
		setWalletSelect([]);
		setSelectedVoucherIds([]);
	});
	const handleSearchIdentificationCodeCompleted = (0, ahooks.useMemoizedFn)((data) => {
		const { currentSearchResults, cachedSearchResults } = data;
		const calculationProducts = getWalletCalculationProducts();
		let formattedResults = currentSearchResults;
		if (walletPassEvaluator && currentSearchResults.length > 0 && totalAmount) formattedResults = walletPassEvaluator.searchVoucherFormat({
			vouchers: currentSearchResults,
			orderTotalAmount: totalAmount,
			products: calculationProducts
		});
		let formattedCachedResults = cachedSearchResults || [];
		if (walletPassEvaluator && cachedSearchResults && cachedSearchResults.length > 0 && totalAmount) formattedCachedResults = walletPassEvaluator.searchVoucherFormat({
			vouchers: cachedSearchResults,
			orderTotalAmount: totalAmount,
			products: calculationProducts
		});
		const mergedSearchResults = (0, _pisell_utils.uniqueByKey)([...formattedCachedResults || [], ...formattedResults], "id");
		let isAvailableData = [];
		let isDisabledData = [];
		if (formattedResults.length > 0) formattedResults.forEach((item) => {
			if (require_utils$1.getVoucherAvailableStatus(item)) isAvailableData.push(item);
			else isDisabledData.push(item);
		});
		const availableData = mergedSearchResults.filter((item) => require_utils$1.getVoucherAvailableStatus(item));
		const allDisabledData = mergedSearchResults.filter((item) => !require_utils$1.getVoucherAvailableStatus(item));
		setDisabledWalletData(allDisabledData);
		let newValues = [...selectedWalletRef.current];
		if (isAvailableData.length === 1) newValues = [...selectedWalletRef.current, ...isAvailableData];
		setSearchIdentificationCodeList(availableData);
		setNoApplicableVoucher(allDisabledData);
		setWalletSelect(newValues);
		setSelectedVoucherIds(newValues.map((item) => item.id));
	});
	const applyWalletInitResult = (0, ahooks.useMemoizedFn)((result) => {
		var _baseSales$getOrderSn5, _walletApi$getStoredW;
		setOrderInfo((baseSales === null || baseSales === void 0 || (_baseSales$getOrderSn5 = baseSales.getOrderSnapshot) === null || _baseSales$getOrderSn5 === void 0 || (_baseSales$getOrderSn5 = _baseSales$getOrderSn5.call(baseSales)) === null || _baseSales$getOrderSn5 === void 0 ? void 0 : _baseSales$getOrderSn5.tempOrder) || {});
		let recommendList = (result === null || result === void 0 ? void 0 : result.walletRecommendList) || getCachedWalletRecommendList();
		let userIdentificationCodes = (result === null || result === void 0 ? void 0 : result.userIdentificationCodes) || getCachedUserIdentificationCodes();
		const walletInitData = (walletApi === null || walletApi === void 0 || (_walletApi$getStoredW = walletApi.getStoredWalletInitData) === null || _walletApi$getStoredW === void 0 ? void 0 : _walletApi$getStoredW.call(walletApi)) || {};
		let transformListData = (result === null || result === void 0 ? void 0 : result.transformList) || walletInitData.transformList || userIdentificationCodes;
		const noApplicableVoucherData = (result === null || result === void 0 ? void 0 : result.noApplicableVoucher) || walletInitData.noApplicableVoucher || [];
		const productsData = (result === null || result === void 0 ? void 0 : result.products) || walletInitData.products || [];
		if (preserveManualWalletSelectionRef.current || confirmedEditAmountIdsRef.current.length > 0) {
			recommendList = mergeManualEditAmount(recommendList);
			userIdentificationCodes = mergeManualEditAmount(userIdentificationCodes);
			transformListData = mergeManualEditAmount(transformListData);
		}
		if (selectedVoucherIds.length > 0) {
			recommendList = mergeSelectedWalletAmount(recommendList);
			userIdentificationCodes = mergeSelectedWalletAmount(userIdentificationCodes);
			transformListData = mergeSelectedWalletAmount(transformListData);
		}
		const initialData = [...recommendList, ...userIdentificationCodes];
		setWalletRecommendList(recommendList);
		setUserIdentificationCodes(userIdentificationCodes);
		setTransformList(transformListData);
		setNoApplicableVoucher(noApplicableVoucherData);
		setProducts(productsData);
		initialOrderedDataRef.current = initialData;
		if (!notSetWalletSelectRef.current && !preserveManualWalletSelectionRef.current) {
			var _walletApi$formatWall;
			setWalletSelect(recommendList);
			setSelectedVoucherIds(recommendList.map((item) => item.id));
			const select = ((walletApi === null || walletApi === void 0 || (_walletApi$formatWall = walletApi.formatWalletPassList2PreparePayments) === null || _walletApi$formatWall === void 0 ? void 0 : _walletApi$formatWall.call(walletApi, recommendList)) || []).map((item) => ({
				code: item.tag,
				voucher_id: item.voucher_id,
				amount: item.amount || 0,
				wallet_pass_usage_unit: item.wallet_pass_usage_unit,
				wallet_pass_use_value: item.wallet_pass_use_value
			}));
			logger === null || logger === void 0 || logger.addLog({
				type: "info",
				title: "useWalletPass_onOrderCreated onSelectChange 开始调用",
				metadata: {}
			});
			onSelectChange === null || onSelectChange === void 0 || onSelectChange(select);
		} else if (preserveManualWalletSelectionRef.current) {
			const selectedIdSet = new Set(selectedVoucherIds);
			setWalletSelect(transformListData.filter((item) => selectedIdSet.has(item.id)));
		} else {
			setWalletSelect([]);
			setSelectedVoucherIds([]);
			notSetWalletSelectRef.current = false;
			onSelectChange === null || onSelectChange === void 0 || onSelectChange([]);
		}
		const sortedDiscountList = sortDiscountListWithInitialOrder(normalizeBaseSalesCurrentDiscountList(baseSales, productsData.length ? productsData : products, historyDiscountIdsRef.current));
		initialDiscountOrderRef.current = sortedDiscountList;
		setDiscountList(sortedDiscountList);
		if (showBestToastRef.current) Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("wallet-pass-module-best-combination-selected"));
		showBestToastRef.current = false;
	});
	const refreshWalletData = (0, ahooks.useMemoizedFn)(function() {
		var _ref8 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			var _ref7, _params$order_wait_pa, _baseSales$getTempOrd4, _baseSales$getOrderId4;
			if (!(baseSales === null || baseSales === void 0 ? void 0 : baseSales.initWalletData)) return;
			const requestedOrderWaitPayAmount = Number((_ref7 = (_params$order_wait_pa = params === null || params === void 0 ? void 0 : params.order_wait_pay_amount) !== null && _params$order_wait_pa !== void 0 ? _params$order_wait_pa : customAmount) !== null && _ref7 !== void 0 ? _ref7 : 0);
			const selectedWalletDeductionAmount = getSelectedWalletDeductionAmount();
			const orderWaitPayAmount = selectedVoucherIds.length > 0 ? Number((requestedOrderWaitPayAmount + selectedWalletDeductionAmount).toFixed(2)) : requestedOrderWaitPayAmount;
			if (orderWaitPayAmount <= 0) return;
			const walletInitKey = JSON.stringify({
				orderId: (baseSales === null || baseSales === void 0 || (_baseSales$getTempOrd4 = baseSales.getTempOrder) === null || _baseSales$getTempOrd4 === void 0 || (_baseSales$getTempOrd4 = _baseSales$getTempOrd4.call(baseSales)) === null || _baseSales$getTempOrd4 === void 0 ? void 0 : _baseSales$getTempOrd4.order_id) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderId4 = baseSales.getOrderIdentity) === null || _baseSales$getOrderId4 === void 0 || (_baseSales$getOrderId4 = _baseSales$getOrderId4.call(baseSales)) === null || _baseSales$getOrderId4 === void 0 ? void 0 : _baseSales$getOrderId4.orderId),
				customerId: getBaseSalesCustomerId(),
				orderWaitPayAmount
			});
			if (walletInitPromiseRef.current && walletInitKeyRef.current === walletInitKey) return walletInitPromiseRef.current;
			if (walletInitKeyRef.current === walletInitKey && walletRecommendList.length > 0) return;
			walletInitKeyRef.current = walletInitKey;
			setLoading(true);
			const walletInitTask = require_asyncToGenerator._asyncToGenerator(function* () {
				const result = yield baseSales.initWalletData(require_objectSpread2._objectSpread2({ order_wait_pay_amount: orderWaitPayAmount }, params));
				applyWalletInitResult(result);
				return result;
			})();
			walletInitPromiseRef.current = walletInitTask;
			try {
				return yield walletInitTask;
			} finally {
				if (walletInitPromiseRef.current === walletInitTask) walletInitPromiseRef.current = null;
				setLoading(false);
			}
		});
		return function(_x2) {
			return _ref8.apply(this, arguments);
		};
	}());
	const customerName = (0, react.useMemo)(() => {
		var _orderInfo$_extend, _orderInfo$original_o, _orderInfo$original_o2, _orderInfo$original_o3;
		const customerSnapshot = (orderInfo === null || orderInfo === void 0 || (_orderInfo$_extend = orderInfo._extend) === null || _orderInfo$_extend === void 0 ? void 0 : _orderInfo$_extend.customerSnapshot) || (orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.customer) || (orderInfo === null || orderInfo === void 0 || (_orderInfo$original_o = orderInfo.original_order_data) === null || _orderInfo$original_o === void 0 ? void 0 : _orderInfo$original_o.customer) || {};
		if (require_utils.isWalkIn((orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.customer_id) || (orderInfo === null || orderInfo === void 0 || (_orderInfo$original_o2 = orderInfo.original_order_data) === null || _orderInfo$original_o2 === void 0 ? void 0 : _orderInfo$original_o2.customer_id) || (customerSnapshot === null || customerSnapshot === void 0 ? void 0 : customerSnapshot.id) || (customerSnapshot === null || customerSnapshot === void 0 ? void 0 : customerSnapshot.customer_id))) return _pisell_utils.locales.getText("wallet-pass-module-customer-name-walk-in");
		return (customerSnapshot === null || customerSnapshot === void 0 ? void 0 : customerSnapshot.display_name) || (customerSnapshot === null || customerSnapshot === void 0 ? void 0 : customerSnapshot.name) || (orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.customer_name) || (orderInfo === null || orderInfo === void 0 || (_orderInfo$original_o3 = orderInfo.original_order_data) === null || _orderInfo$original_o3 === void 0 ? void 0 : _orderInfo$original_o3.customer_name) || "";
	}, [orderInfo]);
	(0, react.useEffect)(() => {
		const shouldSkipForWalkIn = require_utils.isWalkIn(getBaseSalesCustomerId());
		if (!baseSales) return;
		if (shouldSkipForWalkIn) {
			const sortedDiscountList = sortDiscountListWithInitialOrder(normalizeBaseSalesCurrentDiscountList(baseSales, getWalletCalculationProducts(), historyDiscountIdsRef.current));
			initialDiscountOrderRef.current = sortedDiscountList;
			setDiscountList(sortedDiscountList);
			return;
		}
		require_asyncToGenerator._asyncToGenerator(function* () {
			yield prepareBaseSalesDiscounts();
			yield refreshWalletData({ order_wait_pay_amount: Number(customAmount || totalAmount || 0) });
		})();
	}, [
		baseSales,
		clientId,
		customAmount,
		totalAmount
	]);
	const allList = (0, react.useMemo)(() => {
		const reversedSearchData = [...searchIdentificationCodeList].reverse();
		return [
			...userIdentificationCodes,
			...walletRecommendList,
			...reversedSearchData
		];
	}, [
		walletRecommendList,
		userIdentificationCodes,
		searchIdentificationCodeList
	]);
	(0, ahooks.useMemoizedFn)(() => {
		return searchIdentificationCodeList.filter((item) => !selectedWalletRef.current.some((wallet) => wallet.id === item.id)).map((item) => item.code);
	});
	const notifySelectChange = (0, ahooks.useMemoizedFn)((selectedDetails) => {
		var _walletApi$formatWall2;
		const prepare_payments = (walletApi === null || walletApi === void 0 || (_walletApi$formatWall2 = walletApi.formatWalletPassList2PreparePayments) === null || _walletApi$formatWall2 === void 0 ? void 0 : _walletApi$formatWall2.call(walletApi, selectedDetails)) || [];
		const select = [];
		prepare_payments.forEach((item) => {
			if (item.amount && select.every((s) => s.voucher_id !== item.voucher_id)) select.push({
				voucher_id: item.voucher_id,
				amount: item.amount,
				code: item.tag,
				wallet_pass_usage_unit: item.wallet_pass_usage_unit,
				wallet_pass_use_value: item.wallet_pass_use_value
			});
		});
		logger === null || logger === void 0 || logger.addLog({
			type: "info",
			title: "useWalletPass_notifySelectChange 通知外部选择变化",
			metadata: {
				selectedDetails,
				select
			}
		});
		onSelectChange === null || onSelectChange === void 0 || onSelectChange(select);
	});
	const handleSearchIdentificationCode = (0, ahooks.useMemoizedFn)(function() {
		var _ref9 = require_asyncToGenerator._asyncToGenerator(function* (value) {
			var _walletApi$formatWall3;
			if (!(walletApi === null || walletApi === void 0 ? void 0 : walletApi.searchIdentificationCodeAsync)) return null;
			const result = yield walletApi.searchIdentificationCodeAsync({
				code: value,
				prepare_payments: ((_walletApi$formatWall3 = walletApi.formatWalletPassList2PreparePayments) === null || _walletApi$formatWall3 === void 0 ? void 0 : _walletApi$formatWall3.call(walletApi, selectedWithDetails)) || []
			});
			handleSearchIdentificationCodeCompleted({
				currentSearchResults: (result === null || result === void 0 ? void 0 : result.data) || [],
				cachedSearchResults: searchIdentificationCodeList
			});
			return result;
		});
		return function(_x3) {
			return _ref9.apply(this, arguments);
		};
	}());
	const handleSelectWallet = (0, ahooks.useMemoizedFn)((value) => {
		setLoading(true);
		preserveManualWalletSelectionRef.current = true;
		const deselectedIds = selectedVoucherIds.filter((id) => !value.includes(id));
		if (deselectedIds.length > 0) {
			const needResetIds = deselectedIds.filter((id) => {
				const voucher = allVouchersForCalculation.find((v) => v.id === id);
				return (voucher === null || voucher === void 0 ? void 0 : voucher.edit_current_amount) !== void 0;
			});
			if (needResetIds.length > 0) {
				updateWalletDataById(needResetIds, { edit_current_amount: void 0 });
				confirmedEditAmountIdsRef.current = confirmedEditAmountIdsRef.current.filter((id) => !needResetIds.includes(id));
			}
		}
		setSelectedVoucherIds(value);
		setWalletSelect(allVouchersForCalculation.filter((item) => value.includes(item.id)));
	});
	const expiredWalletIds = (0, react.useMemo)(() => {
		return (0, _pisell_utils.uniqueByKey)(allList, "id").filter((item) => item.expire_date && (0, dayjs.default)(item.expire_date).isBefore((0, dayjs.default)()));
	}, [allList, selectedWalletIds]);
	const expiredWalletData = (0, react.useMemo)(() => {
		return require_utils$1.formatMachineCodeServer2CardList((0, _pisell_utils.uniqueByKey)(allList, "id").filter((item) => item.expire_date && (0, dayjs.default)(item.expire_date).isBefore((0, dayjs.default)())), [], {
			error: true,
			showStatus: false
		});
	}, [allList]);
	const clearAllSelectedWallet = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (confirmedEditAmountIdsRef.current.length > 0) {
			updateWalletDataById(confirmedEditAmountIdsRef.current, { edit_current_amount: void 0 });
			confirmedEditAmountIdsRef.current = [];
		}
		if (selectedWalletIds.length === 0 && selectedDiscountList.length === 0) return;
		setLoading(true);
		if (selectedDiscountList.length) {
			var _baseSales$getOrderPr3, _props$onDiscountChan;
			notSetWalletSelectRef.current = true;
			for (const discountId of selectedDiscountList) {
				var _baseSales$setDiscoun;
				yield baseSales === null || baseSales === void 0 || (_baseSales$setDiscoun = baseSales.setDiscountSelected) === null || _baseSales$setDiscoun === void 0 ? void 0 : _baseSales$setDiscoun.call(baseSales, {
					discountId,
					isSelected: false
				});
			}
			const productList = (baseSales === null || baseSales === void 0 || (_baseSales$getOrderPr3 = baseSales.getOrderProducts) === null || _baseSales$getOrderPr3 === void 0 ? void 0 : _baseSales$getOrderPr3.call(baseSales)) || [];
			const detail = {
				productList,
				discountList: normalizeBaseSalesCurrentDiscountList(baseSales, productList, historyDiscountIdsRef.current)
			};
			const sortedDiscountList = sortDiscountListWithInitialOrder(detail.discountList);
			setDiscountList(sortedDiscountList);
			(_props$onDiscountChan = props.onDiscountChange) === null || _props$onDiscountChan === void 0 || _props$onDiscountChan.call(props, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, detail), {}, { discountList: sortedDiscountList }));
			setLoading(false);
			return;
		}
		preserveManualWalletSelectionRef.current = true;
		setWalletSelect([]);
		setSelectedVoucherIds([]);
		logger === null || logger === void 0 || logger.addLog({
			type: "info",
			title: "useWalletPass_clearAllSelectedWallet 立即通知外部清空",
			metadata: {}
		});
		onSelectChange === null || onSelectChange === void 0 || onSelectChange([]);
		setLoading(false);
	}));
	const isCurrentSelectionBest = (0, ahooks.useMemoizedFn)(() => {
		if (walletRecommendList.length === 0) return true;
		const recommendedIds = walletRecommendList.map((item) => item.id).sort();
		const currentSelectedIds = selectedWalletIds.sort();
		return JSON.stringify(recommendedIds) === JSON.stringify(currentSelectedIds);
	});
	const handleBestSaving = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		logger === null || logger === void 0 || logger.addLog({
			type: "info",
			title: "useWalletPass_handleBestSaving 开始调用",
			metadata: {}
		});
		setLoading(true);
		let hasGoodPass = false;
		let isBestDiscount = false;
		if (availableDiscountList.length) {
			var _baseSales$bestDiscou, _baseSales$getOrderPr4, _baseSales$getDiscoun3, _props$onDiscountChan2;
			hasGoodPass = true;
			showBestToastRef.current = true;
			const result = yield baseSales === null || baseSales === void 0 || (_baseSales$bestDiscou = baseSales.bestDiscount) === null || _baseSales$bestDiscou === void 0 ? void 0 : _baseSales$bestDiscou.call(baseSales);
			const productList = (result === null || result === void 0 ? void 0 : result.productList) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderPr4 = baseSales.getOrderProducts) === null || _baseSales$getOrderPr4 === void 0 ? void 0 : _baseSales$getOrderPr4.call(baseSales)) || [];
			const sortedDiscountList = sortDiscountListWithInitialOrder(normalizeBaseSalesDiscountHistory((result === null || result === void 0 ? void 0 : result.discountList) || (baseSales === null || baseSales === void 0 || (_baseSales$getDiscoun3 = baseSales.getDiscountList) === null || _baseSales$getDiscoun3 === void 0 ? void 0 : _baseSales$getDiscoun3.call(baseSales)) || [], productList, historyDiscountIdsRef.current));
			setDiscountList(sortedDiscountList);
			(_props$onDiscountChan2 = props.onDiscountChange) === null || _props$onDiscountChan2 === void 0 || _props$onDiscountChan2.call(props, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, result), {}, { discountList: sortedDiscountList }));
			if (require_utils$1.isSameContent(sortedDiscountList.filter((item) => item.isSelected).map((item) => item.id), selectedDiscountList)) {
				showBestToastRef.current = false;
				isBestDiscount = true;
				setLoading(false);
				Toast === null || Toast === void 0 || Toast.info(_pisell_utils.locales.getText("wallet-pass-module-already-best-combination"));
			}
		}
		if (walletRecommendList.length === 0) {
			if (!hasGoodPass || hasGoodPass && isBestDiscount) setLoading(false);
			if (searchIdentificationCodeList.length) if (require_utils$1.isSameContent(selectedWalletIds, searchIdentificationCodeList.map((item) => item.id))) Toast === null || Toast === void 0 || Toast.info(_pisell_utils.locales.getText("wallet-pass-module-already-best-combination"));
			else {
				const select = searchIdentificationCodeList.filter((item) => require_utils$1.getVoucherAvailableStatus(item));
				setWalletSelect(select);
				setSelectedVoucherIds(select.map((item) => item.id));
				if (select.length) Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("wallet-pass-module-best-combination-selected"));
			}
			return;
		}
		let isChangeAmount = false;
		let newWalletRecommendList = walletRecommendList;
		if (confirmedEditAmountIdsRef.current.length > 0) {
			isChangeAmount = true;
			newWalletRecommendList = updateWalletDataById(confirmedEditAmountIdsRef.current, { edit_current_amount: void 0 }).newWalletRecommendList;
			confirmedEditAmountIdsRef.current = [];
		}
		if (isCurrentSelectionBest() && !isChangeAmount) {
			if (!hasGoodPass) Toast === null || Toast === void 0 || Toast.info(_pisell_utils.locales.getText("wallet-pass-module-already-best-combination"));
		} else {
			if (hasGoodPass && !isBestDiscount) return;
			setWalletSelect(newWalletRecommendList);
			setSelectedVoucherIds(newWalletRecommendList.map((item) => item.id));
			Toast === null || Toast === void 0 || Toast.success(_pisell_utils.locales.getText("wallet-pass-module-best-combination-selected"));
		}
		setLoading(false);
	}));
	const handleSelectDiscount = (0, ahooks.useMemoizedFn)(function() {
		var _ref10 = require_asyncToGenerator._asyncToGenerator(function* (value, option) {
			setLoading(true);
			try {
				var _baseSales$setDiscoun2, _baseSales$getOrderPr5, _props$onDiscountChan3;
				const isSelected = value.includes(option.id);
				yield baseSales === null || baseSales === void 0 || (_baseSales$setDiscoun2 = baseSales.setDiscountSelected) === null || _baseSales$setDiscoun2 === void 0 ? void 0 : _baseSales$setDiscoun2.call(baseSales, {
					discountId: option.id,
					isSelected
				});
				const productList = (baseSales === null || baseSales === void 0 || (_baseSales$getOrderPr5 = baseSales.getOrderProducts) === null || _baseSales$getOrderPr5 === void 0 ? void 0 : _baseSales$getOrderPr5.call(baseSales)) || [];
				const detail = {
					productList,
					discountList: normalizeBaseSalesCurrentDiscountList(baseSales, productList, historyDiscountIdsRef.current)
				};
				const sortedDiscountList = sortDiscountListWithInitialOrder(detail.discountList);
				setDiscountList(sortedDiscountList);
				(_props$onDiscountChan3 = props.onDiscountChange) === null || _props$onDiscountChan3 === void 0 || _props$onDiscountChan3.call(props, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, detail), {}, { discountList: sortedDiscountList }));
			} finally {
				setLoading(false);
			}
		});
		return function(_x4, _x5) {
			return _ref10.apply(this, arguments);
		};
	}());
	const clearDisabledWalletData = (0, ahooks.useMemoizedFn)(() => {
		setDisabledWalletData([]);
	});
	const updateArrayItemById = (0, ahooks.useMemoizedFn)((array, targetId, updateData) => {
		const targetIds = Array.isArray(targetId) ? targetId : [targetId];
		return array.map((item) => targetIds.includes(item.id) ? require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), updateData) : item);
	});
	const updateWalletDataById = (0, ahooks.useMemoizedFn)((targetId, updateData) => {
		const newWalletRecommendList = updateArrayItemById(walletRecommendList, targetId, updateData);
		setWalletRecommendList(newWalletRecommendList);
		const newUserIdentificationCodes = updateArrayItemById(userIdentificationCodes, targetId, updateData);
		setUserIdentificationCodes(newUserIdentificationCodes);
		const newTransformList = updateArrayItemById(transformList, targetId, updateData);
		setTransformList(newTransformList);
		const newSearchIdentificationCodeList = updateArrayItemById(searchIdentificationCodeList, targetId, updateData);
		setSearchIdentificationCodeList(newSearchIdentificationCodeList);
		const newSelectedWallet = updateArrayItemById(selectedWallet, targetId, updateData);
		setWalletSelect(newSelectedWallet);
		return {
			newWalletRecommendList,
			newUserIdentificationCodes,
			newTransformList,
			newSearchIdentificationCodeList,
			newSelectedWallet
		};
	});
	const handleConfirmEditAmount = (0, ahooks.useMemoizedFn)((value, id, data) => {
		if (value === 0) {
			handleSelectWallet(selectedVoucherIds.filter((walletId) => walletId !== data.id));
			return;
		}
		setLoading(true);
		if (!confirmedEditAmountIdsRef.current.includes(data.id)) confirmedEditAmountIdsRef.current.push(data.id);
		updateWalletDataById(data.id, { edit_current_amount: value });
	});
	return {
		walletRecommendList,
		userIdentificationCodes,
		loading,
		error,
		cardData: data,
		handleSelectWallet,
		selectedWalletIds,
		expiredWalletIds,
		expiredWalletData,
		disabledWalletData,
		clearAllSelectedWallet,
		clearDisabledWalletData,
		handleBeforeEditAmount: (0, ahooks.useMemoizedFn)(function() {
			var _ref11 = require_asyncToGenerator._asyncToGenerator(function* (value, index, data) {
				return true;
			});
			return function(_x6, _x7, _x8) {
				return _ref11.apply(this, arguments);
			};
		}()),
		handleBestSaving,
		handleSearchIdentificationCode,
		availableDiscountList,
		selectedDiscountList,
		handleSelectDiscount,
		customerName,
		fetchUserIdentificationCodes,
		getCachedWalletRecommendList,
		getCachedUserIdentificationCodes,
		clearWalletRecommendList,
		clearUserIdentificationCodes,
		clearAllCache,
		handleConfirmEditAmount
	};
};
//#endregion
exports.useWalletPass = useWalletPass;
