import { getLocale } from "../../utils/locales.js";
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 Drawer$2 from "../booking/components/drawer/index.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import { request } from "../../utils/index.js";
import { DeviceEnum, Eftpos, TYPES_WITH_MERCHANT_SETTINGS, getCommByFields, getDefaultValue } from "./const.js";
import table_default from "./table.js";
import Device from "./device.js";
import PosForm from "./pos.js";
import { useCheckPairRequest, usePairRequest, usePairTerminalo } from "./hooks.js";
import Log from "./log.js";
import locales_default from "./locales.js";
import apiKey_default from "./icon/apiKey.js";
import device_default from "./icon/device.js";
import { usePairModal } from "./PairModal/hooks.js";
import PairModal from "./PairModal/index.js";
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
import { Form, Input, Spin, message } from "antd";
import { locales } from "@pisell/utils";
import { Image as Image$1 } from "@pisell/materials";
import mx51SCISvg from "./assets/mx51SCI.svg";
import "./index.less";
//#region src/components/eftpos/index.tsx
locales.init(locales_default, getLocale());
const PosTabs = forwardRef(({ Table, PosForm, style, onChange }, ref) => {
	const [active, setActive] = useState("device");
	/**
	* @title: 切换tab
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:18
	*/
	const onClick = (event) => {
		const target = event.currentTarget;
		if (!target) return;
		const { key } = target.dataset;
		if (key) {
			setActive(key);
			onChange(key);
		}
	};
	useImperativeHandle(ref, () => ({ setActive }));
	const items = [{
		key: "device",
		label: (active) => /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__pos_tabs-tab-label" }, /* @__PURE__ */ React.createElement("div", { className: `pisell-lowcode__pos_circle ${active ? "active" : ""}` }, /* @__PURE__ */ React.createElement(apiKey_default, { color: active ? "#fff" : "#98A2B3" })), /* @__PURE__ */ React.createElement("span", { className: `pisell-lowcode__pos_tabs-tab-label-tlt ${active ? "active" : ""}` }, locales.getText("page.eftpos.text.device"))),
		children: Table
	}, {
		key: "setting",
		label: (active) => /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__pos_tabs-tab-label" }, /* @__PURE__ */ React.createElement("div", { className: `pisell-lowcode__pos_circle ${active ? "active" : ""}` }, /* @__PURE__ */ React.createElement(device_default, { color: active ? "#fff" : "#98A2B3" })), /* @__PURE__ */ React.createElement("span", { className: `pisell-lowcode__pos_tabs-tab-label-tlt ${active ? "active" : ""}` }, locales.getText("page.eftpos.text.setting"))),
		children: PosForm
	}];
	return /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__pos_tabs",
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__pos_tabs-nav" }, items.map((item) => {
		return /* @__PURE__ */ React.createElement("div", {
			key: item.key,
			style: { display: "contents" },
			"data-key": item.key,
			onClick
		}, item.label(active === item.key));
	})), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__pos_tab-content" }, items.map((item) => {
		return /* @__PURE__ */ React.createElement("div", {
			className: `pisell-lowcode__pos_tabs-tabpane ${active === item.key ? "active" : ""}`,
			key: item.key
		}, item.children);
	})));
});
var eftpos_default = (props) => {
	const { name, zIndex, type = Eftpos.Payo, tableSize, getList, getField, getComm, onDel, onEdit, getPosComm, savePos, config, tyroUrl, tyroVersion, useTyroLog } = props;
	const utils = useEngineContext().appHelper.utils || {};
	request.setRequest(utils === null || utils === void 0 ? void 0 : utils.request);
	const [page, setPage] = useState("list");
	const [messageApi, contextHolder] = message.useMessage({ prefixCls: "pisell-lowcode__pos_message" });
	const [loading, setLoading] = useState(false);
	const [status, setStatus] = useState(DeviceEnum.Add);
	const tableRef = useRef();
	const deviceIdRef = useRef("");
	const [deviceItemList, setDeviceCommList] = useState([]);
	const [posItemList, setPosCommList] = useState([]);
	const [deviceItem, setDeviceItem] = useState();
	const [pairStatus, setPairStatus] = useState("");
	const [pairMessage, setPairMessage] = useState("");
	const [systemConfigStatus, setSystemConfigStatus] = useState(true);
	const posTabRef = useRef(null);
	const [posLoading, setPosLoading] = useState(false);
	const pairModalHook = usePairModal();
	const pairRequest = usePairRequest();
	const checkPairRequest = useCheckPairRequest();
	/**
	* @title: 删除设备
	* @param {string} id 设备id
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:20
	*/
	const onDelDevice = (id) => {
		return onDel(id);
	};
	/**
	* @title: 编辑设备
	* @param {any} device 设备信息
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:20
	*/
	const onEditDevice = function() {
		var _ref = _asyncToGenerator(function* (device) {
			if (device) {
				deviceIdRef.current = device.id;
				const list = yield getCommByFields({
					field: getField(type, DeviceEnum.Edit),
					value: device,
					getComm
				});
				setStatus(DeviceEnum.Edit);
				setDeviceCommList(list);
				setPage("edit");
				return;
			}
			setStatus(DeviceEnum.Add);
			const list = yield getCommByFields({
				field: getField(type),
				getComm
			});
			console.log(list);
			setDeviceCommList(list);
			setPage("edit");
		});
		return function onEditDevice(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* @title: 重连设备
	* @description: 编辑第三方设备信息
	* @param {any} device
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:21
	*/
	const onRepair = function() {
		var _ref2 = _asyncToGenerator(function* (device) {
			console.log("onRepair device = ", device);
			if (type === Eftpos.MX51) try {
				setLoading(true);
				const checkPairResponse = yield checkPairRequest.run({
					type,
					pair_response: device === null || device === void 0 ? void 0 : device.response
				});
				console.log("checkPairResponse = ", checkPairResponse);
				if ((checkPairResponse === null || checkPairResponse === void 0 ? void 0 : checkPairResponse.code) == 200) {
					messageApi.open({
						type: "warning",
						style: { zIndex: (zIndex || 9999) + 1 },
						content: locales.getText("page.eftpos.text.repair.message.warning")
					});
					return;
				}
			} catch (error) {
				console.error("onRepair error =>", error);
			} finally {
				setLoading(false);
			}
			const list = yield getCommByFields({
				field: getField(type, DeviceEnum.Repair),
				value: device,
				getComm
			});
			deviceIdRef.current = device.id;
			setDeviceCommList(list);
			setStatus(DeviceEnum.Repair);
			setPage("edit");
		});
		return function onRepair(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const pair = usePairTerminalo(type, {
		url: tyroUrl,
		version: tyroVersion
	});
	const onLog = (device) => {
		console.log(device);
		setDeviceItem(device);
		setPage("log");
	};
	/**
	* @title: 保存设备信息
	* @description: tyro 在新增与重连时候需在前端进行重连
	* @param {any} device 设备信息
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:21
	*/
	const onSave = function() {
		var _ref4 = _asyncToGenerator(function* (device, pair_response) {
			console.log("device = ", device);
			console.log("pair_response = ", pair_response);
			const update = function() {
				var _ref3 = _asyncToGenerator(function* () {
					try {
						yield onEdit(_objectSpread2(_objectSpread2({}, device), {}, {
							type,
							pair_response
						}), status || "add");
						if (type === Eftpos.MX51 && (status === DeviceEnum.Add || status === DeviceEnum.Repair)) {
							var _device$connection;
							messageApi.open({
								type: "success",
								style: { zIndex: (zIndex || 9999) + 1 },
								content: /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__pos_message-custom-content_mx51" }, /* @__PURE__ */ React.createElement("span", null, "Terminal paired successfully."), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", null, "Pairing Name: ", (device === null || device === void 0 || (_device$connection = device.connection) === null || _device$connection === void 0 ? void 0 : _device$connection.pairing_nickname) || "-"), /* @__PURE__ */ React.createElement("span", null, "Pairing ID: ", (pair_response === null || pair_response === void 0 ? void 0 : pair_response.pairing_id) || "-")))
							});
						}
					} catch (error) {
						console.error("onSave error =>", error);
						messageApi.open({
							type: "error",
							style: { zIndex: (zIndex || 9999) + 1 },
							content: (error === null || error === void 0 ? void 0 : error.message) || locales.getText("page.eftpos.text.pair.error")
						});
						return;
					} finally {
						setLoading(false);
					}
					yield tableRef.current.loadData();
					setPage("list");
				});
				return function update() {
					return _ref3.apply(this, arguments);
				};
			}();
			setLoading(true);
			if (type === "tyro" && status !== "edit") {
				pair(_objectSpread2(_objectSpread2({}, config), device.connection), (response) => {
					console.log("response =", response);
					setPairStatus(response.status);
					setPairMessage(response.message);
					if (response.status === "inProgress") {
						messageApi.open({
							type: "info",
							style: { zIndex: (zIndex || 9999) + 1 },
							content: response.message
						});
						return;
					}
					if (response.status === "success") {
						messageApi.open({
							type: "success",
							style: { zIndex: (zIndex || 9999) + 1 },
							content: response.message
						});
						device.connection.integrationKey = response.integrationKey;
						device.status = "paired";
						update();
						return;
					}
					messageApi.open({
						type: "warning",
						style: { zIndex: (zIndex || 9999) + 1 },
						content: response.message
					});
					device.status = "unpaired";
					update();
				});
				return;
			}
			update();
		});
		return function onSave(_x3, _x4) {
			return _ref4.apply(this, arguments);
		};
	}();
	const onClickByTip = () => {
		var _posTabRef$current;
		(_posTabRef$current = posTabRef.current) === null || _posTabRef$current === void 0 || _posTabRef$current.setActive("setting");
	};
	const getPos = useCallback(_asyncToGenerator(function* () {
		if (typeof getPosComm === "function") {
			setPosLoading(true);
			const list = (yield getPosComm(type).catch(() => {
				setPosLoading(false);
			})).map((item) => {
				return _objectSpread2(_objectSpread2({}, item), {}, { __sourceName: item.name });
			});
			setPosLoading(false);
			const obj = getDefaultValue(list);
			setSystemConfigStatus(Object.values(obj).every(Boolean));
			setPosCommList(list);
		}
	}), [getPosComm, type]);
	/**
	* @title: 保存厂商设置
	* @param {any} pos 厂商信息
	* @return {*}
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:22
	*/
	const onSavePos = (pos) => {
		if (typeof savePos === "function") {
			setPosLoading(true);
			savePos(type, pos).then(() => {
				getPos();
			}).catch(() => {
				setPosLoading(false);
			});
		}
	};
	useEffect(() => {
		setPairStatus("");
		setPairMessage("");
	}, [page]);
	/**
	* @title: 回退列表页
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:23
	*/
	const onBack = () => {
		setPage("list");
	};
	const onChangeTabs = (key) => {
		setPage("list");
	};
	/**
	* @title: 设置厂商配置字段，type 变化时重新拉取
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:23
	*/
	useEffect(() => {
		if (type) getPos();
	}, [type]);
	/**
	* @title: 响应外界type变化将page重置为列表页
	* @Author: hongbing.wang
	* @Date: 2024-08-20 11:23
	*/
	useEffect(() => {
		setPage("list");
	}, [type]);
	/**
	* @title 保存配对信息
	* @description MX51设备配对的第一步不是直接保存，而是要先发起配对请求，等刷卡机上配对后，再保存
	*/
	const onSavePair = function() {
		var _ref5 = _asyncToGenerator(function* (device) {
			if ([Eftpos.MX51].includes(type) && (status === DeviceEnum.Add || status === DeviceEnum.Repair)) try {
				setLoading(true);
				const response = yield pairRequest.run(_objectSpread2(_objectSpread2({}, (device === null || device === void 0 ? void 0 : device.connection) || {}), {}, { type }));
				if ((response === null || response === void 0 ? void 0 : response.code) == 200) pairModalHook.open({
					data: {
						type,
						device,
						pairResponse: response === null || response === void 0 ? void 0 : response.data
					},
					onCancel: () => {
						pairModalHook.close();
					},
					onConfirm: () => {
						pairModalHook.close();
						onSave(device, response === null || response === void 0 ? void 0 : response.data);
					}
				});
			} catch (error) {
				console.error("onSavePair error =>", error);
				messageApi.open({
					type: "error",
					style: { zIndex: (zIndex || 9999) + 1 },
					content: (error === null || error === void 0 ? void 0 : error.message) || locales.getText("page.eftpos.text.pair.error")
				});
			} finally {
				setLoading(false);
			}
			else onSave(device);
		});
		return function onSavePair(_x5) {
			return _ref5.apply(this, arguments);
		};
	}();
	if (TYPES_WITH_MERCHANT_SETTINGS.has(type)) return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PosTabs, {
		ref: posTabRef,
		Table: /* @__PURE__ */ React.createElement(table_default, {
			ref: tableRef,
			eftposName: name,
			type,
			useTyroLog,
			tableSize,
			getList,
			onDel: onDelDevice,
			onRepair,
			onEdit: onEditDevice,
			onLog,
			key: `postable${type}`,
			systemConfigStatus,
			onClickByTip
		}),
		PosForm: /* @__PURE__ */ React.createElement(Spin, {
			tip: "Loading...",
			spinning: posLoading,
			wrapperClassName: "pisell-lowcode__pos_setting_box"
		}, /* @__PURE__ */ React.createElement(PosForm, {
			eftposName: name,
			onSave: onSavePos,
			formItemList: posItemList
		})),
		onChange: onChangeTabs
	}), /* @__PURE__ */ React.createElement(Drawer$2, {
		open: page === "edit",
		onClose: onBack,
		title: locales.getText("page.eftpos.text.device.add")(status, name),
		titleNoWrap: true,
		zIndex: zIndex || 9999,
		destroyOnClose: true,
		className: "pisell-lowcode__pos_drawer"
	}, /* @__PURE__ */ React.createElement(Spin, {
		tip: "Loading...",
		spinning: loading,
		wrapperClassName: "pisell-lowcode__pos_box"
	}, /* @__PURE__ */ React.createElement(Device, {
		formItemList: deviceItemList,
		onSave,
		key: `posdevice${type}`
	}, pairStatus ? /* @__PURE__ */ React.createElement(Form.Item, { label: "Status" }, /* @__PURE__ */ React.createElement(Input, {
		value: pairStatus,
		disabled: true
	})) : null, pairMessage ? /* @__PURE__ */ React.createElement(Form.Item, { label: "Message" }, /* @__PURE__ */ React.createElement(Input, {
		value: pairMessage,
		disabled: true
	})) : null))), /* @__PURE__ */ React.createElement(Drawer$2, {
		open: page === "log",
		onClose: onBack,
		title: locales.getText("page.eftpos.text.log"),
		titleNoWrap: true,
		zIndex: zIndex || 9999,
		destroyOnClose: true,
		className: "pisell-lowcode__pos_drawer pisell-lowcode__pos_drawer_log"
	}, /* @__PURE__ */ React.createElement(Log, {
		type,
		tyroUrl,
		tyroVersion,
		device: deviceItem
	})), contextHolder);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(table_default, {
		eftposName: name,
		ref: tableRef,
		type,
		useTyroLog,
		tableSize,
		getList,
		onDel: onDelDevice,
		onRepair,
		onLog,
		onEdit: onEditDevice,
		key: `table${type}`,
		systemConfigStatus,
		onClickByTip
	}), /* @__PURE__ */ React.createElement(Drawer$2, {
		open: page === "edit",
		onClose: onBack,
		title: type === Eftpos.MX51 ? /* @__PURE__ */ React.createElement("span", { style: {
			display: "inline-flex",
			alignItems: "center",
			gap: "4px"
		} }, /* @__PURE__ */ React.createElement(Image$1, {
			src: mx51SCISvg,
			preview: false,
			width: 24
		}), /* @__PURE__ */ React.createElement("span", null, "Simple Cloud Integration")) : locales.getText("page.eftpos.text.device.add")(status, name),
		titleNoWrap: true,
		zIndex: zIndex || 9999,
		destroyOnClose: true,
		className: "pisell-lowcode__pos_drawer"
	}, /* @__PURE__ */ React.createElement(Spin, {
		tip: "Loading...",
		spinning: loading,
		wrapperClassName: "pisell-lowcode__pos_box"
	}, /* @__PURE__ */ React.createElement(Device, {
		formItemList: deviceItemList,
		onSave: onSavePair,
		key: `device${type}`,
		type,
		status
	}, pairStatus ? /* @__PURE__ */ React.createElement(Form.Item, { label: "Status" }, /* @__PURE__ */ React.createElement(Input, {
		value: pairStatus,
		disabled: true
	})) : null, pairMessage ? /* @__PURE__ */ React.createElement(Form.Item, { label: "Message" }, /* @__PURE__ */ React.createElement(Input, {
		value: pairMessage,
		disabled: true
	})) : null))), /* @__PURE__ */ React.createElement(Drawer$2, {
		open: page === "log",
		onClose: onBack,
		title: locales.getText("page.eftpos.text.log"),
		titleNoWrap: true,
		zIndex: zIndex || 9999,
		destroyOnClose: true,
		className: "pisell-lowcode__pos_drawer pisell-lowcode__pos_drawer_log"
	}, /* @__PURE__ */ React.createElement(Log, {
		type,
		tyroUrl,
		tyroVersion,
		device: deviceItem
	})), contextHolder, pairModalHook.visible && /* @__PURE__ */ React.createElement(PairModal, pairModalHook.modalProps));
};
//#endregion
export { eftpos_default as default };
