import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import titlebar_default from "./component/header/titlebar.js";
import { EftposEnum, ModeEnum } from "./const.js";
import { getAmonunt, getPayAmonunt } from "./helper.js";
import { updateDevice, updateState, useContextData, useDispatch } from "./store/index.js";
import payLog from "./utils/payLog.js";
import React, { useRef, useState } from "react";
import { Spin, message } from "antd";
import { locales } from "@pisell/utils";
import ChevronRight from "@pisell/icon/es/ChevronRight";
import { useMount, useUnmount } from "ahooks";
import "./device.less";
//#region src/components/eftposPay/device.tsx
/**
* @title: 设备选择页
* @description: 选择设备信息,无设备增加提示;仅有一条,默认选中跳走;多条记录则停留等待用户选择
* @return React.Element
* @Author: hongbing.wang
* @Date: 2024-08-12 11:40
*/
var device_default = ({ api, onChange, onClose, className = "", device_number, isMobile, net, client, formatAmount = (number, precision, symbol) => `${symbol}${number}`, containerStyle = {}, customSurcharge }) => {
	const { isTerminal, interaction } = useEngineContext().appHelper.utils || {};
	const store = useContextData();
	const { device, symbol, mode, eftpos, order_id } = store;
	const [loading, setLoading] = useState(false);
	const [dataStaus, setDataStaus] = useState(true);
	const [list, setList] = useState([]);
	const dispatch = useDispatch();
	const timerRef = useRef();
	/**
	* @title: 设备选择事件
	* @param {*} event
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:02
	*/
	const onClick = (event) => {
		var _list$index;
		if (!net) {
			message.open({
				key: "net-warning",
				type: "warning",
				content: locales.getText("page.eftpos-pay.text.not.connected")
			});
			return;
		}
		const [index] = [Number(event.currentTarget.dataset.index)];
		payLog.log("手动选择设备", {
			deviceId: (_list$index = list[index]) === null || _list$index === void 0 ? void 0 : _list$index.id,
			index
		});
		setDevice(list[index]);
	};
	/**
	* @title 控制原生关闭按钮的显示与隐藏
	* @description hide_close_button:隐藏关闭按钮 show_close_button:显示关闭按钮
	* @param bool 是否显示关闭按钮
	*/
	const triggerCloseButton = (bool) => {
		var _interaction$utils, _interaction$utils$po;
		if (!(isTerminal === null || isTerminal === void 0 ? void 0 : isTerminal())) return;
		interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 || _interaction$utils$po.call(_interaction$utils, {
			module: "pos",
			key: "other",
			data: { key: bool ? "show_close_button" : "hide_close_button" }
		});
	};
	/**
	* @title 隐藏原生关闭按钮，delay后再显示
	* @description Terminal环境，进入设备列表页面初始化默认关闭原生弹窗的loading，5s后如果还是没有调用成功再放开
	*/
	const closeFirstWithDelayShow = () => {
		timerRef.current && clearTimeout(timerRef.current);
		if (!(isTerminal === null || isTerminal === void 0 ? void 0 : isTerminal())) return;
		triggerCloseButton(false);
		timerRef.current = setTimeout(() => {
			triggerCloseButton(true);
		}, 5e3);
	};
	/**
	* 清除定时器
	*/
	const clearTimer = () => {
		if (timerRef.current) {
			clearTimeout(timerRef.current);
			timerRef.current = void 0;
		}
	};
	/**
	* @title: 初始化加载设备列表页
	* @description: 初始化加载设备列表页 若只有一条数据 则直接进入下一步
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:02
	*/
	useMount(() => {
		payLog.log("设备选择页展示");
		setLoading(true);
		closeFirstWithDelayShow();
		api.getDeviceList({
			type: eftpos,
			status: "paired"
		}).then((baseRes) => {
			clearTimer();
			setLoading(false);
			let res = baseRes;
			if (res && Array.isArray(res.list) && res.list.length > 0) {
				console.log("customSurcharge = >>>>>>>>", customSurcharge);
				if (customSurcharge && (!!(customSurcharge === null || customSurcharge === void 0 ? void 0 : customSurcharge.percentage) || !!(customSurcharge === null || customSurcharge === void 0 ? void 0 : customSurcharge.fixed))) res.list = res.list.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { setting: _objectSpread2(_objectSpread2({}, item.setting || {}), {}, {
					surcharge: true,
					constant_rate: Number((customSurcharge === null || customSurcharge === void 0 ? void 0 : customSurcharge.percentage) || 0) * 100,
					constant_money: customSurcharge === null || customSurcharge === void 0 ? void 0 : customSurcharge.fixed
				}) }));
				console.log("eftpos_device_res = >>>>>>>>", res);
				payLog.log("设备列表加载成功", {
					count: res.list.length,
					hasDeviceNumber: !!device_number
				});
				console.log("customSurcharge = ", customSurcharge);
				if (device_number) {
					const hostDeviceList = res.list.filter((item) => {
						var _item$setting;
						return item === null || item === void 0 || (_item$setting = item.setting) === null || _item$setting === void 0 || (_item$setting = _item$setting.devices) === null || _item$setting === void 0 ? void 0 : _item$setting.some((i) => i.number === device_number);
					});
					if (hostDeviceList.length >= 1) {
						setDataStaus(true);
						setList(setDeviceList(hostDeviceList));
						if (hostDeviceList.length === 1) {
							payLog.log("自动选择设备（device_number匹配）", { device: hostDeviceList[0] });
							setDevice(hostDeviceList[0]);
						}
						return;
					}
				}
				setDataStaus(true);
				setList(setDeviceList(res.list));
				if (res.list.length === 1) {
					payLog.log("自动选择设备（单设备）", { device: res.list[0] });
					setDevice(res.list[0]);
				} else triggerCloseButton(true);
				return;
			}
			payLog.log("设备列表为空");
			triggerCloseButton(true);
			setDataStaus(false);
		}, () => {
			clearTimer();
			payLog.log("设备列表加载失败");
			triggerCloseButton(true);
			setDataStaus(false);
			setLoading(false);
		});
	});
	useUnmount(() => {
		timerRef.current && clearTimeout(timerRef.current);
	});
	/**
	* 延时方法：先延时指定时间，然后执行异步检查
	* @param time 延时时间（毫秒），默认 100ms
	* @returns Promise<boolean> 检查结果
	*/
	const checkIsActiveWithDelay = function() {
		var _ref = _asyncToGenerator(function* (time = 100) {
			var _interaction$utils2;
			if (!(isTerminal === null || isTerminal === void 0 ? void 0 : isTerminal())) return true;
			yield new Promise((resolve) => setTimeout(resolve, time));
			if (interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 ? void 0 : _interaction$utils2.asyncDataManager) try {
				var _interaction$utils3, _interaction$utils3$a;
				return (yield interaction === null || interaction === void 0 || (_interaction$utils3 = interaction.utils) === null || _interaction$utils3 === void 0 || (_interaction$utils3$a = _interaction$utils3.asyncDataManager) === null || _interaction$utils3$a === void 0 ? void 0 : _interaction$utils3$a.call(_interaction$utils3, {
					module: "get",
					key: "pay_webview_active"
				})) !== "unActive";
			} catch (error) {
				return true;
			}
			return true;
		});
		return function checkIsActiveWithDelay() {
			return _ref.apply(this, arguments);
		};
	}();
	const setDevice = function() {
		var _ref2 = _asyncToGenerator(function* (device) {
			payLog.setContext({ deviceId: device === null || device === void 0 ? void 0 : device.id });
			dispatch(updateDevice({ device }));
			if (typeof api.selectDevice === "function") api.selectDevice(device);
			if (typeof onChange === "function") {
				if (mode === ModeEnum.Pay) {
					triggerCloseButton(false);
					const isActive = yield checkIsActiveWithDelay(100);
					if (!isActive) {
						payLog.log("页面非活跃状态，阻断支付", {
							order_id,
							isActive
						});
						return;
					}
					if (device.pay) dispatch(updateState({ pay: device.pay }));
					else dispatch(updateState({ pay: getPayAmonunt(getAmonunt(_objectSpread2(_objectSpread2({}, store), {}, { device })), (total) => formatAmount(total, 2, symbol)) }));
				}
				onChange("page", mode === ModeEnum.FullPay ? "amount" : "pay");
			}
		});
		return function setDevice(_x) {
			return _ref2.apply(this, arguments);
		};
	}();
	const setDeviceList = (list) => {
		return list.map((item) => {
			const pay = getPayAmonunt(getAmonunt(_objectSpread2(_objectSpread2({}, store), {}, { device: item })), (total) => formatAmount(total, 2, symbol));
			return _objectSpread2(_objectSpread2({}, item), {}, { pay });
		});
	};
	return /* @__PURE__ */ React.createElement("div", { className: `pisell-lowcode__eft-pay-device-box ${className}` }, isMobile ? null : /* @__PURE__ */ React.createElement(titlebar_default, {
		type: "left-title-close",
		onClose
	}, dataStaus ? locales.getText("page.eftpos-pay.text.device") : ""), dataStaus ? /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__eft-pay-device-list",
		style: _objectSpread2(_objectSpread2({}, isMobile ? { marginTop: "20px" } : {}), containerStyle || {})
	}, /* @__PURE__ */ React.createElement(Spin, {
		spinning: loading,
		size: "large",
		style: {
			flex: 1,
			overflow: "auto",
			minHeight: "200px"
		}
	}, /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		gap: "10px"
	} }, list.map(({ id, name, pay, connection }, index) => {
		var _connection$response;
		return /* @__PURE__ */ React.createElement("div", {
			key: id,
			className: `pisell-lowcode__eft-pay-device ${id === (device === null || device === void 0 ? void 0 : device.id) ? "active" : ""}`,
			"data-index": index,
			onClick,
			role: "button",
			tabIndex: index
		}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-content" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-name" }, name), mode === ModeEnum.Refund ? null : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-money" }, pay.totalUnit), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-sucharge" }, locales.getText("page.eftpos-pay.text.surcharge.edit.inc.surcharge"), ": ", formatAmount(`${pay.surcharge}`, 2, symbol), " (", locales.getText("page.eftpos-pay.text.surcharge.edit.rate"), ":", pay.surRate, "% +", " ", formatAmount(`${pay.surMoney}`, 2, symbol), ")"), eftpos === EftposEnum.MX51 ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-sucharge" }, "Pairing ID: ", connection === null || connection === void 0 || (_connection$response = connection.response) === null || _connection$response === void 0 ? void 0 : _connection$response.pairing_id) : null)), /* @__PURE__ */ React.createElement("div", { style: { flexShrink: 0 } }, /* @__PURE__ */ React.createElement(ChevronRight, { style: {
			fontWeight: "600",
			fontSize: "24px"
		} })));
	})))) : /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__eft-pay-device-error",
		style: isMobile ? { marginTop: "20px" } : {}
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-tit" }, locales.getText("page.eftpos-pay.text.device.no.title")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, locales.getText("page.eftpos-pay.text.device.no.add")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, locales.getText("page.eftpos-pay.text.device.no.web")), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, locales.getText("page.eftpos-pay.text.device.no.terminal"))));
};
//#endregion
export { device_default as default };
