const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_titlebar = require("./component/header/titlebar.js");
const require_const = require("./const.js");
const require_helper = require("./helper.js");
const require_index = require("./store/index.js");
const require_payLog = require("./utils/payLog.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_icon_es_ChevronRight = require("@pisell/icon/es/ChevronRight");
_pisell_icon_es_ChevronRight = require_runtime.__toESM(_pisell_icon_es_ChevronRight);
let ahooks = require("ahooks");
require("./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 } = require_useEngineContext.default().appHelper.utils || {};
	const store = require_index.useContextData();
	const { device, symbol, mode, eftpos, order_id } = store;
	const [loading, setLoading] = (0, react.useState)(false);
	const [dataStaus, setDataStaus] = (0, react.useState)(true);
	const [list, setList] = (0, react.useState)([]);
	const dispatch = require_index.useDispatch();
	const timerRef = (0, react.useRef)();
	/**
	* @title: 设备选择事件
	* @param {*} event
	* @Author: hongbing.wang
	* @Date: 2024-08-20 13:02
	*/
	const onClick = (event) => {
		var _list$index;
		if (!net) {
			antd.message.open({
				key: "net-warning",
				type: "warning",
				content: _pisell_utils.locales.getText("page.eftpos-pay.text.not.connected")
			});
			return;
		}
		const [index] = [Number(event.currentTarget.dataset.index)];
		require_payLog.default.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
	*/
	(0, ahooks.useMount)(() => {
		require_payLog.default.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) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, { setting: require_objectSpread2._objectSpread2(require_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);
				require_payLog.default.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) {
							require_payLog.default.log("自动选择设备（device_number匹配）", { device: hostDeviceList[0] });
							setDevice(hostDeviceList[0]);
						}
						return;
					}
				}
				setDataStaus(true);
				setList(setDeviceList(res.list));
				if (res.list.length === 1) {
					require_payLog.default.log("自动选择设备（单设备）", { device: res.list[0] });
					setDevice(res.list[0]);
				} else triggerCloseButton(true);
				return;
			}
			require_payLog.default.log("设备列表为空");
			triggerCloseButton(true);
			setDataStaus(false);
		}, () => {
			clearTimer();
			require_payLog.default.log("设备列表加载失败");
			triggerCloseButton(true);
			setDataStaus(false);
			setLoading(false);
		});
	});
	(0, ahooks.useUnmount)(() => {
		timerRef.current && clearTimeout(timerRef.current);
	});
	/**
	* 延时方法：先延时指定时间，然后执行异步检查
	* @param time 延时时间（毫秒），默认 100ms
	* @returns Promise<boolean> 检查结果
	*/
	const checkIsActiveWithDelay = function() {
		var _ref = require_asyncToGenerator._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 = require_asyncToGenerator._asyncToGenerator(function* (device) {
			require_payLog.default.setContext({ deviceId: device === null || device === void 0 ? void 0 : device.id });
			dispatch(require_index.updateDevice({ device }));
			if (typeof api.selectDevice === "function") api.selectDevice(device);
			if (typeof onChange === "function") {
				if (mode === require_const.ModeEnum.Pay) {
					triggerCloseButton(false);
					const isActive = yield checkIsActiveWithDelay(100);
					if (!isActive) {
						require_payLog.default.log("页面非活跃状态，阻断支付", {
							order_id,
							isActive
						});
						return;
					}
					if (device.pay) dispatch(require_index.updateState({ pay: device.pay }));
					else dispatch(require_index.updateState({ pay: require_helper.getPayAmonunt(require_helper.getAmonunt(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, store), {}, { device })), (total) => formatAmount(total, 2, symbol)) }));
				}
				onChange("page", mode === require_const.ModeEnum.FullPay ? "amount" : "pay");
			}
		});
		return function setDevice(_x) {
			return _ref2.apply(this, arguments);
		};
	}();
	const setDeviceList = (list) => {
		return list.map((item) => {
			const pay = require_helper.getPayAmonunt(require_helper.getAmonunt(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, store), {}, { device: item })), (total) => formatAmount(total, 2, symbol));
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, { pay });
		});
	};
	return /* @__PURE__ */ react.default.createElement("div", { className: `pisell-lowcode__eft-pay-device-box ${className}` }, isMobile ? null : /* @__PURE__ */ react.default.createElement(require_titlebar.default, {
		type: "left-title-close",
		onClose
	}, dataStaus ? _pisell_utils.locales.getText("page.eftpos-pay.text.device") : ""), dataStaus ? /* @__PURE__ */ react.default.createElement("div", {
		className: "pisell-lowcode__eft-pay-device-list",
		style: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, isMobile ? { marginTop: "20px" } : {}), containerStyle || {})
	}, /* @__PURE__ */ react.default.createElement(antd.Spin, {
		spinning: loading,
		size: "large",
		style: {
			flex: 1,
			overflow: "auto",
			minHeight: "200px"
		}
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		gap: "10px"
	} }, list.map(({ id, name, pay, connection }, index) => {
		var _connection$response;
		return /* @__PURE__ */ react.default.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.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-content" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-name" }, name), mode === require_const.ModeEnum.Refund ? null : /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-money" }, pay.totalUnit), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-sucharge" }, _pisell_utils.locales.getText("page.eftpos-pay.text.surcharge.edit.inc.surcharge"), ": ", formatAmount(`${pay.surcharge}`, 2, symbol), " (", _pisell_utils.locales.getText("page.eftpos-pay.text.surcharge.edit.rate"), ":", pay.surRate, "% +", " ", formatAmount(`${pay.surMoney}`, 2, symbol), ")"), eftpos === require_const.EftposEnum.MX51 ? /* @__PURE__ */ react.default.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.default.createElement("div", { style: { flexShrink: 0 } }, /* @__PURE__ */ react.default.createElement(_pisell_icon_es_ChevronRight.default, { style: {
			fontWeight: "600",
			fontSize: "24px"
		} })));
	})))) : /* @__PURE__ */ react.default.createElement("div", {
		className: "pisell-lowcode__eft-pay-device-error",
		style: isMobile ? { marginTop: "20px" } : {}
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-tit" }, _pisell_utils.locales.getText("page.eftpos-pay.text.device.no.title")), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, _pisell_utils.locales.getText("page.eftpos-pay.text.device.no.add")), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, _pisell_utils.locales.getText("page.eftpos-pay.text.device.no.web")), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, _pisell_utils.locales.getText("page.eftpos-pay.text.device.no.terminal"))));
};
//#endregion
exports.default = device_default;
