import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { ModeEnum, StatusEnum } from "../const.js";
import { StemTypeEnum, StepStatusEnum, getStepMapping } from "./const.js";
import { getPayParams, getUuid } from "../helper.js";
import { updateCustom, updateState, useContextData, useDispatch } from "../store/index.js";
import { useStoreRef } from "../hooks.js";
import payLog from "../utils/payLog.js";
import step_default from "../component/step/step.js";
import { useFail, useValidate } from "./helper.js";
import Action, { ReceiptAction } from "./receiptAction.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { locales } from "@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 } = useContextData();
	const { deviceRef, payRef, numRef, orderIdRef, modeRef, statusRef, netRef, symbolRef, amountRef, eftposRef, dataRef } = useStoreRef();
	const dispatch = useDispatch();
	const fail = useFail();
	const failRef = useRef(fail);
	const unloadRef = useRef(false);
	const stepRef = useRef(custom === null || custom === void 0 ? void 0 : custom.step);
	const listRef = useRef(custom === null || custom === void 0 ? void 0 : custom.list);
	const initRef = useRef(false);
	const clearRef = useRef(null);
	/** 是否是签名页面 */
	const isReceiptPage = useMemo(() => (custom === null || custom === void 0 ? void 0 : custom.step) === StepStatusEnum.Receipt, [custom === null || custom === void 0 ? void 0 : custom.step]);
	/** 签名页面状态 */
	const receiptPage = useMemo(() => (custom === null || custom === void 0 ? void 0 : custom.step) !== 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] = useState(false);
	useEffect(() => {
		listRef.current = custom === null || custom === void 0 ? void 0 : custom.list;
	}, [custom === null || custom === void 0 ? void 0 : custom.list]);
	useEffect(() => {
		stepRef.current = custom === null || custom === void 0 ? void 0 : custom.step;
	}, [custom === null || custom === void 0 ? void 0 : custom.step]);
	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] = 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(updateCustom({
			list: listRef.current.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { status: "resolve" })),
			card_reader_surcharge: (res === null || res === void 0 ? void 0 : res.card_reader_surcharge) || 0,
			receipt
		}));
		dispatch(updateState({
			status: "success",
			title: locales.getText("page.eftpos-pay.text.successful")(modeRef.current)
		}));
		clearRef.current = setTimeout(() => {
			var _deviceRef$current;
			onChange("success", _objectSpread2(_objectSpread2({}, 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 = useRef();
	useEffect(() => {
		if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (stepRef.current === StepStatusEnum.Receipt) {
			if (StatusEnum.Loading === statusRef.current) {
				payLog.log("Windcave：签名页面处于运行中(已发送签名,或取消签名接口),进行计时查询");
				run();
			} else {
				payLog.log("Windcave：签名页面处于未加载中,进行无限查询");
				run(-1);
			}
			return;
		}
		controllerRef.current = new AbortController();
		if (numRef.current) {
			run();
			return;
		}
		numRef.current = getUuid();
		dispatch(updateState({ number: numRef.current }));
		const isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
		let _params = {};
		if (isPay) {
			var _deviceRef$current2;
			_params = _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(_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(_objectSpread2(_objectSpread2({}, dataRef.current), {}, { number: numRef.current })))))
			};
		}
		payLog.setContext({ transactionNumber: numRef.current });
		if (isPay) payLog.log("Windcave：发起支付", { number: numRef.current });
		else payLog.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;
				payLog.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;
			}
			payLog.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 >= StepStatusEnum.Account);
		}).catch((res) => {
			var _failRef$current2;
			let isNoNet = unloadRef.current || !netRef.current;
			payLog.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 >= StepStatusEnum.Account);
		});
	}, [
		api,
		run,
		dispatch
	]);
	/**
	* @title: 取消支付
	* @Author: hongbing.wang
	* @Date: 2024-08-20 12:51
	*/
	const onCancel = () => {
		payLog.log("Windcave：点击取消支付");
		setDisabled(true);
		api.update({
			type: "CANCEL",
			number: numRef.current
		});
	};
	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) {
			payLog.log("Windcave：签名状态");
			run();
		}
	};
	useEffect(() => {
		if (listRef.current.length === 0) {
			let totalUnit = "";
			if (modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay) {
				var _payRef$current;
				totalUnit = (_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.totalUnit;
			} else if (modeRef.current === ModeEnum.Refund) if (payRef.current) totalUnit = payRef.current.totalUnit;
			else {
				totalUnit = formatAmount(amountRef.current, 2, symbolRef.current);
				dispatch(updateState({ pay: {
					total: amountRef.current,
					totalUnit
				} }));
			}
			dispatch(updateCustom({
				list: [getStepMapping(StepStatusEnum.Free, {
					money: totalUnit,
					mode: modeRef.current
				})],
				step: StepStatusEnum.Free
			}));
		}
	}, [dispatch]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, receiptPage !== "again" ? (custom === null || custom === void 0 ? void 0 : custom.list).map((item) => /* @__PURE__ */ React.createElement(step_default, {
		key: item.index,
		pedding: item.pedding,
		resolve: item.resolve,
		reject: item.reject,
		status: item.status,
		className: item.type === StemTypeEnum.Passive && item.status === "pedding" ? "pisell-lowcode__eft-pay-step-item-warn" : ""
	})) : null, receiptPage === "again" ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-warn-text pisell-lowcode__eft-pay-body" }, locales.getText("page.eftpos-pay.text.signature.text")(modeRef.current)) : null, status === StatusEnum.Loading ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.processing")) : null, status === StatusEnum.Success ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, locales.getText("page.eftpos-pay.text.transaction.end")) : null), !isReceiptPage && status !== StatusEnum.Success ? /* @__PURE__ */ React.createElement(Action, {
		index: custom === null || custom === void 0 ? void 0 : custom.step,
		onCancel,
		disabled
	}) : null, isReceiptPage ? /* @__PURE__ */ React.createElement(ReceiptAction, {
		api,
		onChange: onChangeReceipt
	}) : null);
};
//#endregion
export { windcave_default as default };
