import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { ClientEnum, PayStatus, StatusEnum } from "../const.js";
import { StemTypeEnum, StepStatusEnum, getStepMapping } from "./const.js";
import { updateComponent, updateCustom, updateKey, updateState, updateStatus, useContextData, useDispatch } from "../store/index.js";
import { useStoreRef } from "../hooks.js";
import XhrTimer from "./timer.js";
import { useCallback, useEffect, useRef } from "react";
import { locales } from "@pisell/utils";
//#region src/components/eftposPay/windcave/helper.tsx
const Max4004 = 1;
/**
* @title: windcave 支付,退款,查询 错误逻辑处理
* @description: 动态步骤页 异常前往 FailCustom 页面
* @return null
* @Author: hongbing.wang
* @Date: 2024-08-12 10:29
*/
const useFail = () => {
	const dispatch = useDispatch();
	const { custom } = useContextData();
	const { modeRef, clientRef } = useStoreRef();
	const ref = useRef((custom === null || custom === void 0 ? void 0 : custom.retry) || 0);
	useEffect(() => {
		ref.current = (custom === null || custom === void 0 ? void 0 : custom.retry) || 0;
	}, [custom === null || custom === void 0 ? void 0 : custom.retry]);
	return useCallback((res, isMark = false) => {
		if (!res || !res.code) {
			dispatch(updateCustom({ errorStatus: "unknow" }));
			dispatch(updateState({ status: "fail" }));
			if (clientRef.current === ClientEnum.Merchant) dispatch(updateComponent("UnknowFail"));
			else dispatch(updateComponent("Prompt"));
			return;
		}
		const [code] = [`${res.code}`];
		if (`${res.code}` === PayStatus.Unknown) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.fail"),
				warn: null,
				title: locales.getText("page.eftpos-pay.text.failed")(modeRef.current)
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		console.log(code, ref.current, Max4004);
		if (code === PayStatus.NoPay) {
			if (ref.current > Max4004) {
				dispatch(updateCustom({
					retry: 0,
					failCustom: {
						isPosNetworkError: false,
						status: "fail",
						fail: locales.getText("page.eftpos-pay.text.transaction.fail"),
						warn: null,
						titl: locales.getText("page.eftpos-pay.text.failed")(modeRef.current)
					}
				}));
				dispatch(updateComponent("FailCustom"));
				return;
			}
			ref.current += 1;
			dispatch(updateState({ number: "" }));
			dispatch(updateCustom({
				retry: ref.current,
				list: []
			}));
			dispatch(updateKey(Date.now()));
			return;
		}
		if (code === PayStatus.PayTimeout) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.fail.timeout"),
				title: locales.getText("page.eftpos-pay.text.failed")(modeRef.current),
				warn: null
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		if (code === PayStatus.Timeout) {
			if (isMark) {
				dispatch(updateState({ manual: {
					title: locales.getText("page.eftpos-pay.text.timedout.title"),
					text: locales.getText("page.eftpos-pay.text.timedout.text")(modeRef.current)
				} }));
				if (clientRef.current === ClientEnum.Merchant) dispatch(updateComponent("Manual"));
				else dispatch(updateComponent("Prompt"));
				return;
			}
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.fail.timeout"),
				title: locales.getText("page.eftpos-pay.text.failed")(modeRef.current),
				warn: null
			} }));
			dispatch(updateComponent("Prompt"));
			return;
		}
		if (code === PayStatus.PayOtherEftposFailed) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.fail.terminal"),
				title: locales.getText("page.eftpos-pay.text.transaction.fail.terminal.title"),
				warn: null
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		if (code === PayStatus.PayCardErrorFailed) {
			dispatch(updateCustom({ failCustom: {
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.fail.cancel"),
				title: locales.getText("page.eftpos-pay.text.transaction.fail.cancel.title"),
				warn: null
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		if (code === PayStatus.NoNetWork || code === PayStatus.SocketError) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: true,
				status: "warn",
				fail: null,
				title: locales.getText("page.eftpos-pay.text.interrupted"),
				warn: `${locales.getText("page.eftpos-pay.text.transaction.eftpos.fail.title")}\n${locales.getText("page.eftpos-pay.text.transaction.eftpos.fail.power")}\n ${locales.getText("page.eftpos-pay.text.transaction.eftpos.fail.device")}\n${locales.getText("page.eftpos-pay.text.transaction.eftpos.fail.network")}\n${locales.getText("page.eftpos-pay.text.transaction.eftpos.fail.if")(modeRef.current)}`
			} }));
			if (clientRef.current === ClientEnum.Merchant) dispatch(updateComponent("FailCustom"));
			else dispatch(updateComponent("Prompt"));
			return;
		}
		if (code === PayStatus.PayBankRefuses) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.back.declined.text"),
				title: locales.getText("page.eftpos-pay.text.transaction.back.declined.title"),
				warn: null
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		if (code === PayStatus.SignatureDeclined) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.user.declined.text"),
				title: locales.getText("page.eftpos-pay.text.transaction.user.declined.title"),
				warn: null
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		if (code === PayStatus.UserConfigError) {
			dispatch(updateCustom({ failCustom: {
				isPosNetworkError: false,
				status: "fail",
				fail: locales.getText("page.eftpos-pay.text.transaction.user.config.text"),
				title: locales.getText("page.eftpos-pay.text.transaction.user.config.title"),
				warn: null
			} }));
			dispatch(updateComponent("FailCustom"));
			return;
		}
		dispatch(updateCustom({ errorStatus: "unknow" }));
		dispatch(updateComponent("UnknowFail"));
	}, [dispatch]);
};
/**
* @title: 轮询 check 接口
* @description: 轮询 终止条件 1.超时 , 2. 返回非200状态码 , 3. 外部关闭
* @return [run, XhrTimer] run: 启动函数 , XhrTimer 轮询类
* @Author: hongbing.wang
* @Date: 2024-08-12 10:30
*/
const useValidate = (check, num, onChange) => {
	const unloadRef = useRef(false);
	const dispatch = useDispatch();
	const failRef = useRef(useFail());
	const ref = useRef();
	const { custom } = useContextData();
	const { netRef, payRef, numRef, modeRef, clientRef } = useStoreRef();
	const stepRef = useRef(custom === null || custom === void 0 ? void 0 : custom.step);
	const listRef = useRef(custom === null || custom === void 0 ? void 0 : custom.list);
	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]);
	const watchRef = useRef();
	const run = useCallback((timeout) => {
		var _ref$current2, _ref$current3;
		if (timeout === -1) console.log("无限加载");
		else console.log("计时加载 ", typeof timeout === "number" ? timeout : num);
		if (unloadRef.current) {
			var _ref$current;
			(_ref$current = ref.current) === null || _ref$current === void 0 || _ref$current.close();
			return;
		}
		if (!watchRef.current || !netRef.current) return;
		(_ref$current2 = ref.current) === null || _ref$current2 === void 0 || _ref$current2.close();
		ref.current = new XhrTimer({
			xhr: check,
			timeout: typeof timeout === "number" ? timeout : num,
			callback: watchRef.current
		});
		(_ref$current3 = ref.current) === null || _ref$current3 === void 0 || _ref$current3.run({ number: numRef.current }).then((res) => {
			if (unloadRef.current) return;
			if (!netRef.current) return;
			if (!res || Number(res.code) !== 200) return Promise.reject(res);
		}).catch((res) => {
			var _failRef$current;
			if (unloadRef.current) return;
			if (!netRef.current) return;
			if (res && res.code === -1) return;
			(_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, res, stepRef.current >= StepStatusEnum.Account);
		});
	}, [check, num]);
	useEffect(() => {
		/**
		* @title: 轮询结果处理
		* @description: 将轮询结果进行处理,根据不同的轮询结果进行不同的业务逻辑处理
		* @param {any} res 轮询接口范湖遗址
		* @return null
		* @Author: hongbing.wang
		* @Date: 2024-08-12 12:42
		*/
		watchRef.current = (res, isRun) => {
			if (unloadRef.current) {
				var _ref$current4;
				(_ref$current4 = ref.current) === null || _ref$current4 === void 0 || _ref$current4.close();
				return;
			}
			if (!res || !res.data || !res.data.txn_status_id) {
				var _ref$current5;
				(_ref$current5 = ref.current) === null || _ref$current5 === void 0 || _ref$current5.close();
			}
			const [txn_status_id, status_id, complete] = [
				Number(res.data.txn_status_id),
				Number(res.data.status_id),
				Number(res.data.complete)
			];
			if (txn_status_id === StepStatusEnum.Wait && status_id === 6 && complete === 1) {
				var _ref$current6;
				(_ref$current6 = ref.current) === null || _ref$current6 === void 0 || _ref$current6.close();
				if (stepRef.current !== txn_status_id && listRef.current.every(({ index }) => txn_status_id !== index)) {
					var _payRef$current;
					const current = listRef.current.map((item) => {
						if (Number(item === null || item === void 0 ? void 0 : item.index) < Number(stepRef.current)) return _objectSpread2(_objectSpread2({}, item), {}, { status: "resolve" });
						return item;
					});
					const nextStep = getStepMapping(txn_status_id, {
						money: (_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.totalUnit,
						mode: modeRef.current
					});
					if (nextStep) current.push(nextStep);
					dispatch(updateCustom({
						list: current,
						step: txn_status_id
					}));
				}
				onChange(res.data);
				return;
			}
			if (stepRef.current !== txn_status_id && listRef.current.every(({ index }) => txn_status_id !== index)) {
				var _ref$current7, _payRef$current2;
				console.log("self.flag  stepRef.current, txn_status_id ", stepRef.current, txn_status_id);
				stepRef.current = txn_status_id;
				(_ref$current7 = ref.current) === null || _ref$current7 === void 0 || _ref$current7.close();
				const current = listRef.current.map((item) => {
					if (Number(item === null || item === void 0 ? void 0 : item.index) < Number(stepRef.current)) return _objectSpread2(_objectSpread2({}, item), {}, { status: "resolve" });
					return item;
				});
				const nextStep = getStepMapping(txn_status_id, {
					money: (_payRef$current2 = payRef.current) === null || _payRef$current2 === void 0 ? void 0 : _payRef$current2.totalUnit,
					mode: modeRef.current
				});
				if (nextStep) {
					current.push(nextStep);
					if (nextStep.type === StemTypeEnum.Passive) dispatch(updateStatus(StatusEnum.Question));
					if (nextStep.index === StepStatusEnum.Receipt) dispatch(updateState({ title: locales.getText("page.eftpos-pay.text.waiting.signature") }));
				}
				dispatch(updateCustom({
					list: current,
					step: txn_status_id
				}));
				txn_status_id === StepStatusEnum.Receipt ? run(-1) : run();
				return;
			}
			if (isRun) run();
		};
	}, [
		dispatch,
		onChange,
		run
	]);
	useEffect(() => () => {
		var _ref$current8;
		(_ref$current8 = ref.current) === null || _ref$current8 === void 0 || _ref$current8.close();
		unloadRef.current = true;
	}, []);
	return [
		run,
		watchRef,
		ref
	];
};
//#endregion
export { useFail, useValidate };
