const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_serve = require("./serve.js");
//#region src/components/pay/toC/payGroup.ts
const STORAGE_KEY = "payGroup";
/** stash 失败时两次重试之间的间隔（毫秒） */
const STASH_RETRY_DELAY_MS = 400;
/** 含首次请求在内最多尝试次数（失败重试 2 次 => 共 3 次） */
const STASH_MAX_ATTEMPTS = 3;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* @title: 创建交易组key
* @description:
* @param {string} orderId
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-08-16 10:40
*/
const createPayGroupKey = (orderId) => {
	return `${STORAGE_KEY}_${orderId}`;
};
/**
* 生成 `/h5/core/stash` 的 token：前缀 + 订单号
*/
const buildPayGroupStashToken = (orderId) => {
	return `payGroup_stash_${orderId}`;
};
const formatWalletCards = (cards) => {
	return cards.map((card) => {
		var _card$actualDeduction;
		return {
			id: card.id,
			available_max_amount: (_card$actualDeduction = card.actualDeduction) !== null && _card$actualDeduction !== void 0 ? _card$actualDeduction : card.available_max_amount,
			available_max_par_value: card.available_max_par_value,
			tag: card.tag,
			wallet_pass_usage_unit: card.wallet_pass_usage_unit,
			metadata: card.metadata
		};
	});
};
/**
* 将带 pay_number 的完整 PayGroup 写入服务端暂存；含首次共最多 3 次，仍失败则返回 false（不阻塞本地写入）。
*/
const stashPayGroupWithRetry = function() {
	var _ref = require_asyncToGenerator._asyncToGenerator(function* (payGroup, orderId, tokenStr) {
		const token = buildPayGroupStashToken(orderId);
		console.log("setPayNumber11->>>", payGroup, token, STASH_MAX_ATTEMPTS);
		for (let attempt = 0; attempt < STASH_MAX_ATTEMPTS; attempt++) try {
			var _payGroup$walletPass;
			yield require_serve.postCoreStash({
				token,
				data: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, payGroup), {}, {
					token: tokenStr,
					orderDetail: void 0,
					otherPayment: void 0,
					walletPass: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (payGroup === null || payGroup === void 0 ? void 0 : payGroup.walletPass) || {}), {}, {
						noApplicableVoucher: [],
						transformList: [],
						cards: formatWalletCards((payGroup === null || payGroup === void 0 || (_payGroup$walletPass = payGroup.walletPass) === null || _payGroup$walletPass === void 0 ? void 0 : _payGroup$walletPass.cards) || [])
					})
				}),
				ttl: 3600
			});
			return true;
		} catch (_unused) {
			if (attempt === STASH_MAX_ATTEMPTS - 1) return false;
			yield delay(STASH_RETRY_DELAY_MS);
		}
		return false;
	});
	return function stashPayGroupWithRetry(_x, _x2, _x3) {
		return _ref.apply(this, arguments);
	};
}();
/**
* @title: 同步交易组到storage
* @description:
* @param {PayGroup} payGroup
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-08-16 10:40
*/
const syncPayGroupToStorage = (payGroup) => {
	localStorage.setItem(createPayGroupKey(payGroup.order_id), JSON.stringify(payGroup));
};
/**
* @title: 通过订单id获取交易组
* @description:
* @param {string} orderId
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-08-16 10:40
*/
const getPayGroupFromStorage = (orderId) => {
	const key = createPayGroupKey(orderId);
	const payGroupStr = localStorage.getItem(key);
	if (payGroupStr) return JSON.parse(payGroupStr);
	return null;
};
/**
* @title: 删除交易组
* @description:
* @param {string} orderId
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-08-16 10:40
*/
const removePayGroupFromStorage = (orderId) => {
	const key = createPayGroupKey(orderId);
	localStorage.removeItem(key);
};
/**
* @title: 获取交易组参数
* @description:
* @param {string} orderId
* @param {any} rest
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-08-16 10:40
*/
const getPayGroupParamsFromStorage = (orderId, rest) => {
	try {
		const payGroup = getPayGroupFromStorage(orderId);
		if (!payGroup) return null;
		return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, rest), {}, {
			amount: payGroup === null || payGroup === void 0 ? void 0 : payGroup.wait_amount,
			payment_group_id: payGroup === null || payGroup === void 0 ? void 0 : payGroup.payment_group_id
		});
	} catch (err) {}
	return null;
};
/**
* @title: 通过订单id设置交易号
* @description: 合并 pay_number 后调用 `/h5/core/stash` 最多 3 次；无论 stash 成败均写入 localStorage
* @param {string} orderId
* @param {string} payNumber
* @param {string} [token] 引擎 utils.token.get()，写入 stash 的 data.token
* @Author: zhiwei.Wang
* @Date: 2024-08-16 10:41
*/
const setPayNumber = function() {
	var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (orderId, payNumber, token) {
		const payGroup = getPayGroupFromStorage(orderId);
		console.log("setPayNumber->>>", payGroup);
		if (!payGroup || !orderId) return;
		const merged = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, payGroup), {}, { pay_number: payNumber });
		yield stashPayGroupWithRetry(merged, orderId, token);
		syncPayGroupToStorage(merged);
	});
	return function setPayNumber(_x4, _x5, _x6) {
		return _ref2.apply(this, arguments);
	};
}();
/**
* @title: 清除服务端暂存
* @description:
* @param {string} orderId
* @return {*}
*/
const clearStashPayGroup = function() {
	var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (orderId) {
		const token = buildPayGroupStashToken(orderId);
		try {
			yield require_serve.postCoreStash({
				token,
				data: { status: "done" },
				ttl: 3600
			});
		} catch (err) {
			console.error("清除服务端暂存失败", err);
		}
	});
	return function clearStashPayGroup(_x7) {
		return _ref3.apply(this, arguments);
	};
}();
//#endregion
exports.buildPayGroupStashToken = buildPayGroupStashToken;
exports.clearStashPayGroup = clearStashPayGroup;
exports.getPayGroupFromStorage = getPayGroupFromStorage;
exports.getPayGroupParamsFromStorage = getPayGroupParamsFromStorage;
exports.removePayGroupFromStorage = removePayGroupFromStorage;
exports.setPayNumber = setPayNumber;
exports.syncPayGroupToStorage = syncPayGroupToStorage;
