const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_defineProperty = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/defineProperty.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_objectWithoutProperties = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
let _pisell_utils = require("@pisell/utils");
//#region src/components/eftposPay/utils/payLog.ts
const _excluded = ["extra"];
/** localStorage 持久化 key */
const STORAGE_KEY = "pisell2_eftpos_paylog";
/** 异常关键词，命中时不压缩 */
const ERROR_KEYWORDS = [
	"失败",
	"错误",
	"异常",
	"error",
	"fail",
	"timeout",
	"超时"
];
function generateSessionKey() {
	return `eft_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
}
/**
* 判断 title 是否包含异常关键词
*/
function isErrorLog(title) {
	const lower = title.toLowerCase();
	return ERROR_KEYWORDS.some((kw) => lower.includes(kw));
}
/**
* 浅比较两个值是否"相同"（用于 data 去重）
*/
function shallowEqual(a, b) {
	if (a === b) return true;
	if (a == null && b == null) return true;
	if (a == null || b == null) return false;
	try {
		return JSON.stringify(a) === JSON.stringify(b);
	} catch (_unused) {
		return false;
	}
}
/**
* 将原始日志列表压缩：连续同名非异常日志合并
*/
function compressLogs(logs) {
	if (logs.length === 0) return [];
	const result = [];
	let i = 0;
	while (i < logs.length) {
		const current = logs[i];
		if (isErrorLog(current.t)) {
			result.push({
				t: current.t,
				ts: current.ts,
				d: current.d
			});
			i++;
			continue;
		}
		let j = i + 1;
		while (j < logs.length && logs[j].t === current.t && !isErrorLog(logs[j].t)) j++;
		const count = j - i;
		if (count === 1) result.push({
			t: current.t,
			ts: current.ts,
			d: current.d
		});
		else {
			const last = logs[j - 1];
			const entry = {
				t: current.t,
				ts: current.ts,
				count,
				lastTs: last.ts
			};
			if (current.d !== void 0) entry.d = current.d;
			if (!shallowEqual(current.d, last.d) && last.d !== void 0) entry.lastD = last.d;
			result.push(entry);
		}
		i = j;
	}
	return result;
}
var PayLog = class PayLog {
	constructor() {
		require_defineProperty._defineProperty(this, "sessionKey", null);
		require_defineProperty._defineProperty(this, "context", {});
		require_defineProperty._defineProperty(this, "logs", []);
		require_defineProperty._defineProperty(this, "startTime", 0);
		require_defineProperty._defineProperty(this, "flushed", false);
	}
	static getInstance() {
		if (!PayLog.instance) PayLog.instance = new PayLog();
		return PayLog.instance;
	}
	/**
	* 初始化一次交易会话
	* - 生成唯一 sessionKey
	* - 恢复上报 localStorage 中残留的旧日志
	* - 接受部分 context（后续可通过 setContext 补充）
	*/
	init(context) {
		try {
			this.recoverOrphanedLogs();
			this.sessionKey = generateSessionKey();
			this.context = context || {};
			this.logs = [];
			this.startTime = Date.now();
			this.flushed = false;
			this.log("PayLog 初始化", context);
		} catch (error) {
			console.error("PayLog init error:", error);
		}
	}
	/**
	* 补充/更新上下文信息
	* 新值覆盖旧值，extra 做浅合并
	*/
	setContext(partial) {
		if (!this.sessionKey) return;
		const { extra } = partial, rest = require_objectWithoutProperties._objectWithoutProperties(partial, _excluded);
		Object.assign(this.context, rest);
		if (extra) {
			var _this$context;
			this.context.extra = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, ((_this$context = this.context) === null || _this$context === void 0 ? void 0 : _this$context.extra) || {}), extra || {});
		}
		this.persistToStorage();
	}
	/**
	* 记录一条日志
	*/
	log(title, data) {
		if (!this.sessionKey) {
			console.warn("PayLog: 未初始化，日志将被忽略 -", title);
			return;
		}
		const entry = {
			t: title,
			ts: (0, dayjs.default)().format("HH:mm:ss.SSS")
		};
		if (data !== void 0) entry.d = data;
		this.logs.push(entry);
		this.persistToStorage();
	}
	/**
	* 上报日志到飞书并清理 localStorage
	*/
	flush(customTitle) {
		if (this.flushed || !this.sessionKey) return;
		this.flushed = true;
		try {
			const elapsed = ((Date.now() - this.startTime) / 1e3).toFixed(1);
			const compressed = compressLogs(this.logs);
			const { paymentType, mode, orderId } = this.context;
			(0, _pisell_utils.sendWarningLog)({
				title: customTitle || `[EFTPOS] ${paymentType || "Unknown"}-${mode || "unknown"}-${orderId || "Unknown"}`,
				content: this.buildContent(compressed, elapsed)
			});
			this.removeFromStorage(this.sessionKey);
		} catch (error) {
			console.error("PayLog flush error:", error);
		} finally {
			this.sessionKey = null;
		}
	}
	/**
	* flush + 重置内部状态
	*/
	destroy() {
		this.flush();
		this.sessionKey = null;
		this.context = {};
		this.logs = [];
		this.startTime = 0;
		this.flushed = false;
	}
	/**
	* 构建 sendWarningLog 所需的 content 数组
	*/
	buildContent(compressed, elapsed) {
		const ctx = this.context;
		return [
			{
				key: "sessionKey",
				value: this.sessionKey || ""
			},
			{
				key: "发起时间",
				value: (0, dayjs.default)(this.startTime).format("YYYY-MM-DD HH:mm:ss")
			},
			{
				key: "交易号",
				value: String(ctx.transactionNumber || "未知")
			},
			{
				key: "订单ID",
				value: String(ctx.orderId || "未知")
			},
			{
				key: "设备ID",
				value: String(ctx.deviceId || "未知")
			},
			{
				key: "支付类型",
				value: String(ctx.paymentType || "未知")
			},
			{
				key: "模式",
				value: String(ctx.mode || "未知")
			},
			{
				key: "渠道",
				value: String(ctx.channel || "未知")
			},
			{
				key: "总耗时",
				value: `${elapsed}s`
			},
			{
				key: "时间线",
				value: JSON.stringify(compressed)
			}
		];
	}
	/**
	* 持久化当前会话到 localStorage
	*/
	persistToStorage() {
		if (!this.sessionKey) return;
		try {
			const all = this.getAllSessions();
			all[this.sessionKey] = {
				sessionKey: this.sessionKey,
				context: this.context,
				logs: this.logs,
				startTime: this.startTime
			};
			localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
		} catch (error) {
			console.error("PayLog persist error:", error);
		}
	}
	/**
	* 从 localStorage 移除指定 session
	*/
	removeFromStorage(key) {
		try {
			const all = this.getAllSessions();
			delete all[key];
			if (Object.keys(all).length === 0) localStorage.removeItem(STORAGE_KEY);
			else localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
		} catch (error) {
			console.error("PayLog removeFromStorage error:", error);
		}
	}
	/**
	* 获取 localStorage 中所有 session
	*/
	getAllSessions() {
		try {
			const raw = localStorage.getItem(STORAGE_KEY);
			if (!raw) return {};
			return JSON.parse(raw);
		} catch (_unused2) {
			return {};
		}
	}
	/**
	* 恢复上报 localStorage 中残留的旧日志（崩溃/异常退出场景）
	*/
	recoverOrphanedLogs() {
		try {
			const all = this.getAllSessions();
			const keys = Object.keys(all);
			if (keys.length === 0) return;
			for (const key of keys) {
				const session = all[key];
				try {
					const elapsed = ((Date.now() - session.startTime) / 1e3).toFixed(1);
					const compressed = compressLogs(session.logs);
					const ctx = session.context;
					(0, _pisell_utils.sendWarningLog)({
						title: `[PRE][EFTPOS] ${ctx.paymentType || "未知支付"}-${ctx.mode || "未知模式"}-${ctx.orderId || "未知订单ID"}`,
						content: [
							{
								key: "sessionKey",
								value: session.sessionKey
							},
							{
								key: "发起时间",
								value: (0, dayjs.default)(session.startTime).format("YYYY-MM-DD HH:mm:ss")
							},
							{
								key: "交易号",
								value: String(ctx.transactionNumber || "未知")
							},
							{
								key: "订单ID",
								value: String(ctx.orderId || "未知")
							},
							{
								key: "设备ID",
								value: String(ctx.deviceId || "未知")
							},
							{
								key: "支付类型",
								value: String(ctx.paymentType || "未知")
							},
							{
								key: "模式",
								value: String(ctx.mode || "未知")
							},
							{
								key: "总耗时",
								value: `${elapsed}s`
							},
							{
								key: "日志条数(原始/压缩)",
								value: `${session.logs.length}/${compressed.length}`
							},
							{
								key: "时间线",
								value: JSON.stringify(compressed)
							}
						]
					});
					this.removeFromStorage(key);
				} catch (err) {
					console.error(`PayLog: 恢复上报失败 (${key}):`, err);
					this.removeFromStorage(key);
				}
			}
		} catch (error) {
			console.error("PayLog recoverOrphanedLogs error:", error);
		}
	}
};
require_defineProperty._defineProperty(PayLog, "instance", void 0);
const payLog = PayLog.getInstance();
/**
* 在根组件中使用，管理 PayLog 生命周期
* - mount 时 init（+ 恢复上报残留日志）
* - unmount 时 destroy
*/
function usePayLog(context) {
	const initialized = (0, react.useRef)(false);
	(0, react.useEffect)(() => {
		if (!initialized.current) {
			initialized.current = true;
			payLog.init(context);
		}
		return () => {
			payLog.log("流程结束，上报日志");
			payLog.destroy();
		};
	}, []);
	return {
		log: (title, data) => payLog.log(title, data),
		setContext: (partial) => payLog.setContext(partial)
	};
}
//#endregion
exports.default = payLog;
exports.usePayLog = usePayLog;
