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 { request } from "../../../utils/index.js";
import { StatusEnum } from "../const.js";
import { LinklyActionStatus } from "./const.js";
import { getPayParams } from "../helper.js";
import { updateCustom, updateNextStep, updateState, useContextData, useDispatch } from "../store/index.js";
import { useFail, useStoreRef } from "../hooks.js";
import payLog from "../utils/payLog.js";
import step_default from "../component/step/step.js";
import { useLinklyCancel, useLinklyPayOrRefund, useLinklySignature } from "./hooks/normal.js";
import { useTimeResultQuery } from "./hooks/useTimeQuery.js";
import React, { useEffect, useRef } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
//#region src/components/eftposPay/linkly/index.tsx
const Linkly = ({ api, onChange }) => {
	const utils = useEngineContext().appHelper.utils || {};
	request.setRequest(utils === null || utils === void 0 ? void 0 : utils.request);
	const { custom, status } = useContextData();
	const { statusRef, netRef, modeRef, amountRef, orderIdRef, numRef, deviceRef, payRef } = useStoreRef();
	const dispatch = useDispatch();
	const stepRef = useRef(custom === null || custom === void 0 ? void 0 : custom.step);
	const fail = useFail(0);
	const failRef = useRef(fail);
	const initRef = useRef(false);
	const controllerRef = useRef();
	const unloadRef = useRef(false);
	const clearRef = useRef();
	const handleCheck = () => !(unloadRef.current || !netRef.current);
	const handleLinklySuccess = (res) => {
		payLog.log("Linkly：最终支付成功");
		const resData = (res === null || res === void 0 ? void 0 : res.data) || {};
		let receipt = Array.isArray(resData === null || resData === void 0 ? void 0 : resData.receipt) ? resData.receipt : [resData.receipt];
		receipt = receipt.filter((item) => typeof item === "string").filter(Boolean);
		dispatch(updateNextStep());
		dispatch(updateCustom({
			card_reader_surcharge: (resData === null || resData === void 0 ? void 0 : resData.card_reader_surcharge) || 0,
			receipt
		}));
		dispatch(updateState({
			status: "success",
			title: locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
		}));
		clearRef.current = setTimeout(() => {
			var _deviceRef$current;
			onChange("success", _objectSpread2(_objectSpread2({}, getPayParams({
				mode: modeRef.current,
				amount: amountRef.current,
				order_id: orderIdRef.current,
				number: numRef.current,
				device: deviceRef.current,
				pay: payRef.current,
				custom: {
					card_reader_surcharge: (resData === null || resData === void 0 ? void 0 : resData.card_reader_surcharge) || 0,
					receipt
				}
			}, "success")), {}, { receipt: ((_deviceRef$current = deviceRef.current) === null || _deviceRef$current === void 0 || (_deviceRef$current = _deviceRef$current.setting) === null || _deviceRef$current === void 0 ? void 0 : _deviceRef$current.receipts) ? [] : receipt }));
		}, 1e3);
	};
	const { payOrRefund } = useLinklyPayOrRefund(handleCheck);
	const { linklyCancel } = useLinklyCancel(handleCheck);
	const { run: resultQuery, stop: stopResultQuery } = useTimeResultQuery(api, handleCheck, handleLinklySuccess);
	const { linklySignature } = useLinklySignature(handleCheck);
	useEffect(() => {
		stepRef.current = custom === null || custom === void 0 ? void 0 : custom.step;
	}, [custom === null || custom === void 0 ? void 0 : custom.step]);
	useEffect(() => {
		failRef.current = fail;
	}, [fail]);
	useEffect(() => {
		var _utils$isTerminal, _utils$interaction;
		console.log("statusRef.current11111", statusRef.current);
		if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			resultQuery();
			return;
		}
		if ((utils === null || utils === void 0 || (_utils$isTerminal = utils.isTerminal) === null || _utils$isTerminal === void 0 ? void 0 : _utils$isTerminal.call(utils)) && (utils === null || utils === void 0 || (_utils$interaction = utils.interaction) === null || _utils$interaction === void 0 || (_utils$interaction = _utils$interaction.utils) === null || _utils$interaction === void 0 ? void 0 : _utils$interaction.asyncDataManager)) (function() {
			var _ref = _asyncToGenerator(function* () {
				try {
					var _utils$interaction2, _utils$interaction2$a;
					const activeStatus = yield utils === null || utils === void 0 || (_utils$interaction2 = utils.interaction) === null || _utils$interaction2 === void 0 || (_utils$interaction2 = _utils$interaction2.utils) === null || _utils$interaction2 === void 0 || (_utils$interaction2$a = _utils$interaction2.asyncDataManager) === null || _utils$interaction2$a === void 0 ? void 0 : _utils$interaction2$a.call(_utils$interaction2, {
						module: "get",
						key: "pay_webview_active"
					});
					if (activeStatus !== "unActive") {
						console.log("当前页面活跃状态，可以进行支付");
						payOrRefund(resultQuery, handleLinklySuccess);
					} else {
						console.log("当前页面非活跃状态，无法进行支付");
						payLog.log("Linkly：页面非活跃状态，阻断支付", { activeStatus });
					}
				} catch (error) {
					payLog.log("Linkly：获取页面活跃状态失败", { error });
					payOrRefund(resultQuery, handleLinklySuccess);
				}
			});
			return function _payOrRefund() {
				return _ref.apply(this, arguments);
			};
		})()();
		else {
			console.log("非terminal环境，直接进行支付");
			payOrRefund(resultQuery, handleLinklySuccess);
		}
	}, []);
	useEffect(() => {
		return () => {
			var _controllerRef$curren;
			(_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || _controllerRef$curren.abort();
			unloadRef.current = true;
			if (clearRef.current) clearTimeout(clearRef.current);
		};
	}, []);
	/**
	* 取消支付
	*/
	const onCancel = () => {
		payLog.log("Linkly：点击取消支付");
		stopResultQuery();
		linklyCancel(resultQuery);
	};
	const onDecline = () => {
		payLog.log("Linkly：签名-点击拒绝");
		stopResultQuery();
		linklySignature(2, resultQuery);
	};
	const onAccept = () => {
		payLog.log("Linkly：签名-点击接受");
		stopResultQuery();
		linklySignature(3, resultQuery);
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, ((custom === null || custom === void 0 ? void 0 : custom.list) || []).map((item) => /* @__PURE__ */ React.createElement(step_default, {
		key: item.index,
		pedding: item.pedding,
		resolve: item.resolve,
		reject: item.reject,
		status: item.status
	})), status === StatusEnum.Loading ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.processing")) : null, status === StatusEnum.Question ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.receipt.again.title")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.receipt.again.text"))) : null, status === StatusEnum.Success ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.transaction.end")) : null), (custom === null || custom === void 0 ? void 0 : custom.actionStatus) === LinklyActionStatus.Cancel ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: onCancel,
		disabled: !!(custom === null || custom === void 0 ? void 0 : custom.buttonDisabled)
	}, locales.getText("page.eftpos-pay.text.cancel"))) : null, (custom === null || custom === void 0 ? void 0 : custom.actionStatus) === LinklyActionStatus.CancelWaiting || (custom === null || custom === void 0 ? void 0 : custom.actionStatus) === LinklyActionStatus.SignatureWaiting ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		disabled: true
	}, locales.getText("page.eftpos-pay.text.leave"))) : null, (custom === null || custom === void 0 ? void 0 : custom.actionStatus) === LinklyActionStatus.Signature ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: onDecline
	}, locales.getText("page.eftpos-pay.text.decline")), /* @__PURE__ */ React.createElement(Button, {
		block: true,
		type: "primary",
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: onAccept
	}, locales.getText("page.eftpos-pay.text.accept"))) : null);
};
//#endregion
export { Linkly as default };
