import { _asyncToGenerator } from "../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../../../hooks/useEngineContext.js";
import { postMessageToMiniProgram } from "../../../utils.js";
import { buildPayGroupStashToken, getPayGroupFromStorage } from "../../../payGroup.js";
import { Context } from "../../../model.js";
import { getPaymentResult, getStashData } from "./serve.js";
import { handleMiniProgram3DS } from "./3dsPayment.js";
import React, { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { copyToClipboard, locales } from "@pisell/utils";
import { Button, PisellContainer, PisellToast } from "@pisell/materials";
import "./index.less";
//#region src/components/pay/toC/PaymentMethods/components/MiniProgramWaitingPaymentModal/index.tsx
const maxRetryCount = 200;
/**
* 微信小程序内 H5：三方支付需复制链接到外部浏览器时的全屏等待页（PisellContainer + 移动端 Modal）
*/
const MiniProgramWaitingPaymentModal = (props, ref) => {
	var _context$appHelper, _utils$getStore;
	const { onAnotherPayment } = props;
	const { state, dispatch } = useContext(Context);
	const [open, setOpen] = useState(false);
	const [orderId, setOrderId] = useState("");
	const [paymentUrl, setPaymentUrl] = useState("");
	const [whyDetailOpen, setWhyDetailOpen] = useState(false);
	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 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 refreshNumber = useRef(0);
	const isPolling = useRef(true);
	const queryPaymentResult = useCallback(function() {
		var _ref = _asyncToGenerator(function* (orderId, paymentNumber) {
			if (!isPolling.current) return;
			try {
				const res = yield getPaymentResult({
					orderId,
					paymentNumber
				});
				if ((res === null || res === void 0 ? void 0 : res.payment_status) === "paid") {
					var _state$payCallback;
					(_state$payCallback = state.payCallback) === null || _state$payCallback === void 0 || _state$payCallback.call(state, { key: "success" });
					refreshNumber.current = 0;
					return;
				}
				if (refreshNumber.current >= maxRetryCount) {
					var _state$payCallback2;
					(_state$payCallback2 = state.payCallback) === null || _state$payCallback2 === void 0 || _state$payCallback2.call(state, { key: "fail" });
					return;
				}
				refreshNumber.current++;
				setTimeout(() => {
					queryPaymentResult(orderId, paymentNumber);
				}, 3e3);
			} catch (err) {
				console.log("miniProgramQueryPaymentResult_error", err);
				setTimeout(() => {
					queryPaymentResult(orderId, paymentNumber);
				}, 3e3);
			}
		});
		return function(_x, _x2) {
			return _ref.apply(this, arguments);
		};
	}(), [state.payCallback]);
	const getStashDataResult = useCallback(function() {
		var _ref2 = _asyncToGenerator(function* (orderId) {
			if (!isPolling.current) return;
			try {
				const { data } = yield getStashData(buildPayGroupStashToken(orderId));
				if (data === null || data === void 0 ? void 0 : data.pay_number) {
					refreshNumber.current = 0;
					queryPaymentResult(orderId, data.pay_number);
					return;
				}
				setTimeout(() => {
					getStashDataResult(orderId);
				}, 3e3);
			} catch (err) {
				console.log("miniProgramGetStashDataResult_error", err);
				setTimeout(() => {
					getStashDataResult(orderId);
				}, 3e3);
			}
		});
		return function(_x3) {
			return _ref2.apply(this, arguments);
		};
	}(), [queryPaymentResult]);
	const startPaymentPolling = useCallback((orderId) => {
		const payGroup = getPayGroupFromStorage(orderId);
		const payNumber = payGroup === null || payGroup === void 0 ? void 0 : payGroup.pay_number;
		if (payNumber) queryPaymentResult(orderId, payNumber);
		else getStashDataResult(orderId);
	}, [queryPaymentResult, getStashDataResult]);
	const init = useCallback(function() {
		var _ref3 = _asyncToGenerator(function* (val) {
			if (!!(val === null || val === void 0 ? void 0 : val.open)) {
				isPolling.current = true;
				refreshNumber.current = 0;
				setOpen(!!val.open);
				setPaymentUrl(val.paymentUrl || "");
				setOrderId(val.orderId || "");
				const orderId = val.orderId;
				if (orderId) startPaymentPolling(orderId);
			}
		});
		return function(_x4) {
			return _ref3.apply(this, arguments);
		};
	}(), [startPaymentPolling]);
	const handleCopy = useCallback(_asyncToGenerator(function* () {
		if (!paymentUrl) return;
		try {
			var _state$miniProgramPay;
			let resultUrl = paymentUrl;
			const threeDSPayParams = (_state$miniProgramPay = state.miniProgramPayment) === null || _state$miniProgramPay === void 0 ? void 0 : _state$miniProgramPay.threeDSPayParams;
			if (threeDSPayParams) {
				const res = yield handleMiniProgram3DS(paymentUrl, {
					threeDSPayParams,
					utils,
					locales,
					config,
					dvaStore,
					startPaymentPolling
				});
				if (res) resultUrl = res;
			}
			yield copyToClipboard(resultUrl);
			PisellToast({ content: locales.getText("tocPay.text.miniProgram.waitingPay.copySuccess") });
		} catch (_unused) {}
	}), [
		paymentUrl,
		state,
		utils,
		config,
		dvaStore,
		startPaymentPolling
	]);
	const handleClose = useCallback(() => {
		isPolling.current = false;
		setOpen(false);
		dispatch({
			type: "setMiniProgramPayment",
			payload: { open: false }
		});
	}, []);
	const goHome = useCallback(() => {
		postMessageToMiniProgram("goHome");
	}, []);
	const handleHavePaid = useCallback(() => {
		PisellToast({ content: locales.getText("tocPay.text.miniProgram.waitingPay.checkStatus") });
	}, []);
	const handleAnother = useCallback(() => {
		isPolling.current = false;
		PisellToast({
			content: locales.getText("tocPay.text.miniProgram.waitingPay.redirect"),
			duration: 2
		});
		setTimeout(() => {
			handleClose();
			onAnotherPayment && (onAnotherPayment === null || onAnotherPayment === void 0 || onAnotherPayment());
		}, 2e3);
	}, []);
	useEffect(() => {
		return () => {
			isPolling.current = false;
		};
	}, []);
	useImperativeHandle(ref, () => ({ init }), [init]);
	const headerRender = useMemo(() => {
		return /* @__PURE__ */ React.createElement("div", { className: "mini-program-waiting-pay-header" }, /* @__PURE__ */ React.createElement("div", {
			className: "header-icon",
			onClick: goHome
		}, /* @__PURE__ */ React.createElement("svg", {
			width: "22",
			height: "22",
			viewBox: "0 0 24 24",
			fill: "none",
			stroke: "currentColor",
			"stroke-width": "2",
			"stroke-linecap": "round",
			"stroke-linejoin": "round"
		}, /* @__PURE__ */ React.createElement("path", { d: "M3 12l9-9 9 9M5 10v10h4v-6h6v6h4V10" }))), /* @__PURE__ */ React.createElement("span", { className: "header-title" }, locales.getText("tocPay.text.miniProgram.waitingPay.title")));
	}, []);
	if (!open) return null;
	return /* @__PURE__ */ React.createElement(PisellContainer, {
		renderType: "modal",
		props: {
			platform: "h5",
			open,
			footer: false,
			closable: false,
			maskClosable: false,
			bodyStyle: {
				padding: "0 20px",
				height: "100%"
			},
			onCancel: handleClose,
			forceRender: true,
			title: headerRender,
			cancelVisible: false,
			wrapClassName: "mini-program-waiting-pay-modal-wrap"
		}
	}, /* @__PURE__ */ React.createElement("div", { className: "mini-program-waiting-pay-content" }, /* @__PURE__ */ React.createElement("div", { className: "hero" }, /* @__PURE__ */ React.createElement("svg", {
		className: "hero-icon",
		viewBox: "0 0 64 64",
		fill: "none",
		stroke: "currentColor",
		"stroke-width": "3",
		"stroke-linecap": "round",
		"stroke-linejoin": "round"
	}, /* @__PURE__ */ React.createElement("rect", {
		x: "8",
		y: "12",
		width: "48",
		height: "40",
		rx: "5"
	}), /* @__PURE__ */ React.createElement("line", {
		x1: "8",
		y1: "22",
		x2: "56",
		y2: "22"
	}), /* @__PURE__ */ React.createElement("circle", {
		cx: "14",
		cy: "17",
		r: "1.2",
		fill: "currentColor",
		stroke: "none"
	}), /* @__PURE__ */ React.createElement("circle", {
		cx: "18",
		cy: "17",
		r: "1.2",
		fill: "currentColor",
		stroke: "none"
	}), /* @__PURE__ */ React.createElement("circle", {
		cx: "22",
		cy: "17",
		r: "1.2",
		fill: "currentColor",
		stroke: "none"
	}), /* @__PURE__ */ React.createElement("path", { d: "M20 34 L28 42 L44 28" })), /* @__PURE__ */ React.createElement("h1", { className: "hero-title" }, locales.getText("tocPay.text.miniProgram.waitingPay.finishTip")), /* @__PURE__ */ React.createElement("p", { className: "hero-subtitle" }, locales.getText("tocPay.text.miniProgram.waitingPay.finishDesc"))), /* @__PURE__ */ React.createElement("div", { className: "action-block" }, /* @__PURE__ */ React.createElement("div", { className: "link-preview" }, /* @__PURE__ */ React.createElement("svg", {
		className: "link-preview-icon",
		viewBox: "0 0 24 24",
		fill: "none",
		stroke: "currentColor",
		"stroke-width": "2",
		"stroke-linecap": "round",
		"stroke-linejoin": "round"
	}, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" })), /* @__PURE__ */ React.createElement("span", { className: "link-preview-text" }, paymentUrl)), /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		onClick: handleCopy,
		className: "btn-primary"
	}, /* @__PURE__ */ React.createElement("svg", {
		id: "copyBtnIcon",
		width: "20",
		height: "20",
		viewBox: "0 0 24 24",
		fill: "none",
		stroke: "currentColor",
		"stroke-width": "2",
		"stroke-linecap": "round",
		"stroke-linejoin": "round"
	}, /* @__PURE__ */ React.createElement("rect", {
		x: "9",
		y: "9",
		width: "13",
		height: "13",
		rx: "2",
		ry: "2"
	}), /* @__PURE__ */ React.createElement("path", { d: "M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" })), /* @__PURE__ */ React.createElement("span", null, locales.getText("tocPay.text.miniProgram.waitingPay.copy")))), /* @__PURE__ */ React.createElement("div", { className: "status-bar-waiting" }, /* @__PURE__ */ React.createElement("div", { class: "spinner" }), /* @__PURE__ */ React.createElement("span", { className: "status-bar-text" }, locales.getText("tocPay.text.miniProgram.waitingPay.statusText"))), /* @__PURE__ */ React.createElement("div", { className: "footer-help" }, /* @__PURE__ */ React.createElement("div", { className: "footer-help-links" }, /* @__PURE__ */ React.createElement("a", { onClick: handleHavePaid }, locales.getText("tocPay.text.miniProgram.waitingPay.havePaid")), /* @__PURE__ */ React.createElement("a", { onClick: handleAnother }, locales.getText("tocPay.text.miniProgram.waitingPay.another"))), /* @__PURE__ */ React.createElement("div", { className: "why-toggle" }, /* @__PURE__ */ React.createElement("span", {
		className: "why-toggle-link",
		onClick: () => setWhyDetailOpen(!whyDetailOpen)
	}, locales.getText("tocPay.text.miniProgram.waitingPay.why")), whyDetailOpen && /* @__PURE__ */ React.createElement("div", { className: "why-detail" }, locales.getText("tocPay.text.miniProgram.waitingPay.whyDetail"))))));
};
var MiniProgramWaitingPaymentModal_default = forwardRef(MiniProgramWaitingPaymentModal);
//#endregion
export { MiniProgramWaitingPaymentModal_default as default };
