const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_const = require("../const.js");
const require_const$1 = require("./const.js");
const require_helper = require("../helper.js");
const require_index = require("../store/index.js");
const require_hooks = require("../hooks.js");
const require_payLog = require("../utils/payLog.js");
const require_step = require("../component/step/step.js");
const require_helper$1 = require("./helper.js");
const require_receiptAction = require("./receiptAction.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
//#region src/components/eftposPay/windcave/windcave.tsx
const Minute = 1e3 * 60;
var windcave_default = ({ api, onChange, formatAmount = (number, precision, symbol) => `${symbol}${number}` }) => {
	const { custom, status } = require_index.useContextData();
	const { deviceRef, payRef, numRef, orderIdRef, modeRef, statusRef, netRef, symbolRef, amountRef, eftposRef, dataRef } = require_hooks.useStoreRef();
	const dispatch = require_index.useDispatch();
	const fail = require_helper$1.useFail();
	const failRef = (0, react.useRef)(fail);
	const unloadRef = (0, react.useRef)(false);
	const stepRef = (0, react.useRef)(custom === null || custom === void 0 ? void 0 : custom.step);
	const listRef = (0, react.useRef)(custom === null || custom === void 0 ? void 0 : custom.list);
	const initRef = (0, react.useRef)(false);
	const clearRef = (0, react.useRef)(null);
	/** 是否是签名页面 */
	const isReceiptPage = (0, react.useMemo)(() => (custom === null || custom === void 0 ? void 0 : custom.step) === require_const$1.StepStatusEnum.Receipt, [custom === null || custom === void 0 ? void 0 : custom.step]);
	/** 签名页面状态 */
	const receiptPage = (0, react.useMemo)(() => (custom === null || custom === void 0 ? void 0 : custom.step) !== require_const$1.StepStatusEnum.Receipt ? "" : (custom === null || custom === void 0 ? void 0 : custom.receiptPage) || "receipt", [custom === null || custom === void 0 ? void 0 : custom.step, custom === null || custom === void 0 ? void 0 : custom.receiptPage]);
	const [disabled, setDisabled] = (0, react.useState)(false);
	(0, react.useEffect)(() => {
		listRef.current = custom === null || custom === void 0 ? void 0 : custom.list;
	}, [custom === null || custom === void 0 ? void 0 : custom.list]);
	(0, react.useEffect)(() => {
		stepRef.current = custom === null || custom === void 0 ? void 0 : custom.step;
	}, [custom === null || custom === void 0 ? void 0 : custom.step]);
	(0, react.useEffect)(() => {
		failRef.current = fail;
	}, [fail]);
	/**
	* @title:  查询支付状态
	* @description: 轮询 api.check 检查支付状态, 中间状态转换在 useValidate 中进行,结束在当前回调中完成
	* @param {*} useValidate
	* @return {*}
	* @Author: hongbing.wang
	* @Date: 2024-08-12 11:02
	*/
	const [run, validateRef] = require_helper$1.useValidate(api.check, Minute, (res) => {
		let receipt = Array.isArray(res === null || res === void 0 ? void 0 : res.receipt) ? res.receipt : [res.receipt];
		receipt = receipt.filter((item) => typeof item === "string").filter(Boolean);
		dispatch(require_index.updateCustom({
			list: listRef.current.map((item) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, { status: "resolve" })),
			card_reader_surcharge: (res === null || res === void 0 ? void 0 : res.card_reader_surcharge) || 0,
			receipt
		}));
		dispatch(require_index.updateState({
			status: "success",
			title: _pisell_utils.locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
		}));
		clearRef.current = setTimeout(() => {
			var _deviceRef$current;
			onChange("success", require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, require_helper.getPayParams({
				mode: modeRef.current,
				amount: amountRef.current,
				order_id: orderIdRef.current,
				number: numRef.current,
				device: deviceRef.current,
				pay: payRef.current,
				custom: {
					card_reader_surcharge: (res === null || res === void 0 ? void 0 : res.card_reader_surcharge) || 0,
					receipt
				}
			}, "success")), {}, { receipt: ((_deviceRef$current = deviceRef.current) === null || _deviceRef$current === void 0 || (_deviceRef$current = _deviceRef$current.setting) === null || _deviceRef$current === void 0 ? void 0 : _deviceRef$current.receipts) ? [] : receipt }));
		}, 1e3);
	});
	const controllerRef = (0, react.useRef)();
	(0, react.useEffect)(() => {
		if (statusRef.current === require_const.StatusEnum.Success || statusRef.current === require_const.StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (stepRef.current === require_const$1.StepStatusEnum.Receipt) {
			if (require_const.StatusEnum.Loading === statusRef.current) {
				require_payLog.default.log("Windcave：签名页面处于运行中(已发送签名,或取消签名接口),进行计时查询");
				run();
			} else {
				require_payLog.default.log("Windcave：签名页面处于未加载中,进行无限查询");
				run(-1);
			}
			return;
		}
		controllerRef.current = new AbortController();
		if (numRef.current) {
			run();
			return;
		}
		numRef.current = require_helper.getUuid();
		dispatch(require_index.updateState({ number: numRef.current }));
		const isPay = modeRef.current === require_const.ModeEnum.Pay || modeRef.current === require_const.ModeEnum.FullPay;
		let _params = {};
		if (isPay) {
			var _deviceRef$current2;
			_params = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (custom === null || custom === void 0 ? void 0 : custom.platform) ? {
				operator_id: custom.operator_id,
				operator_type: custom.operator_type,
				platform: custom.platform,
				custom_payment_id: custom.custom_payment_id
			} : {}), {}, {
				service_charge: {
					amount: payRef.current.surMoney,
					percentage: payRef.current.surPercentRate
				},
				original_amount: payRef.current.amount,
				order_id: orderIdRef.current,
				amount: payRef.current.total,
				card_reader_type: eftposRef.current,
				card_reader_id: (_deviceRef$current2 = deviceRef.current) === null || _deviceRef$current2 === void 0 ? void 0 : _deviceRef$current2.id,
				number: numRef.current,
				pay_param_base64: encodeURIComponent(btoa(encodeURIComponent(JSON.stringify(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, dataRef.current), {}, { number: numRef.current })))))
			});
		} else {
			var _deviceRef$current3;
			_params = {
				order_id: orderIdRef.current,
				amount: amountRef.current,
				card_reader_type: eftposRef.current,
				card_reader_id: (_deviceRef$current3 = deviceRef.current) === null || _deviceRef$current3 === void 0 ? void 0 : _deviceRef$current3.id,
				number: numRef.current,
				pay_param_base64: encodeURIComponent(btoa(encodeURIComponent(JSON.stringify(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, dataRef.current), {}, { number: numRef.current })))))
			};
		}
		require_payLog.default.setContext({ transactionNumber: numRef.current });
		if (isPay) require_payLog.default.log("Windcave：发起支付", { number: numRef.current });
		else require_payLog.default.log("Windcave：发起退款", { number: numRef.current });
		(isPay ? api.pay(_params, { signal: controllerRef.current.signal }) : api.refund(_params, { signal: controllerRef.current.signal })).then((res) => {
			var _failRef$current;
			if (unloadRef.current || !netRef.current) return;
			if (res && `${res.code}` === "200" && res.data && res.data.txn_status_id) {
				var _res$data, _validateRef$current;
				require_payLog.default.log("Windcave：接口成功，进入轮询", { txn_status_id: res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.txn_status_id });
				(_validateRef$current = validateRef.current) === null || _validateRef$current === void 0 || _validateRef$current.call(validateRef, res, true);
				return;
			}
			require_payLog.default.log("Windcave：支付接口返回失败", { code: res === null || res === void 0 ? void 0 : res.code });
			(_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, res, stepRef.current >= require_const$1.StepStatusEnum.Account);
		}).catch((res) => {
			var _failRef$current2;
			let isNoNet = unloadRef.current || !netRef.current;
			require_payLog.default.log("Windcave：支付接口异常", {
				error: res === null || res === void 0 ? void 0 : res.message,
				isNoNet
			});
			if (isNoNet) return;
			(_failRef$current2 = failRef.current) === null || _failRef$current2 === void 0 || _failRef$current2.call(failRef, res, stepRef.current >= require_const$1.StepStatusEnum.Account);
		});
	}, [
		api,
		run,
		dispatch
	]);
	/**
	* @title: 取消支付
	* @Author: hongbing.wang
	* @Date: 2024-08-20 12:51
	*/
	const onCancel = () => {
		require_payLog.default.log("Windcave：点击取消支付");
		setDisabled(true);
		api.update({
			type: "CANCEL",
			number: numRef.current
		});
	};
	(0, react.useEffect)(() => () => {
		var _controllerRef$curren, _controllerRef$curren2;
		unloadRef.current = true;
		(_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || (_controllerRef$curren2 = _controllerRef$curren.abort) === null || _controllerRef$curren2 === void 0 || _controllerRef$curren2.call(_controllerRef$curren);
		if (clearRef.current) clearTimeout(clearRef.current);
	}, []);
	/**
	* @title:  签名状态
	* @param {boolean} status 签名状态
	* @Author: hongbing.wang
	* @Date: 2024-08-20 12:54
	*/
	const onChangeReceipt = (status) => {
		if (status) {
			require_payLog.default.log("Windcave：签名状态");
			run();
		}
	};
	(0, react.useEffect)(() => {
		if (listRef.current.length === 0) {
			let totalUnit = "";
			if (modeRef.current === require_const.ModeEnum.Pay || modeRef.current === require_const.ModeEnum.FullPay) {
				var _payRef$current;
				totalUnit = (_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.totalUnit;
			} else if (modeRef.current === require_const.ModeEnum.Refund) if (payRef.current) totalUnit = payRef.current.totalUnit;
			else {
				totalUnit = formatAmount(amountRef.current, 2, symbolRef.current);
				dispatch(require_index.updateState({ pay: {
					total: amountRef.current,
					totalUnit
				} }));
			}
			dispatch(require_index.updateCustom({
				list: [require_const$1.getStepMapping(require_const$1.StepStatusEnum.Free, {
					money: totalUnit,
					mode: modeRef.current
				})],
				step: require_const$1.StepStatusEnum.Free
			}));
		}
	}, [dispatch]);
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, receiptPage !== "again" ? (custom === null || custom === void 0 ? void 0 : custom.list).map((item) => /* @__PURE__ */ react.default.createElement(require_step.default, {
		key: item.index,
		pedding: item.pedding,
		resolve: item.resolve,
		reject: item.reject,
		status: item.status,
		className: item.type === require_const$1.StemTypeEnum.Passive && item.status === "pedding" ? "pisell-lowcode__eft-pay-step-item-warn" : ""
	})) : null, receiptPage === "again" ? /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-warn-text pisell-lowcode__eft-pay-body" }, _pisell_utils.locales.getText("page.eftpos-pay.text.signature.text")(modeRef.current)) : null, status === require_const.StatusEnum.Loading ? /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, _pisell_utils.locales.getText("page.eftpos-pay.text.processing")) : null, status === require_const.StatusEnum.Success ? /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, _pisell_utils.locales.getText("page.eftpos-pay.text.transaction.end")) : null), !isReceiptPage && status !== require_const.StatusEnum.Success ? /* @__PURE__ */ react.default.createElement(require_receiptAction.default, {
		index: custom === null || custom === void 0 ? void 0 : custom.step,
		onCancel,
		disabled
	}) : null, isReceiptPage ? /* @__PURE__ */ react.default.createElement(require_receiptAction.ReceiptAction, {
		api,
		onChange: onChangeReceipt
	}) : null);
};
//#endregion
exports.default = windcave_default;
