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 useEngineContext from "../../../../../hooks/useEngineContext.js";
import pinVerifyModal_default from "../../../../pinVerifyModal/index.js";
import MultiModeSearch_default from "./MultiModeSearch/index.js";
import { searchMachineCodeList, searchWalletCode } from "./serve.js";
import { formatWalletPassList2PreparePayments } from "../../utils.js";
import { formatMachineCodeServer2CardList, formatWalletPassWithUniquePaymentNumber, getIsWalletCode } from "./utils.js";
import List_default from "./List/index.js";
import React, { forwardRef, memo, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { locales, uniqueByKey } from "@pisell/utils";
import { PisellModal, PisellText, PisellToast } from "@pisell/materials";
import { useMemoizedFn } from "ahooks";
import { InfoCircleOutlined } from "@ant-design/icons";
import "./index.less";
//#region src/components/pay/toC/PaymentMethods/WalletPass/index.tsx
const { Amount } = PisellText;
var WalletPass_default = memo(forwardRef((props, ref) => {
	var _context$appHelper, _context$appHelper2, _context$appHelper2$g, _searchSelectData$ids;
	const { onWalletPassChange, walletPass, walletSetting, orderDetail, total_amount } = props;
	const context = useEngineContext();
	const { walletPassEvaluator } = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const { detail } = orderDetail;
	const isWalletCode = context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.businessUtils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getAppByModal) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2, "wallet");
	const { cards: recommended, transformList, noApplicableVoucher } = walletPass;
	/** 当前选中的券ID列表（按选中顺序） */
	const [selectedVoucherIds, setSelectedVoucherIds] = useState([]);
	/** 当前 walletPass信息 弹窗操作时都在内部进行，点击 redeem时同步到外层 */
	const [currentWalletPass, setCurrentWalletPass] = useState(walletPass);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	/** 搜索 modal */
	const [searchOpen, setSearchOpen] = useState(false);
	/** 搜索后添加的walletPass */
	const [addList, setAddList] = useState([]);
	/** 当前order信息 */
	const [order, setOrder] = useState(null);
	/** 当前搜索modal内list数据 */
	const [searchData, setSearchData] = useState([]);
	/** 当前搜索modal内选中数据 */
	const [searchSelectData, setSearchSelectData] = useState({
		ids: [],
		details: []
	});
	/** 是否默认选中 搜索时默认选中 列表select变更更新列表时不默认选中 */
	const isAutoSelect = useRef(false);
	/** 当前搜索框搜索值 */
	const searchValRef = useRef(null);
	const pinVerifyModalRef = useRef(null);
	const allVouchersForCalculation = useMemo(() => {
		return [...transformList || [], ...addList || []];
	}, [transformList, addList]);
	const selectedVouchers = useMemo(() => {
		return selectedVoucherIds.map((id) => allVouchersForCalculation.find((v) => v.id === id)).filter(Boolean);
	}, [selectedVoucherIds, allVouchersForCalculation]);
	const { displayVouchers, displayOtherVouchers, selectedWithDetails, totalDeduction } = useMemo(() => {
		if (!walletPassEvaluator || !allVouchersForCalculation.length || !(order === null || order === void 0 ? void 0 : order.total_amount)) return {
			displayVouchers: [...transformList || [], ...noApplicableVoucher || []],
			displayOtherVouchers: addList || [],
			selectedWithDetails: [],
			totalDeduction: 0
		};
		if (selectedVouchers.length === 0) return {
			displayVouchers: [...transformList || [], ...noApplicableVoucher || []],
			displayOtherVouchers: addList || [],
			selectedWithDetails: [],
			totalDeduction: 0
		};
		const result = walletPassEvaluator.recalculateVouchers(allVouchersForCalculation, selectedVouchers, order.total_amount, detail || []);
		const currentCustomerVouchers = [];
		const otherCustomerVouchers = [];
		result.allWithUpdatedStatus.forEach((voucher) => {
			if (voucher.customer_id === (order === null || order === void 0 ? void 0 : order.customer_id)) currentCustomerVouchers.push(voucher);
			else otherCustomerVouchers.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,
		addList,
		noApplicableVoucher,
		order === null || order === void 0 ? void 0 : order.total_amount,
		order === null || order === void 0 ? void 0 : order.customer_id,
		detail,
		walletPassEvaluator
	]);
	const prepare_payments = useMemo(() => {
		return formatWalletPassList2PreparePayments(uniqueByKey((selectedWithDetails || []).concat(searchSelectData.details), "id"));
	}, [selectedWithDetails, searchSelectData]);
	const selectValue = useMemo(() => {
		return selectedVoucherIds;
	}, [selectedVoucherIds]);
	useEffect(() => {
		if (recommended && recommended.length > 0) setSelectedVoucherIds(recommended.map((v) => v.id));
	}, [recommended]);
	/**
	*  搜索结果list弹窗列表选中发生变更时 重新获取接口
	*/
	useEffect(() => {
		if ((order === null || order === void 0 ? void 0 : order.order_id) && searchValRef.current) searchList(searchValRef.current, true);
	}, [order === null || order === void 0 ? void 0 : order.order_id, searchSelectData]);
	const init = function() {
		var _ref = _asyncToGenerator(function* (res) {
			if (!res) return;
			setOrder(res);
			setOpen(true);
			setCurrentWalletPass(walletPass);
			if (recommended && recommended.length > 0) setSelectedVoucherIds(recommended.map((v) => v.id));
		});
		return function init(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* 获取搜索弹窗list数据
	* @param val
	*/
	const searchList = function() {
		var _ref2 = _asyncToGenerator(function* ({ code, customer_pin_key }, isSelectChange) {
			if (!(order === null || order === void 0 ? void 0 : order.order_id)) return;
			setLoading(true);
			try {
				var _order$_order;
				const baseResult = yield searchMachineCodeList({
					order_id: order.order_id,
					code,
					prepare_payments,
					sale_channel: ((_order$_order = order._order) === null || _order$_order === void 0 ? void 0 : _order$_order.sale_channel) || "online-store",
					customer_pin_key
				});
				if (!baseResult) {
					if (!isSelectChange) PisellToast({ content: locales.getText("tocPay.text.walletSearchEmpty") });
					return;
				}
				if (isSelectChange && !searchValRef.current) return;
				let result = walletPassEvaluator.searchVoucherFormat({
					vouchers: baseResult,
					orderTotalAmount: order.total_amount,
					products: detail
				});
				setSearchData(formatMachineCodeServer2CardList([...searchSelectData.details, ...result], searchSelectData.ids));
				if (result.length) {
					if (result.length === 1 && result[0].unified_available_status && isAutoSelect.current) setSearchSelectData({
						ids: [result[0].id],
						details: result
					});
					setSearchOpen(true);
					searchValRef.current = {
						code,
						customer_pin_key
					};
				}
			} finally {
				setLoading(false);
			}
		});
		return function searchList(_x2, _x3) {
			return _ref2.apply(this, arguments);
		};
	}();
	const searchWalletCodeFn = function() {
		var _ref3 = _asyncToGenerator(function* (val) {
			setLoading(true);
			try {
				var _pinVerifyModalRef$cu;
				const result = yield searchWalletCode({
					code: val,
					with_customer: 1
				});
				console.log(result, "result");
				if (!result) {
					searchList({ code: val });
					return;
				}
				(_pinVerifyModalRef$cu = pinVerifyModalRef.current) === null || _pinVerifyModalRef$cu === void 0 || _pinVerifyModalRef$cu.open({
					wallet_code: result.code,
					wallet_detail_id: result.id,
					failed_count: result.failed_count,
					check_max_count: result.check_max_count,
					customer: result.customer
				});
			} finally {
				setLoading(false);
			}
		});
		return function searchWalletCodeFn(_x4) {
			return _ref3.apply(this, arguments);
		};
	}();
	const handleSearch = useMemoizedFn((val) => {
		if (!val || searchOpen) return;
		isAutoSelect.current = true;
		if (getIsWalletCode(val) && isWalletCode) searchWalletCodeFn(val);
		else searchList({ code: val });
	});
	useImperativeHandle(ref, () => ({ init }));
	const handleSearchModalClose = () => {
		setSearchOpen(false);
		searchValRef.current = null;
		setSearchSelectData({
			ids: [],
			details: []
		});
	};
	const handleSelectOk = () => {
		const otherCustomerSearchVouchers = searchSelectData.details.filter((item) => item.customer_id !== (order === null || order === void 0 ? void 0 : order.customer_id));
		setAddList((prevState) => {
			return uniqueByKey([...prevState, ...otherCustomerSearchVouchers], "id");
		});
		setSelectedVoucherIds(uniqueByKey([...selectedWithDetails || [], ...searchSelectData.details], "id").map((v) => v.id));
		handleSearchModalClose();
	};
	const handleAddChange = useMemoizedFn((val, details) => {
		isAutoSelect.current = false;
		setSearchSelectData({
			ids: val,
			details: details.map((item) => item.originData)
		});
	});
	const handleSelectChange = (val, details, type) => {
		setSelectedVoucherIds(val);
	};
	const handleRedeem = () => {
		onWalletPassChange === null || onWalletPassChange === void 0 || onWalletPassChange(formatWalletPassWithUniquePaymentNumber(_objectSpread2(_objectSpread2({}, currentWalletPass), {}, {
			cards: selectedWithDetails,
			amount: totalDeduction
		})));
		setOpen(false);
	};
	const handleWalletClose = () => {
		setOpen(false);
		setCurrentWalletPass(walletPass);
	};
	const handleOtherChange = useMemoizedFn((val, valDetail) => {
		handleSelectChange(val, valDetail, "other");
	});
	const handleCurrentChange = useMemoizedFn((val, valDetail) => {
		handleSelectChange(val, valDetail, "current");
	});
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PisellModal, {
		title: /* @__PURE__ */ React.createElement("div", null, walletSetting.name),
		open,
		onCancel: () => handleWalletClose(),
		cancelVisible: false,
		destroyOnClose: true,
		okText: /* @__PURE__ */ React.createElement("div", null, locales.getText("tocPay.text.redeem"), " ", /* @__PURE__ */ React.createElement(Amount, { value: totalDeduction })),
		onOk: handleRedeem
	}, /* @__PURE__ */ React.createElement("div", {
		className: "",
		style: { marginTop: 24 }
	}, /* @__PURE__ */ React.createElement(MultiModeSearch_default, { onChange: handleSearch }), /* @__PURE__ */ React.createElement("div", { className: "wallet-pass-modal-multi-selection-available" }, /* @__PURE__ */ React.createElement("div", { className: "wallet-pass-modal-multi-selection-available-title" }, /* @__PURE__ */ React.createElement(InfoCircleOutlined, { className: "wallet-pass-modal-multi-selection-available-title-icon" }), locales.getText("tocPay.text.multipleSelectionAvailable")), /* @__PURE__ */ React.createElement("div", { className: "wallet-pass-modal-multi-selection-available-desc" }, locales.getText("tocPay.text.youCanSelectMultipleWalletPassesToCombineForPayment")(walletSetting.name))), displayOtherVouchers.length > 0 && /* @__PURE__ */ React.createElement(List_default, {
		walletSetting,
		data: formatMachineCodeServer2CardList(displayOtherVouchers, selectValue),
		title: locales.getText("tocPay.text.couponCodesAdded"),
		onChange: handleOtherChange,
		value: selectValue,
		loading,
		onChangeDebounce: true
	}), /* @__PURE__ */ React.createElement(List_default, {
		walletSetting,
		title: walletSetting.name,
		onChange: handleCurrentChange,
		data: formatMachineCodeServer2CardList(displayVouchers, selectValue),
		value: selectValue,
		loading
	}))), /* @__PURE__ */ React.createElement(PisellModal, {
		title: /* @__PURE__ */ React.createElement("div", null, locales.getText("tocPay.text.searchResult")),
		mobileModalHeight: "90%",
		destroyOnClose: true,
		open: searchOpen,
		onCancel: () => handleSearchModalClose(),
		cancelVisible: false,
		okText: locales.getText("tocPay.text.select"),
		onOk: handleSelectOk,
		okButtonProps: { disabled: ((_searchSelectData$ids = searchSelectData.ids) === null || _searchSelectData$ids === void 0 ? void 0 : _searchSelectData$ids.length) === 0 }
	}, /* @__PURE__ */ React.createElement("div", {
		className: "",
		style: { marginTop: 24 }
	}, /* @__PURE__ */ React.createElement(List_default, {
		walletSetting,
		data: searchData,
		value: searchSelectData.ids,
		onChange: handleAddChange,
		loading
	}))), /* @__PURE__ */ React.createElement(pinVerifyModal_default, {
		ref: pinVerifyModalRef,
		onSuccess: (params) => {
			searchList({ customer_pin_key: params === null || params === void 0 ? void 0 : params.customer_pin_key });
		}
	}));
}));
//#endregion
export { WalletPass_default as default };
