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_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_useShopDiscountModule = require("../../ticketBooking/hooks/pisellos/useShopDiscountModule.js");
const require_utils$1 = require("../components/WalletPassModule/utils.js");
const require_usePaymentLogger = require("./usePaymentLogger.js");
const require_useActiveExecute = require("../../ticketBooking/hooks/pisellos/useActiveExecute.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
/**
* 自定义Hook：使用WalletPass功能
*/
const useWalletPass = (props) => {
	const { onSelectChange, customAmount, clientId, totalAmount } = props;
	const logger = require_usePaymentLogger.default();
	const { executeIfActive } = require_useActiveExecute.useActiveExecute();
	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 [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 showBestToastRef = (0, react.useRef)(false);
	const [products, setProducts] = (0, react.useState)([]);
	const selectedWalletIds = (0, react.useMemo)(() => {
		return selectedWallet.map((item) => item.id);
	}, [selectedWallet]);
	const pisellos = require_useEngineContext.usePisellOS();
	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 checkoutModule = pisellos.getModule("checkout");
	const shopDiscount = require_useShopDiscountModule.useShopDiscountModule();
	const paymentModule = checkoutModule === null || checkoutModule === void 0 ? void 0 : checkoutModule.payment;
	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);
	}, []);
	const setWalletSelect = (0, ahooks.useMemoizedFn)((data) => {
		setSelectedWallet(data);
		selectedWalletRef.current = data;
	});
	(0, react.useEffect)(() => {
		if (require_utils.isWalkIn(clientId) && searchIdentificationCodeList.length === 0) {
			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: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
			});
		}));
	}, [discountList]);
	const selectedDiscountList = (0, react.useMemo)(() => {
		return availableDiscountList.filter((item) => item.isSelected).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) => {
		if (initialDiscountOrderRef.current.length === 0 || newDiscountList.length === 0) return newDiscountList.sort((a, b) => {
			if (a.isSelected && !b.isSelected) return -1;
			if (!a.isSelected && b.isSelected) return 1;
			return 0;
		});
		const newDataMap = new Map(newDiscountList.map((item) => [item.id, item]));
		const orderedResult = [];
		const addedIds = /* @__PURE__ */ new Set();
		for (const initialItem of initialDiscountOrderRef.current) if (newDataMap.has(initialItem.id)) {
			orderedResult.push(newDataMap.get(initialItem.id));
			addedIds.add(initialItem.id);
		}
		const newItems = newDiscountList.filter((item) => !addedIds.has(item.id));
		newItems.sort((a, b) => {
			if (a.isSelected && !b.isSelected) return -1;
			if (!a.isSelected && b.isSelected) return 1;
			return 0;
		});
		orderedResult.push(...newItems);
		return orderedResult;
	});
	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 result = walletPassEvaluator.recalculateVouchers(allVouchersForCalculation, selectedVouchers, totalAmount, products || []);
		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
	]);
	(0, ahooks.useUpdateEffect)(() => {
		notifySelectChange(selectedWithDetails);
		setLoading(false);
	}, [selectedWithDetails]);
	const data = (0, react.useMemo)(() => {
		return require_utils$1.formatMachineCodeServer2CardList((0, _pisell_utils.uniqueByKey)(mergeDataWithInitialOrder([
			...selectedWallet,
			...displayVouchers,
			...displayOtherVouchers
		]), "id"), selectedVoucherIds);
	}, [
		displayVouchers,
		displayOtherVouchers,
		selectedVoucherIds,
		selectedWallet
	]);
	const fetchUserIdentificationCodes = (0, ahooks.useMemoizedFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (params) {
			setLoading(true);
			setError(null);
			try {
				const result = yield paymentModule.wallet.getUserIdentificationCodeListAsync(params);
				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 _ref.apply(this, arguments);
		};
	}());
	const getCachedWalletRecommendList = (0, ahooks.useMemoizedFn)(() => {
		return paymentModule.wallet.getWalletRecommendList();
	});
	const getCachedUserIdentificationCodes = (0, ahooks.useMemoizedFn)(() => {
		return paymentModule.wallet.getUserIdentificationCodes();
	});
	const clearWalletRecommendList = (0, ahooks.useMemoizedFn)(() => {
		paymentModule.wallet.clearWalletRecommendList();
	});
	const clearUserIdentificationCodes = (0, ahooks.useMemoizedFn)(() => {
		paymentModule.wallet.clearUserIdentificationCodes();
	});
	const clearAllCache = (0, ahooks.useMemoizedFn)(() => {
		paymentModule.wallet.clearAllCache();
	});
	const handleUserIdentificationCodesUpdated = (0, ahooks.useMemoizedFn)((data) => {
		setUserIdentificationCodes([...selectedWalletRef.current, ...data.userIdentificationCodes]);
	});
	const handleSearchIdentificationCodeCompleted = (0, ahooks.useMemoizedFn)((data) => {
		const { currentSearchResults, cachedSearchResults } = data;
		let formattedResults = currentSearchResults;
		if (walletPassEvaluator && currentSearchResults.length > 0 && totalAmount) formattedResults = walletPassEvaluator.searchVoucherFormat({
			vouchers: currentSearchResults,
			orderTotalAmount: totalAmount,
			products: products || []
		});
		let formattedCachedResults = cachedSearchResults || [];
		if (walletPassEvaluator && cachedSearchResults && cachedSearchResults.length > 0 && totalAmount) formattedCachedResults = walletPassEvaluator.searchVoucherFormat({
			vouchers: cachedSearchResults,
			orderTotalAmount: totalAmount,
			products: products || []
		});
		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 onOrderCreated = (0, ahooks.useMemoizedFn)(() => {
		var _paymentModule$wallet, _paymentModule$wallet2;
		setOrderInfo(checkoutModule.getOrderOriginalData());
		const recommendList = getCachedWalletRecommendList();
		const userIdentificationCodes = getCachedUserIdentificationCodes();
		const walletInitData = (paymentModule === null || paymentModule === void 0 || (_paymentModule$wallet = paymentModule.wallet) === null || _paymentModule$wallet === void 0 || (_paymentModule$wallet2 = _paymentModule$wallet.getStoredWalletInitData) === null || _paymentModule$wallet2 === void 0 ? void 0 : _paymentModule$wallet2.call(_paymentModule$wallet)) || {};
		const transformListData = walletInitData.transformList || userIdentificationCodes;
		const noApplicableVoucherData = walletInitData.noApplicableVoucher || [];
		const productsData = walletInitData.products || [];
		const initialData = [...recommendList, ...userIdentificationCodes];
		setWalletRecommendList(recommendList);
		setUserIdentificationCodes(userIdentificationCodes);
		setTransformList(transformListData);
		setNoApplicableVoucher(noApplicableVoucherData);
		setProducts(productsData);
		initialOrderedDataRef.current = initialData;
		if (!notSetWalletSelectRef.current) {
			setWalletSelect(recommendList);
			setSelectedVoucherIds(recommendList.map((item) => item.id));
			const select = paymentModule.wallet.formatWalletPassList2PreparePayments(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 {
			setWalletSelect([]);
			setSelectedVoucherIds([]);
			notSetWalletSelectRef.current = false;
			onSelectChange === null || onSelectChange === void 0 || onSelectChange([]);
		}
		const sortedDiscountList = sortDiscountListWithInitialOrder(shopDiscount.getDiscountList());
		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 customerName = (0, react.useMemo)(() => {
		var _orderInfo$original_o, _orderInfo$original_o2, _orderInfo$original_o3;
		if (!(orderInfo === null || orderInfo === void 0 || (_orderInfo$original_o = orderInfo.original_order_data) === null || _orderInfo$original_o === void 0 ? void 0 : _orderInfo$original_o.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) === 1) return _pisell_utils.locales.getText("wallet-pass-module-customer-name-walk-in");
		return (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]);
	const handleWalletCacheCleared = (0, ahooks.useMemoizedFn)((data) => {
		if (data.clearedTypes.includes("all")) setSearchIdentificationCodeList([]);
	});
	const handleWalletInitializationStarted = (0, ahooks.useMemoizedFn)(() => {
		setLoading(true);
	});
	const handleWalletInitializationCompleted = (0, ahooks.useMemoizedFn)(() => {
		setLoading(false);
	});
	const handleWalletInitializationFailed = (0, ahooks.useMemoizedFn)(() => {
		setLoading(false);
	});
	const handlePaymentStarted = (0, ahooks.useMemoizedFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (params) {
			if (params.paymentMethodCode !== "VOUCHER_BATCH" && Number(customAmount || 0) > 0) {
				notSetWalletSelectRef.current = true;
				yield checkoutModule.initWalletData({ order_wait_pay_amount: Number(customAmount) });
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	const handleWalletRecommendListUpdated = (0, ahooks.useMemoizedFn)((data) => {
		setWalletRecommendList(data.walletRecommendList);
	});
	(0, react.useEffect)(() => {
		if (!paymentModule) return;
		const wrappedHandlePaymentStarted = executeIfActive(handlePaymentStarted);
		const wrappedOnOrderCreated = executeIfActive(onOrderCreated);
		const wrappedHandleWalletRecommendListUpdated = executeIfActive(handleWalletRecommendListUpdated);
		const wrappedHandleUserIdentificationCodesUpdated = executeIfActive(handleUserIdentificationCodesUpdated);
		const wrappedHandleWalletCacheCleared = executeIfActive(handleWalletCacheCleared);
		const wrappedHandleSearchIdentificationCodeCompleted = executeIfActive(handleSearchIdentificationCodeCompleted);
		const wrappedHandleWalletInitializationStarted = executeIfActive(handleWalletInitializationStarted);
		const wrappedHandleWalletInitializationCompleted = executeIfActive(handleWalletInitializationCompleted);
		const wrappedHandleWalletInitializationFailed = executeIfActive(handleWalletInitializationFailed);
		paymentModule.effectsOn("onWalletRecommendListUpdated", wrappedHandleWalletRecommendListUpdated);
		checkoutModule.effectsOn("onPaymentStarted", wrappedHandlePaymentStarted);
		checkoutModule.effectsOn("onPaymentItemAdded", wrappedHandlePaymentStarted);
		paymentModule.effectsOn("onUserIdentificationCodesUpdated", wrappedHandleUserIdentificationCodesUpdated);
		paymentModule.effectsOn("onWalletCacheCleared", wrappedHandleWalletCacheCleared);
		paymentModule.effectsOn("onSearchIdentificationCodeCompleted", wrappedHandleSearchIdentificationCodeCompleted);
		checkoutModule.effectsOn("onWalletDataInitialized", wrappedOnOrderCreated);
		paymentModule.effectsOn("onWalletInitializationStarted", wrappedHandleWalletInitializationStarted);
		paymentModule.effectsOn("onWalletInitializationCompleted", wrappedHandleWalletInitializationCompleted);
		paymentModule.effectsOn("onWalletInitializationFailed", wrappedHandleWalletInitializationFailed);
		return () => {
			paymentModule.effectsOff("onWalletRecommendListUpdated", wrappedHandleWalletRecommendListUpdated);
			checkoutModule.effectsOff("onPaymentStarted", wrappedHandlePaymentStarted);
			checkoutModule.effectsOff("onPaymentItemAdded", wrappedHandlePaymentStarted);
			paymentModule.effectsOff("onUserIdentificationCodesUpdated", wrappedHandleUserIdentificationCodesUpdated);
			paymentModule.effectsOff("onWalletCacheCleared", wrappedHandleWalletCacheCleared);
			paymentModule.effectsOff("onSearchIdentificationCodeCompleted", wrappedHandleSearchIdentificationCodeCompleted);
			checkoutModule.effectsOff("onWalletDataInitialized", wrappedOnOrderCreated);
			paymentModule.effectsOff("onWalletInitializationStarted", wrappedHandleWalletInitializationStarted);
			paymentModule.effectsOff("onWalletInitializationCompleted", wrappedHandleWalletInitializationCompleted);
			paymentModule.effectsOff("onWalletInitializationFailed", wrappedHandleWalletInitializationFailed);
		};
	}, [paymentModule]);
	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) => {
		const select = paymentModule.wallet.formatWalletPassList2PreparePayments(selectedDetails).map((item) => ({
			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)((value) => {
		return paymentModule.wallet.searchIdentificationCodeAsync({
			code: value,
			prepare_payments: paymentModule.wallet.formatWalletPassList2PreparePayments(selectedWalletRef.current)
		});
	});
	const handleSelectWallet = (0, ahooks.useMemoizedFn)((value) => {
		setLoading(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)(() => {
		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 _pisellos$effects;
			notSetWalletSelectRef.current = true;
			const detail = shopDiscount.setDiscountSelected({ selectedList: selectedDiscountList.map((item) => ({
				discountId: item,
				isSelected: false
			})) });
			setDiscountList(sortDiscountListWithInitialOrder(detail.discountList));
			pisellos === null || pisellos === void 0 || (_pisellos$effects = pisellos.effects) === null || _pisellos$effects === void 0 || _pisellos$effects.emit("shopDiscount:onSelectedDiscountListChange", detail);
			return;
		}
		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)(() => {
		logger === null || logger === void 0 || logger.addLog({
			type: "info",
			title: "useWalletPass_handleBestSaving 开始调用",
			metadata: {}
		});
		setLoading(true);
		let hasGoodPass = false;
		let isBestDiscount = false;
		if (availableDiscountList.length) {
			hasGoodPass = true;
			showBestToastRef.current = true;
			shopDiscount.bestDiscount((result) => {
				if (require_utils$1.isSameContent(((result === null || result === void 0 ? void 0 : result.discountList) || []).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)((value, option) => {
		var _detail$discountList, _pisellos$effects2;
		setLoading(true);
		const isSelected = value.includes(option.id);
		const detail = shopDiscount.setDiscountSelected({
			discountId: option.id,
			isSelected
		});
		if (!(detail === null || detail === void 0 || (_detail$discountList = detail.discountList) === null || _detail$discountList === void 0 || (_detail$discountList = _detail$discountList.find((item) => item.id === option.id)) === null || _detail$discountList === void 0 ? void 0 : _detail$discountList.isSelected)) setLoading(false);
		setDiscountList(sortDiscountListWithInitialOrder(detail.discountList));
		pisellos === null || pisellos === void 0 || (_pisellos$effects2 = pisellos.effects) === null || _pisellos$effects2 === void 0 || _pisellos$effects2.emit("shopDiscount:onSelectedDiscountListChange", detail);
	});
	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 _ref3 = require_asyncToGenerator._asyncToGenerator(function* (value, index, data) {
				return true;
			});
			return function(_x3, _x4, _x5) {
				return _ref3.apply(this, arguments);
			};
		}()),
		handleBestSaving,
		handleSearchIdentificationCode,
		availableDiscountList,
		selectedDiscountList,
		handleSelectDiscount,
		customerName,
		fetchUserIdentificationCodes,
		getCachedWalletRecommendList,
		getCachedUserIdentificationCodes,
		clearWalletRecommendList,
		clearUserIdentificationCodes,
		clearAllCache,
		handleConfirmEditAmount
	};
};
//#endregion
exports.useWalletPass = useWalletPass;
