const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_locales = require("../../utils/locales.js");
const require_objectSpread2 = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_const = require("./const.js");
const require_index = require("./store/index.js");
const require_payLog = require("./utils/payLog.js");
const require_manufacturer = require("./manufacturer.js");
const require_app = require("./app.js");
const require_tip = require("./tip.js");
const require_locales$1 = require("./locales.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
require("./index.less");
//#region src/components/eftposPay/index.tsx
_pisell_utils.locales.init(require_locales$1.default, require_locales.getLocale());
var eftposPay_default = (props) => {
	var _props$params, _context$appHelper, _props$params3, _store$getState, _props$params4, _props$params5;
	const [check, setCheckStatus] = (0, react.useState)(props.type === require_const.EftposEnum.Tyro ? require_const.OrderEumn.Null : props.source === require_const.RestoreEumn.Restore ? require_const.OrderEumn.Restore : require_const.OrderEumn.Normal);
	const context = require_useEngineContext.default();
	require_payLog.usePayLog({
		paymentType: props.type,
		mode: props.mode || require_const.ModeEnum.Pay,
		orderId: (_props$params = props.params) === null || _props$params === void 0 ? void 0 : _props$params.order_id,
		extra: {
			initialParams: (props === null || props === void 0 ? void 0 : props.params) || null,
			initialSource: (props === null || props === void 0 ? void 0 : props.source) || "",
			initialDevice: (props === null || props === void 0 ? void 0 : props.device) || null
		}
	});
	const [cardSurcharge, setCardSurcharge] = (0, react.useState)(0);
	const [receipt, setReceipt] = (0, react.useState)([]);
	const [updateTime, setTime] = (0, react.useState)("");
	console.log("context = ", context);
	const [historyData, setHistory] = (0, react.useState)();
	const { formatAmount, storage, store } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {
		store: {},
		formatAmount: (number, precision, symbol) => `${symbol}${number}`,
		storage: () => ({ get: () => "" })
	};
	/**
	* 优先从 props.params.platform 中获取渠道信息，其次读取 storage 中的 channel 字段
	* terminal: terminal 内嵌
	* android_kiosk / kiosk: kiosk 内嵌
	* 默认: web
	*/
	const channel = (0, react.useMemo)(() => {
		var _props$params2, _storage$get;
		if ((props === null || props === void 0 || (_props$params2 = props.params) === null || _props$params2 === void 0 ? void 0 : _props$params2.platform) === "kiosk") return "kiosk";
		const rawChannel = (storage === null || storage === void 0 || (_storage$get = storage.get) === null || _storage$get === void 0 ? void 0 : _storage$get.call(storage, "channel")) || "";
		if (rawChannel === "terminal") return "terminal";
		if (rawChannel === "android_kiosk") return "kiosk";
		return "";
	}, [props === null || props === void 0 || (_props$params3 = props.params) === null || _props$params3 === void 0 ? void 0 : _props$params3.platform, storage]);
	(0, react.useEffect)(() => {
		require_payLog.default.setContext({ channel: channel || "web" });
	}, [channel]);
	const isMobile = (0, react.useMemo)(() => {
		if ((props === null || props === void 0 ? void 0 : props.isWebPos) !== void 0 && typeof (props === null || props === void 0 ? void 0 : props.isWebPos) === "boolean") return !props.isWebPos;
		return Boolean(channel);
	}, [channel, props.isWebPos]);
	const symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || "$";
	const mode = (0, react.useMemo)(() => {
		if (props.source === require_const.RestoreEumn.Restore) {
			if (props.params) {
				if (props.params.mode) return props.params.mode;
			}
			return require_const.ModeEnum.Pay;
		}
		if (props.mode) return props.mode;
		return require_const.ModeEnum.Pay;
	}, [
		props.mode,
		props.source,
		props.params
	]);
	/**
	* @title: 构建全局状态
	* @description: 1. 初始化, 2. 恢复
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:11
	*/
	const state = (0, react.useMemo)(() => {
		const current = props.params && props.params.symbol ? props.params.symbol : symbol;
		if (props.source === require_const.RestoreEumn.Restore) return props.params;
		return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, require_manufacturer.getInitState(props.type, props.params ? require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({ mode }, props.params), {}, { symbol: current }) : {
			mode,
			symbol: current
		}) || {}), {}, { originalParams: props.params || {} });
	}, [
		mode,
		props.params,
		props.type,
		symbol
	]);
	const stateRef = (0, react.useRef)(state);
	(0, react.useEffect)(() => {
		stateRef.current = state;
	}, [state]);
	const onChangeStatus = (0, react.useCallback)((status, params, other) => {
		require_payLog.default.log("支付状态回调", {
			status,
			params,
			other
		});
		props.onChangeStatus(status, params, other);
	}, []);
	const action = (0, react.useMemo)(() => {
		const act = (() => {
			if (state.action) return state.action;
			if (mode === require_const.ModeEnum.Pay || mode === require_const.ModeEnum.FullPay) {
				if (state.device && state.pay) return require_const.RouteEnum.Pay;
				if (state.device) return require_const.RouteEnum.Amount;
				return require_const.RouteEnum.DeviceList;
			}
			if (mode === require_const.ModeEnum.Refund) {
				if (state.device) return require_const.RouteEnum.Pay;
				return require_const.RouteEnum.DeviceList;
			}
			if (mode === require_const.ModeEnum.Query) return require_const.RouteEnum.Pay;
			throw Error("未知模式");
		})();
		onChangeStatus("page", act);
		return act;
	}, [mode, state]);
	(0, react.useEffect)(() => {
		document.body.id = "body";
	}, []);
	console.log("props?.params?.device_number = ", props === null || props === void 0 || (_props$params4 = props.params) === null || _props$params4 === void 0 ? void 0 : _props$params4.device_number);
	/**
	* @title: api 接口 数据
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:10
	*/
	const api = (0, react.useMemo)(() => {
		if (typeof props.getApi === "function") return props.getApi();
		return {};
	}, [props.getApi]);
	(0, react.useEffect)(() => {
		if (props.source === require_const.RestoreEumn.Restore || props.type === require_const.EftposEnum.Tyro) return;
		require_payLog.default.log("交易检查：开始检查交易");
		api.getTransaction({
			order_id: stateRef.current.order_id,
			card_reader_type: stateRef.current.eftpos,
			receive_status: "unprocessed"
		}).then((res) => {
			if (!Array.isArray(res.data) || res.data.length === 0) {
				require_payLog.default.log("交易检查：无未处理交易");
				setCheckStatus(require_const.OrderEumn.Null);
				return;
			}
			const currentMode = stateRef.current.mode === require_const.ModeEnum.FullPay ? require_const.ModeEnum.Pay : stateRef.current.mode;
			const list = res.data.filter((item) => item.action === currentMode);
			if (list.length === 0) {
				setCheckStatus(require_const.OrderEumn.Null);
				return;
			}
			const latest = list.pop();
			const numberList = list.map((item) => item.number);
			if (latest.status === require_const.OrderEumn.Failed) {
				require_payLog.default.log("交易检查：最新交易已失败", { number: latest.number });
				setCheckStatus(latest.status);
				onChangeStatus("mark_tx_processed", [...numberList, latest.number]);
				return;
			}
			if (list.length > 0) onChangeStatus("mark_tx_processed", numberList);
			const { pay_param_base64, card_reader_surcharge, receipt } = (latest === null || latest === void 0 ? void 0 : latest.metadata) || {};
			setTime(latest.updated_at);
			setCardSurcharge(card_reader_surcharge || 0);
			setReceipt(receipt || []);
			if (!pay_param_base64) {
				setCheckStatus(require_const.OrderEumn.Failed);
				return;
			}
			try {
				setHistory(JSON.parse(decodeURIComponent(atob(decodeURIComponent(pay_param_base64)))));
				require_payLog.default.log("交易检查：发现待处理交易", {
					status: latest.status,
					number: latest.number
				});
				setCheckStatus(latest.status);
			} catch (e) {
				require_payLog.default.log("交易检查：解析交易数据失败", { error: e });
				setCheckStatus(require_const.OrderEumn.Failed);
				return;
			}
		});
	}, []);
	if (check === require_const.OrderEumn.Normal) return null;
	if (check === require_const.OrderEumn.Succeed) return /* @__PURE__ */ react.default.createElement(require_index.Provider, { state: historyData }, /* @__PURE__ */ react.default.createElement(require_tip.default, {
		cardSurcharge,
		receipts: receipt,
		onChangeStatus,
		onChangeParams: props.onChangeParams,
		formatAmount,
		successTime: updateTime,
		className: isMobile ? "pisell-lowcode__eft-pay-terminal" : ""
	}));
	return /* @__PURE__ */ react.default.createElement(require_index.Provider, { state: check === require_const.OrderEumn.Pending ? historyData : state }, /* @__PURE__ */ react.default.createElement(require_app.default, {
		api,
		channel,
		params: props.params,
		onChangeStatus,
		terminal: props.terminal,
		onChangeParams: props.onChangeParams,
		action: check === require_const.OrderEumn.Pending ? require_const.ModeEnum.Pay : action,
		source: props.source,
		tyroUrl: props.tyroUrl,
		tyroVersion: props.tyroVersion,
		device_number: props === null || props === void 0 || (_props$params5 = props.params) === null || _props$params5 === void 0 ? void 0 : _props$params5.device_number,
		isMobile,
		formatAmount,
		styles: props.styles
	}));
};
//#endregion
exports.default = eftposPay_default;
