import { getLocale } from "../../utils/locales.js";
import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import { EftposEnum, ModeEnum, OrderEumn, RestoreEumn, RouteEnum } from "./const.js";
import { Provider } from "./store/index.js";
import payLog, { usePayLog } from "./utils/payLog.js";
import { getInitState } from "./manufacturer.js";
import App from "./app.js";
import tip_default from "./tip.js";
import locales_default from "./locales.js";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import "./index.less";
//#region src/components/eftposPay/index.tsx
locales.init(locales_default, getLocale());
var eftposPay_default = (props) => {
	var _props$params, _context$appHelper, _props$params3, _store$getState, _props$params4, _props$params5;
	const [check, setCheckStatus] = useState(props.type === EftposEnum.Tyro ? OrderEumn.Null : props.source === RestoreEumn.Restore ? OrderEumn.Restore : OrderEumn.Normal);
	const context = useEngineContext();
	usePayLog({
		paymentType: props.type,
		mode: props.mode || 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] = useState(0);
	const [receipt, setReceipt] = useState([]);
	const [updateTime, setTime] = useState("");
	console.log("context = ", context);
	const [historyData, setHistory] = 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 = 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]);
	useEffect(() => {
		payLog.setContext({ channel: channel || "web" });
	}, [channel]);
	const isMobile = 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 = useMemo(() => {
		if (props.source === RestoreEumn.Restore) {
			if (props.params) {
				if (props.params.mode) return props.params.mode;
			}
			return ModeEnum.Pay;
		}
		if (props.mode) return props.mode;
		return ModeEnum.Pay;
	}, [
		props.mode,
		props.source,
		props.params
	]);
	/**
	* @title: 构建全局状态
	* @description: 1. 初始化, 2. 恢复
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:11
	*/
	const state = useMemo(() => {
		const current = props.params && props.params.symbol ? props.params.symbol : symbol;
		if (props.source === RestoreEumn.Restore) return props.params;
		return _objectSpread2(_objectSpread2({}, getInitState(props.type, props.params ? _objectSpread2(_objectSpread2({ mode }, props.params), {}, { symbol: current }) : {
			mode,
			symbol: current
		}) || {}), {}, { originalParams: props.params || {} });
	}, [
		mode,
		props.params,
		props.type,
		symbol
	]);
	const stateRef = useRef(state);
	useEffect(() => {
		stateRef.current = state;
	}, [state]);
	const onChangeStatus = useCallback((status, params, other) => {
		payLog.log("支付状态回调", {
			status,
			params,
			other
		});
		props.onChangeStatus(status, params, other);
	}, []);
	const action = useMemo(() => {
		const act = (() => {
			if (state.action) return state.action;
			if (mode === ModeEnum.Pay || mode === ModeEnum.FullPay) {
				if (state.device && state.pay) return RouteEnum.Pay;
				if (state.device) return RouteEnum.Amount;
				return RouteEnum.DeviceList;
			}
			if (mode === ModeEnum.Refund) {
				if (state.device) return RouteEnum.Pay;
				return RouteEnum.DeviceList;
			}
			if (mode === ModeEnum.Query) return RouteEnum.Pay;
			throw Error("未知模式");
		})();
		onChangeStatus("page", act);
		return act;
	}, [mode, state]);
	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 = useMemo(() => {
		if (typeof props.getApi === "function") return props.getApi();
		return {};
	}, [props.getApi]);
	useEffect(() => {
		if (props.source === RestoreEumn.Restore || props.type === EftposEnum.Tyro) return;
		payLog.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) {
				payLog.log("交易检查：无未处理交易");
				setCheckStatus(OrderEumn.Null);
				return;
			}
			const currentMode = stateRef.current.mode === ModeEnum.FullPay ? ModeEnum.Pay : stateRef.current.mode;
			const list = res.data.filter((item) => item.action === currentMode);
			if (list.length === 0) {
				setCheckStatus(OrderEumn.Null);
				return;
			}
			const latest = list.pop();
			const numberList = list.map((item) => item.number);
			if (latest.status === OrderEumn.Failed) {
				payLog.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(OrderEumn.Failed);
				return;
			}
			try {
				setHistory(JSON.parse(decodeURIComponent(atob(decodeURIComponent(pay_param_base64)))));
				payLog.log("交易检查：发现待处理交易", {
					status: latest.status,
					number: latest.number
				});
				setCheckStatus(latest.status);
			} catch (e) {
				payLog.log("交易检查：解析交易数据失败", { error: e });
				setCheckStatus(OrderEumn.Failed);
				return;
			}
		});
	}, []);
	if (check === OrderEumn.Normal) return null;
	if (check === OrderEumn.Succeed) return /* @__PURE__ */ React.createElement(Provider, { state: historyData }, /* @__PURE__ */ React.createElement(tip_default, {
		cardSurcharge,
		receipts: receipt,
		onChangeStatus,
		onChangeParams: props.onChangeParams,
		formatAmount,
		successTime: updateTime,
		className: isMobile ? "pisell-lowcode__eft-pay-terminal" : ""
	}));
	return /* @__PURE__ */ React.createElement(Provider, { state: check === OrderEumn.Pending ? historyData : state }, /* @__PURE__ */ React.createElement(App, {
		api,
		channel,
		params: props.params,
		onChangeStatus,
		terminal: props.terminal,
		onChangeParams: props.onChangeParams,
		action: check === OrderEumn.Pending ? 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
export { eftposPay_default as default };
