import { _asyncToGenerator } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../../hooks/useEngineContext.js";
import { isMiniProgram } from "../../utils.js";
import { getPayGroupParamsFromStorage, setPayNumber } from "../../payGroup.js";
import { Context } from "../../model.js";
import { fastPayNew } from "./List/serve.js";
import List_default from "./List/index.js";
import Add_default from "./Add/index.js";
import { preCheckEnrollment } from "./tds2.js";
import TDSPay_default from "./TDSPay/index.js";
import TDSErrorModal from "./components/TDSErrorModal/index.js";
import React, { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { PisellToast } from "@pisell/materials";
import "./index.less";
//#region src/components/pay/toC/PaymentMethods/MWCreditCard/index.tsx
/**
* @title: 信用卡支付
* @description: 整合信用卡列表、添加卡、3DS 验证，
*              在 onChange/onAdd 时前置执行 3DS 预检查，
*              失败时弹出 TDSErrorModal 阻断支付。
* @param {MWCreditCardProps} props
* @param {any} ref
* @return {*}
*/
const MWCreditCard = (props, ref) => {
	var _context$appHelper, _utils$getStore;
	const MWCreditCardListRef = useRef();
	const AddMWCreditCardRef = useRef();
	const TDSPayRef = useRef();
	const context = useEngineContext();
	const utils = context.appHelper.utils || {};
	const { config } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.constants) || {};
	const { token, interaction } = utils;
	const dvaStore = utils === null || utils === void 0 || (_utils$getStore = utils.getStore) === null || _utils$getStore === void 0 || (_utils$getStore = _utils$getStore.call(utils)) === null || _utils$getStore === void 0 ? void 0 : _utils$getStore.getState();
	const [order, setOrder] = useState(null);
	const [tdsErrorVisible, setTdsErrorVisible] = useState(false);
	const [bankVerifyFailVisible, setBankVerifyFailVisible] = useState(false);
	const [loading, setLoading] = useState(false);
	const { state, dispatch } = useContext(Context);
	/**
	* @title: 初始化
	* @description: 展示信用卡列表
	*/
	const init = function() {
		var _ref = _asyncToGenerator(function* (res) {
			var _MWCreditCardListRef$;
			setOrder(res.order);
			(_MWCreditCardListRef$ = MWCreditCardListRef.current) === null || _MWCreditCardListRef$ === void 0 || _MWCreditCardListRef$.init(order);
		});
		return function init(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* @title: 关闭所有弹窗
	* @description: 关闭 List + Add 弹窗（供"使用其他支付方式"按钮调用）
	*/
	const closeAll = () => {
		var _MWCreditCardListRef$2, _AddMWCreditCardRef$c;
		(_MWCreditCardListRef$2 = MWCreditCardListRef.current) === null || _MWCreditCardListRef$2 === void 0 || _MWCreditCardListRef$2.close();
		(_AddMWCreditCardRef$c = AddMWCreditCardRef.current) === null || _AddMWCreditCardRef$c === void 0 || _AddMWCreditCardRef$c.close();
	};
	const openCopyLinkModal = (params, data, orderId) => {
		var _dvaStore$core;
		const locale = ((_dvaStore$core = dvaStore.core) === null || _dvaStore$core === void 0 ? void 0 : _dvaStore$core.translateLocale) || "en";
		const payCode = data === null || data === void 0 ? void 0 : data.pay_code;
		const payUrl = `${config === null || config === void 0 ? void 0 : config.domain}/${locale}/miniapp-payment/${payCode}?locale=${locale}&order_id=${orderId}`;
		if (!(config === null || config === void 0 ? void 0 : config.domain)) return;
		dispatch({
			type: "setMiniProgramPayment",
			payload: {
				open: true,
				paymentUrl: payUrl,
				threeDSPayParams: params
			}
		});
	};
	/**
	* @title: 已保存卡的 3DS 验证（含预检查）
	* @description: 选择已保存卡时，先调用 fastPayNew API，
	*              若返回 type=3ds 则执行 preCheckEnrollment 前置检查，
	*              失败时弹出 TDSErrorModal；成功时传入 TDSPay.init。
	* @param {any} card 已保存的卡信息
	*/
	const fastPay = function() {
		var _ref2 = _asyncToGenerator(function* (card) {
			try {
				var _utils$Toast, _utils$Toast$loading, _state$payGroup, _state$payGroup2, _state$payGroup3, _token$get;
				setLoading(true);
				utils === null || utils === void 0 || (_utils$Toast = utils.Toast) === null || _utils$Toast === void 0 || (_utils$Toast$loading = _utils$Toast.loading) === null || _utils$Toast$loading === void 0 || _utils$Toast$loading.call(_utils$Toast, locales.getText("tocPay.text.checkingCard"), 0, void 0, true);
				const params = getPayGroupParamsFromStorage((_state$payGroup = state.payGroup) === null || _state$payGroup === void 0 ? void 0 : _state$payGroup.order_id, { card_id: card.id });
				if (!params) {
					var _state$payCallback;
					(_state$payCallback = state.payCallback) === null || _state$payCallback === void 0 || _state$payCallback.call(state, {
						key: "fail",
						data: {
							res: card,
							fn: "MWCreditCard.fastPay.noParams",
							message: locales.getText("tocPay.text.getParamsFail")
						}
					});
					return;
				}
				const { data } = yield fastPayNew({
					order_id: (_state$payGroup2 = state.payGroup) === null || _state$payGroup2 === void 0 ? void 0 : _state$payGroup2.order_id,
					params
				});
				yield setPayNumber((_state$payGroup3 = state.payGroup) === null || _state$payGroup3 === void 0 ? void 0 : _state$payGroup3.order_id, data === null || data === void 0 ? void 0 : data.pay_number, token === null || token === void 0 || (_token$get = token.get) === null || _token$get === void 0 ? void 0 : _token$get.call(token));
				if ((data === null || data === void 0 ? void 0 : data.type) === "token") {
					var _TDSPayRef$current;
					(_TDSPayRef$current = TDSPayRef.current) === null || _TDSPayRef$current === void 0 || _TDSPayRef$current.init(card, order, data);
					return;
				}
				if ((data === null || data === void 0 ? void 0 : data.type) === "3ds") {
					var _TDSPayRef$current2;
					if (isMiniProgram(interaction)) {
						var _state$payGroup4;
						const _params = {
							order_id: (_state$payGroup4 = state.payGroup) === null || _state$payGroup4 === void 0 ? void 0 : _state$payGroup4.order_id,
							params,
							isAddCard: false
						};
						openCopyLinkModal(_params, data, _params === null || _params === void 0 ? void 0 : _params.order_id);
						return;
					}
					(_TDSPayRef$current2 = TDSPayRef.current) === null || _TDSPayRef$current2 === void 0 || _TDSPayRef$current2.init(card, order, data);
					return;
				}
			} catch (e) {
				if ((e === null || e === void 0 ? void 0 : e.code) === 700500) setTdsErrorVisible(true);
				else PisellToast({
					content: (e === null || e === void 0 ? void 0 : e.message) || "",
					duration: 2
				});
			} finally {
				var _utils$Toast2, _utils$Toast2$hide;
				setLoading(false);
				utils === null || utils === void 0 || (_utils$Toast2 = utils.Toast) === null || _utils$Toast2 === void 0 || (_utils$Toast2$hide = _utils$Toast2.hide) === null || _utils$Toast2$hide === void 0 || _utils$Toast2$hide.call(_utils$Toast2);
			}
		});
		return function fastPay(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	/**
	* @title: 新卡支付（含 3DS 预检查）
	* @description: 添加新卡时，先构建 cardInfo 并执行 preCheckEnrollment，
	*              失败时弹出 TDSErrorModal；成功时传入 TDSPay.init。
	* @param {any} res 新卡表单数据
	*/
	const onCreate = function() {
		var _ref3 = _asyncToGenerator(function* (res) {
			try {
				var _utils$Toast3, _utils$Toast3$loading, _state$payGroup5, _state$payGroup6, _token$get2, _TDSPayRef$current3;
				setLoading(true);
				utils === null || utils === void 0 || (_utils$Toast3 = utils.Toast) === null || _utils$Toast3 === void 0 || (_utils$Toast3$loading = _utils$Toast3.loading) === null || _utils$Toast3$loading === void 0 || _utils$Toast3$loading.call(_utils$Toast3, locales.getText("tocPay.text.checkingCard"), 0, void 0, true);
				let _cardInfo = {
					card_name: res.card_name,
					card_number: res.card_number,
					card_expiry_month: res.date.format("MM"),
					card_expiry_year: res.date.format("YY"),
					card_ccv: res.card_ccv,
					is_save: res.is_save ? 1 : 0
				};
				_cardInfo = getPayGroupParamsFromStorage((_state$payGroup5 = state.payGroup) === null || _state$payGroup5 === void 0 ? void 0 : _state$payGroup5.order_id, _cardInfo);
				if (!_cardInfo) {
					var _state$payCallback2;
					(_state$payCallback2 = state.payCallback) === null || _state$payCallback2 === void 0 || _state$payCallback2.call(state, {
						key: "fail",
						data: {
							_cardInfo,
							message: locales.getText("tocPay.text.getParamsFail"),
							fn: "MWCreditCard.onCreate.noCardInfo"
						}
					});
					return;
				}
				const preCheckData = yield preCheckEnrollment((_state$payGroup6 = state.payGroup) === null || _state$payGroup6 === void 0 ? void 0 : _state$payGroup6.order_id, _cardInfo, token === null || token === void 0 || (_token$get2 = token.get) === null || _token$get2 === void 0 ? void 0 : _token$get2.call(token));
				if ((preCheckData === null || preCheckData === void 0 ? void 0 : preCheckData.type) === "3ds") {
					if (isMiniProgram(interaction)) {
						var _state$payGroup7;
						const _params = {
							order_id: (_state$payGroup7 = state.payGroup) === null || _state$payGroup7 === void 0 ? void 0 : _state$payGroup7.order_id,
							params: _cardInfo,
							isAddCard: true
						};
						openCopyLinkModal(_params, preCheckData, _params === null || _params === void 0 ? void 0 : _params.order_id);
						return;
					}
				}
				(_TDSPayRef$current3 = TDSPayRef.current) === null || _TDSPayRef$current3 === void 0 || _TDSPayRef$current3.init(res, order, preCheckData);
			} catch (e) {
				if ((e === null || e === void 0 ? void 0 : e.code) === 700500) setTdsErrorVisible(true);
				else PisellToast({
					content: (e === null || e === void 0 ? void 0 : e.message) || "",
					duration: 2
				});
			} finally {
				var _utils$Toast4, _utils$Toast4$hide;
				setLoading(false);
				utils === null || utils === void 0 || (_utils$Toast4 = utils.Toast) === null || _utils$Toast4 === void 0 || (_utils$Toast4$hide = _utils$Toast4.hide) === null || _utils$Toast4$hide === void 0 || _utils$Toast4$hide.call(_utils$Toast4);
			}
		});
		return function onCreate(_x3) {
			return _ref3.apply(this, arguments);
		};
	}();
	/**
	* @title: TDSPay 支付回调包装
	* @description: 拦截 bankVerifyFailed 信号弹出银行验证失败弹窗，
	*              其余 key 正常透传给全局 payCallback。
	* @param {any} res TDSPay 回调结果
	*/
	const handleTDSPayChange = (res) => {
		var _state$payCallback3;
		if ((res === null || res === void 0 ? void 0 : res.key) === "bankVerifyFailed") {
			setBankVerifyFailVisible(true);
			return;
		}
		(_state$payCallback3 = state.payCallback) === null || _state$payCallback3 === void 0 || _state$payCallback3.call(state, res);
	};
	/**
	* @title: TDS 错误弹窗 - 更换卡片
	* @description: 关闭错误弹窗，留在选择卡片页面
	*/
	const handleUseAnotherCard = () => {
		setTdsErrorVisible(false);
		setBankVerifyFailVisible(false);
	};
	/**
	* @title: TDS 错误弹窗 - 使用其他支付方式
	* @description: 关闭所有弹窗，返回支付方式列表
	*/
	const handleUseAnotherPayment = () => {
		setTdsErrorVisible(false);
		setBankVerifyFailVisible(false);
		closeAll();
	};
	/**
	* @title: TDS 错误弹窗 - 稍后支付
	* @description: 关闭弹窗，触发 payCallback cancel 跳转至订单详情页
	*/
	const handlePayLater = () => {
		var _state$payCallback4;
		setTdsErrorVisible(false);
		setBankVerifyFailVisible(false);
		closeAll();
		(_state$payCallback4 = state.payCallback) === null || _state$payCallback4 === void 0 || _state$payCallback4.call(state, { key: "cancel" });
	};
	useImperativeHandle(ref, () => ({
		init,
		closeAll
	}));
	useEffect(() => {}, []);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(List_default, {
		ref: MWCreditCardListRef,
		onAdd: () => {
			var _AddMWCreditCardRef$c2;
			(_AddMWCreditCardRef$c2 = AddMWCreditCardRef.current) === null || _AddMWCreditCardRef$c2 === void 0 || _AddMWCreditCardRef$c2.init();
		},
		onChange: fastPay,
		btnLoading: loading
	}), /* @__PURE__ */ React.createElement(Add_default, {
		ref: AddMWCreditCardRef,
		onCreate,
		shopName: props.shopName,
		btnLoading: loading
	}), /* @__PURE__ */ React.createElement(TDSPay_default, {
		ref: TDSPayRef,
		onChange: handleTDSPayChange,
		closeAll
	}), /* @__PURE__ */ React.createElement(TDSErrorModal, {
		open: tdsErrorVisible,
		type: "tds-not-supported",
		shopPhone: props.shopPhone,
		shopEmail: props.shopEmail,
		onUseAnotherCard: handleUseAnotherCard,
		onUseAnotherPayment: handleUseAnotherPayment,
		onPayLater: handlePayLater
	}), /* @__PURE__ */ React.createElement(TDSErrorModal, {
		open: bankVerifyFailVisible,
		type: "bank-verify-failed",
		shopPhone: props.shopPhone,
		shopEmail: props.shopEmail,
		onUseAnotherCard: handleUseAnotherCard,
		onUseAnotherPayment: handleUseAnotherPayment,
		onPayLater: handlePayLater
	}));
};
var MWCreditCard_default = forwardRef(MWCreditCard);
//#endregion
export { MWCreditCard_default as default };
