import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { ModeEnum, PayStatus, StatusEnum } from "../const.js";
import { getPayParams } from "../helper.js";
import { updateCustom, updateNextStep, updateState, updateStatus, useContextData, useDispatch } from "../store/index.js";
import { useFail, useStoreRef } from "../hooks.js";
import { EPaymentStatus } from "../aggregatePayment/types.js";
import useMicropay from "../aggregatePayment/hooks/useMicropay.js";
import { ScanAction } from "./Action.js";
import React, { useEffect, useRef } from "react";
import { locales } from "@pisell/utils";
import "./index.less";
//#region src/components/eftposPay/huifu/index.tsx
const Huifu = ({ isNativeApp, onChange }) => {
	var _context$appHelper, _data$custom;
	const data = useContextData();
	const { interaction } = ((_context$appHelper = useEngineContext().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const { statusRef, numRef, netRef, modeRef, amountRef, orderIdRef, deviceRef, payRef } = useStoreRef();
	const dispatch = useDispatch();
	const fail = useFail(0);
	const failRef = useRef(fail);
	const initRef = useRef(false);
	const unloadRef = useRef(false);
	const clearRef = useRef(null);
	const payment = useMicropay({
		paymentCode: (data === null || data === void 0 || (_data$custom = data.custom) === null || _data$custom === void 0 ? void 0 : _data$custom.custom_payment_code) || "EFTPOS_HUIFU",
		paymentNum: numRef.current || "",
		shouldContinue: () => !(unloadRef.current || !netRef.current),
		callback: (_instance, response) => {
			console.log("callback = ", response);
			const { status, data } = response || {};
			if (status === EPaymentStatus.Success) {
				dispatch(updateNextStep());
				dispatch(updateCustom({
					card_reader_surcharge: 0,
					receipt: []
				}));
				dispatch(updateState({
					status: "success",
					title: locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
				}));
				clearRef.current = setTimeout(() => {
					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: 0,
							receipt: []
						}
					}, "success")), {}, { receipt: [] }));
				}, 1e3);
			} else if (status === EPaymentStatus.Failed) handleFail(data);
		}
	});
	useEffect(() => {
		failRef.current = fail;
	}, [fail]);
	useEffect(() => {
		if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			console.log("payment.query");
			payment.query();
			return;
		}
		console.log("data?.custom =>>>> ", data === null || data === void 0 ? void 0 : data.custom);
		if (!(modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay)) {
			var _data$custom2;
			payment.run({ orderPaymentId: data === null || data === void 0 || (_data$custom2 = data.custom) === null || _data$custom2 === void 0 ? void 0 : _data$custom2.order_payment_id });
			return;
		}
	}, []);
	useEffect(() => {
		if (isNativeApp && (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Init) {
			var _interaction$utils, _interaction$utils$po;
			interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 || _interaction$utils$po.call(_interaction$utils, {
				module: "pos",
				key: "other",
				data: { key: "show_close_button" }
			});
		}
	}, [isNativeApp, data === null || data === void 0 ? void 0 : data.status]);
	useEffect(() => {
		return () => {
			unloadRef.current = true;
			if (clearRef.current) clearTimeout(clearRef.current);
		};
	}, []);
	/**
	* 触发支付失败流程：交由 useFail 统一处理失败/重试逻辑
	*/
	const handleFail = (errorData) => {
		var _errorData$data, _failRef$current;
		const { message, response_code } = (errorData === null || errorData === void 0 || (_errorData$data = errorData.data) === null || _errorData$data === void 0 ? void 0 : _errorData$data.external_unified_response) || {};
		const _code = `${response_code || ""}` || PayStatus.PaymentFailed;
		const _message = message || (errorData === null || errorData === void 0 ? void 0 : errorData.message) || "";
		console.log("handleFail =>>>> ", errorData, _code, _message);
		(_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, {
			code: _code,
			message: _message
		}, false);
	};
	/**
	* 更新到加载状态
	*/
	const updateToLoading = () => {
		if (isNativeApp) {
			var _interaction$utils2, _interaction$utils2$p;
			interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$p = _interaction$utils2.postMessageToApp) === null || _interaction$utils2$p === void 0 || _interaction$utils2$p.call(_interaction$utils2, {
				module: "pos",
				key: "other",
				data: { key: "hide_close_button" }
			});
		}
		dispatch(updateStatus(StatusEnum.Loading));
		dispatch(updateState({ title: locales.getText("page.eftpos-pay.text.loading")(modeRef.current) }));
	};
	const onClose = () => {
		onChange("fail", {
			number: data.number,
			uniquePaymentNumber: data.number,
			device: data.device,
			order_id: data.order_id
		});
	};
	const onPayClick = (scanResult) => {
		console.log("scanResult = ", scanResult);
		updateToLoading();
		payment.run({ authCode: scanResult });
	};
	const onScanCallback = (scanResult) => {
		console.log("scanResult = ", scanResult);
		updateToLoading();
		payment.run({ authCode: scanResult });
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Init && /* @__PURE__ */ React.createElement(ScanAction, {
		onClose,
		onScanCallback,
		onPayClick,
		isNativeApp
	}), (data === null || data === void 0 ? void 0 : data.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);
};
//#endregion
export { Huifu as default };
