import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import { ClientEnum, ModeEnum, PayStatus, StatusEnum } from "../const.js";
import { getPayParams, getUuid } from "../helper.js";
import { updateComponent, updateCustom, updateNextStep, updateState, useContextData, useDispatch } from "../store/index.js";
import step_default from "../component/step/index.js";
import { useFail, useStoreRef } from "../hooks.js";
import payLog from "../utils/payLog.js";
import { useValidate } from "./hooks.js";
import { ActionType, usePayment } from "./payment.js";
import React, { useEffect, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
//#region src/components/eftposPay/payo/config.tsx
const _excluded = ["key"];
const POS = ({ api, onChange }) => {
	const { steps, custom } = useContextData();
	const { deviceRef, payRef, numRef, statusRef, modeRef, netRef, orderIdRef, amountRef, eftposRef, dataRef } = useStoreRef();
	const dispatch = useDispatch();
	const _steps$ = steps[0], { key } = _steps$, props = _objectWithoutProperties(_steps$, _excluded);
	const fail = useFail(0);
	const failRef = useRef(fail);
	const controllerRef = useRef();
	const clearRef = useRef(null);
	const initRef = useRef(false);
	const unloadRef = useRef(false);
	const [check] = useValidate(1e3 * 60);
	const { run: paymentRun, clean: paymentClean } = usePayment({
		payApi: api.pay,
		checkApi: api.check,
		shouldContinue: () => {
			return !(unloadRef.current || !netRef.current);
		}
	});
	useEffect(() => {
		failRef.current = fail;
	}, [fail]);
	/**
	* @title: 支付,退款,查询 成功 后续逻辑处理
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:34
	*/
	const success = (res) => {
		var _res$data, _res$data2, _res$data3, _res$data4;
		let receipt = Array.isArray(res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.receipt) ? res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.receipt : [res === null || res === void 0 || (_res$data3 = res.data) === null || _res$data3 === void 0 ? void 0 : _res$data3.receipt];
		receipt = receipt.filter((item) => typeof item === "string").filter(Boolean);
		dispatch(updateNextStep());
		dispatch(updateCustom({
			card_reader_surcharge: (res === null || res === void 0 || (_res$data4 = res.data) === null || _res$data4 === void 0 ? void 0 : _res$data4.card_reader_surcharge) || 0,
			receipt
		}));
		clearRef.current = setTimeout(() => {
			var _res$data5, _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 || (_res$data5 = res.data) === null || _res$data5 === void 0 ? void 0 : _res$data5.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);
	};
	/**
	* @title: 检查支付状态
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:53
	*/
	const checkApi = () => {
		check(api.check, numRef.current).then((res) => {
			if (unloadRef.current || !netRef.current) return;
			if (res && `${res.code}` === "200") {
				success(res);
				return;
			}
			failRef.current(res, true);
		}, (res) => {
			if (unloadRef.current || !netRef.current) return;
			failRef.current(res, true);
		});
	};
	/**
	* @title: 支付,退款,查询 初始化逻辑处理
	* @Author: hongbing.wang
	* @Date: 2024-08-12 10:14
	*/
	useEffect(() => {
		var _deviceRef$current2, _deviceRef$current3;
		if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) return;
		if (initRef.current) return;
		initRef.current = true;
		if (numRef.current) {
			checkApi();
			return;
		}
		numRef.current = getUuid();
		dispatch(updateState({ number: numRef.current }));
		controllerRef.current = new AbortController();
		const isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
		const apiParams = isPay ? _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
		} : {}), {}, {
			original_amount: payRef.current.amount,
			service_charge: {
				amount: payRef.current.surMoney,
				percentage: payRef.current.surPercentRate
			},
			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 })))))
		}) : {
			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,
			original_payment_number: custom === null || custom === void 0 ? void 0 : custom.original_payment_number,
			pay_param_base64: encodeURIComponent(btoa(encodeURIComponent(JSON.stringify(_objectSpread2(_objectSpread2({}, dataRef.current), {}, { number: numRef.current })))))
		};
		payLog.setContext({ transactionNumber: numRef.current });
		if (isPay) {
			var _deviceRef$current4;
			payLog.log("Payo：发起支付", {
				isPay,
				number: numRef.current
			});
			paymentRun({
				paymentType: ActionType.Pay,
				paymentNum: numRef.current,
				orderId: orderIdRef.current,
				deviceId: (_deviceRef$current4 = deviceRef.current) === null || _deviceRef$current4 === void 0 ? void 0 : _deviceRef$current4.id,
				params: apiParams,
				callbacks: {
					onSuccess: (res) => {
						payLog.log("Payo：支付成功", { code: res === null || res === void 0 ? void 0 : res.code });
						success(res);
					},
					onError: (err) => {
						payLog.log("Payo：支付失败", { code: err === null || err === void 0 ? void 0 : err.code });
						failRef.current(err, true);
					}
				}
			});
			return;
		} else {
			payLog.log("Payo：发起退款", {
				isPay,
				number: numRef.current
			});
			api.refund(apiParams, { signal: controllerRef.current.signal }).then((res) => {
				console.log("netRef.current111 = ", netRef.current);
				if (unloadRef.current || !netRef.current) {
					payLog.log("Payo：退款拦截", {
						isUnload: unloadRef.current,
						isNet: netRef.current
					});
					return;
				}
				if (res && `${res.code}` === "200") {
					payLog.log("Payo：退款成功", { res: JSON.stringify(res) });
					success(res);
					return;
				}
				return Promise.reject(res);
			}).catch((err) => {
				if (unloadRef.current || !netRef.current) {
					payLog.log("Payo：退款失败拦截", {
						isUnload: unloadRef.current,
						isNet: netRef.current
					});
					return;
				}
				if (!(err === null || err === void 0 ? void 0 : err.code) || `${err.code}` === PayStatus.Timeout) {
					payLog.log("Payo：退款超时，转查询");
					checkApi();
					return;
				}
				payLog.log("Payo：退款失败", {
					code: err === null || err === void 0 ? void 0 : err.code,
					message: err === null || err === void 0 ? void 0 : err.message
				});
				failRef.current(err, true);
			});
		}
	}, [
		api,
		check,
		dispatch,
		onChange
	]);
	useEffect(() => () => {
		var _controllerRef$curren;
		(_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || _controllerRef$curren.abort();
		unloadRef.current = true;
		if (clearRef.current) clearTimeout(clearRef.current);
		paymentClean();
	}, []);
	return /* @__PURE__ */ React.createElement(step_default, props);
};
const Action = ({ onChange }) => {
	const dispatch = useDispatch();
	const { mode, client, order_id, number, device } = useContextData();
	const [isShowCancel, setIsShowCancel] = useState(false);
	useEffect(() => {
		const timer = setTimeout(() => {
			setIsShowCancel(true);
			payLog.log("Payo：30秒后显示取消按钮");
		}, 30 * 1e3);
		return () => {
			clearTimeout(timer);
		};
	}, []);
	/**
	* @title: 前往手动标记页
	* @Author: hongbing.wang
	* @Date: 2024-08-20 12:18
	*/
	const onManually = () => {
		payLog.log("Payo：点击手动标记");
		dispatch(updateState({ manual: {
			title: locales.getText("page.eftpos-pay.text.request.title")(mode),
			text: locales.getText("page.eftpos-pay.text.request.text")(mode)
		} }));
		dispatch(updateComponent("Manual", true));
	};
	const onCancel = () => {
		payLog.log("Payo：点击取消");
		onChange("fail", {
			number,
			uniquePaymentNumber: number,
			device,
			order_id
		});
	};
	return /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, client !== ClientEnum.Merchant && isShowCancel && /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: onCancel
	}, locales.getText("page.eftpos-pay.text.cancel")), client === ClientEnum.Merchant ? /* @__PURE__ */ React.createElement(Button, {
		block: true,
		className: "pisell-lowcode__eft-pay-step-item-btn",
		onClick: onManually
	}, locales.getText("page.eftpos-pay.text.manual.marking")) : null);
};
//#endregion
export { Action, POS };
