import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { AuthMethodCategory, AuthMethodType } from "../AuthMethods/types.js";
import AuthMethods from "../AuthMethods/index.js";
import SettingsDrawer from "../AuthMethods/SettingsDrawer.js";
import locales_default from "./locales.js";
import React, { useEffect, useState } from "react";
import { Button, Spin, Typography, message } from "antd";
import { locales } from "@pisell/utils";
import { NumberOutlined } from "@ant-design/icons";
import "./POSOperatorAuth.less";
//#region src/components/authentication/admin/POSOperatorAuth/index.tsx
const { Title, Paragraph } = Typography;
/**
* 获取POS操作员认证方法列表（支持多语言）
* 每次调用都会根据当前语言设置返回对应的文本
* @returns 认证方法数组
*/
const getPOSOperatorAuthMethods = () => [{
	id: "digit_id_pin",
	type: AuthMethodType.DIGIT_ID_PIN,
	title: locales.getText("auth.method.digit_id_pin.title") || "Digit ID + PIN",
	category: AuthMethodCategory.GENERAL,
	description: locales.getText("auth.method.digit_id_pin.description") || "Quick login with employee ID and PIN code",
	icon: /* @__PURE__ */ React.createElement(NumberOutlined, { style: {
		fontSize: 20,
		color: "#4096ff"
	} }),
	enabled: true,
	hasSettings: true,
	disableToggle: true
}];
getPOSOperatorAuthMethods();
const convertApiDataToComponent = (apiData) => {
	const methodsArray = Object.entries(apiData.method).map(([key, value]) => ({
		key,
		sort: value.sort,
		enabled: value.enabled,
		setting: value.setting
	}));
	methodsArray.sort((a, b) => a.sort - b.sort);
	const authMethods = [];
	const settingsMap = {};
	const processedKeys = /* @__PURE__ */ new Set();
	const currentAuthMethods = getPOSOperatorAuthMethods();
	methodsArray.forEach(({ key, enabled, setting }) => {
		processedKeys.add(key);
		if (key === "digit_id_pin") {
			const digitIdPinMethod = currentAuthMethods.find((m) => m.id === "digit_id_pin");
			authMethods.push(_objectSpread2(_objectSpread2({}, digitIdPinMethod), {}, { enabled }));
			settingsMap["digit_id_pin"] = setting;
		}
	});
	currentAuthMethods.forEach((defaultMethod) => {
		if (!processedKeys.has(defaultMethod.id)) authMethods.push(_objectSpread2(_objectSpread2({}, defaultMethod), {}, { enabled: false }));
	});
	return {
		authMethods,
		settingsMap
	};
};
const convertComponentDataToApi = (authMethods, settingsMap) => {
	console.log("convertComponentDataToApi 被调用");
	console.log("authMethods:", authMethods);
	console.log("settingsMap:", settingsMap);
	const method = {};
	authMethods.forEach((authMethod, index) => {
		console.log(`处理 authMethod: ${authMethod.id}, index: ${index}`);
		if (authMethod.id === "digit_id_pin") {
			const digitIdPinSettings = settingsMap["digit_id_pin"] || {};
			console.log("digit_id_pin settings:", digitIdPinSettings);
			method["digit_id_pin"] = {
				sort: index + 1,
				enabled: authMethod.enabled,
				setting: digitIdPinSettings
			};
			console.log("添加了 digit_id_pin 到 method");
		}
	});
	console.log("最终的 method 对象:", method);
	return { method };
};
const POSOperatorAuth = ({ className, style, onSave }) => {
	const context = useEngineContext();
	const app = context.appHelper.utils.getApp();
	const { request, data } = context.appHelper.utils.getApp();
	const dataKey = "auth.pos_operator";
	const [tenantId, setTenantId] = useState(null);
	const [loading, setLoading] = useState(true);
	const [authMethods, setAuthMethods] = useState([]);
	const [settingsMap, setSettingsMap] = useState({});
	const [drawerOpen, setDrawerOpen] = useState(false);
	const [selectedMethod, setSelectedMethod] = useState(null);
	useEffect(() => {
		var _context$engine;
		console.log("app_init_pos_operator_auth", app, context, data.storage);
		locales.init(locales_default, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en");
		setAuthMethods(getPOSOperatorAuthMethods());
	}, []);
	useEffect(() => {
		const coreData = data.storage.getStorage("core");
		if (coreData) try {
			var _coreDataJson$tenant;
			const coreDataJson = JSON.parse(coreData);
			if (coreDataJson === null || coreDataJson === void 0 || (_coreDataJson$tenant = coreDataJson.tenant) === null || _coreDataJson$tenant === void 0 ? void 0 : _coreDataJson$tenant.id) setTenantId(coreDataJson.tenant.id);
		} catch (error) {
			console.error("Error parsing core data:", error);
		}
	}, [data.storage]);
	useEffect(() => {
		if (tenantId) {
			setLoading(true);
			request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`).then((res) => {
				var _res$data;
				console.log("res_pos_operator_auth_methods", res);
				if (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.length) {
					var _res$data$;
					const { authMethods: convertedAuthMethods, settingsMap: convertedSettingsMap } = convertApiDataToComponent((_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value);
					setAuthMethods(convertedAuthMethods);
					setSettingsMap(convertedSettingsMap);
					console.log("Converted data:", {
						convertedAuthMethods,
						convertedSettingsMap
					});
				} else setAuthMethods(getPOSOperatorAuthMethods());
				setLoading(false);
			}).catch((error) => {
				console.error("Error fetching tenant data:", error);
				setAuthMethods(getPOSOperatorAuthMethods());
				setLoading(false);
			});
		}
	}, [tenantId, request]);
	const handleAuthMethodsOrderChange = (methods) => {
		setAuthMethods(methods);
	};
	const handleAuthMethodToggle = (method, enabled) => {
		console.log("Auth method toggled:", method.id, enabled);
		setAuthMethods((prevMethods) => prevMethods.map((m) => m.id === method.id ? _objectSpread2(_objectSpread2({}, m), {}, { enabled }) : m));
	};
	const handleAuthMethodSettings = (method) => {
		setSelectedMethod(method);
		setDrawerOpen(true);
	};
	const handleDrawerClose = () => {
		setDrawerOpen(false);
		setSelectedMethod(null);
	};
	const saveToApi = (currentAuthMethods, currentSettingsMap) => {
		console.log("=== 开始保存到接口 ===");
		console.log("authMethods:", currentAuthMethods);
		console.log("settingsMap:", currentSettingsMap);
		const completeSettingsMap = _objectSpread2({}, currentSettingsMap);
		currentAuthMethods.forEach((method) => {
			console.log(`检查 method: ${method.id}, 当前有设置: ${!!completeSettingsMap[method.id]}`);
			if (!completeSettingsMap[method.id]) {
				if (method.id === "digit_id_pin") {
					console.log("添加 digit_id_pin 默认设置");
					completeSettingsMap["digit_id_pin"] = {
						digit_length: 4,
						pin_length: 4
					};
				}
			}
		});
		console.log("完整的 settingsMap:", completeSettingsMap);
		const apiData = convertComponentDataToApi(currentAuthMethods, completeSettingsMap);
		console.log("=== 保存的接口数据 ===");
		console.log(JSON.stringify(apiData, null, 2));
		onSave === null || onSave === void 0 || onSave(currentAuthMethods);
		request.post(`/tenant/core/meta/tenant/${tenantId}`, { [dataKey]: apiData }).then((res) => {
			console.log("res_pos_operator_auth_save", res);
			message.success(locales.getText("auth.save.success") || "保存成功");
		}).catch((error) => {
			console.error("Error saving tenant data:", error);
			message.error(locales.getText("auth.save.error") || "保存失败");
		});
	};
	const handleSettingsSave = (settings) => {
		console.log("Settings saved:", settings);
		let updatedSettingsMap = _objectSpread2({}, settingsMap);
		if (selectedMethod) {
			if (selectedMethod.id === "digit_id_pin") {
				updatedSettingsMap = _objectSpread2(_objectSpread2({}, updatedSettingsMap), {}, { digit_id_pin: settings });
				setSettingsMap(updatedSettingsMap);
			}
		}
		saveToApi(authMethods, updatedSettingsMap);
	};
	const handleSave = () => {
		saveToApi(authMethods, settingsMap);
	};
	if (loading) return /* @__PURE__ */ React.createElement("div", {
		className: `pos-operator-auth ${className || ""}`,
		style: _objectSpread2(_objectSpread2({}, style), {}, {
			display: "flex",
			justifyContent: "center",
			alignItems: "center",
			minHeight: "400px"
		})
	}, /* @__PURE__ */ React.createElement(Spin, { size: "large" }));
	return /* @__PURE__ */ React.createElement("div", {
		className: `pos-operator-auth ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "pos-operator-auth-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 1,
		className: "pos-operator-auth-title"
	}, locales.getText("pos.operator.auth.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "pos-operator-auth-description" }, locales.getText("pos.operator.auth.description"))), /* @__PURE__ */ React.createElement("div", { className: "pos-operator-auth-section" }, /* @__PURE__ */ React.createElement("div", { className: "pos-operator-auth-section-layout" }, /* @__PURE__ */ React.createElement("div", { className: "pos-operator-auth-section-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "pos-operator-auth-section-title"
	}, locales.getText("pos.operator.auth.methods.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "pos-operator-auth-section-description" }, locales.getText("pos.operator.auth.methods.description"))), /* @__PURE__ */ React.createElement("div", { className: "pos-operator-auth-section-content" }, /* @__PURE__ */ React.createElement(AuthMethods, {
		methods: authMethods,
		onOrderChange: handleAuthMethodsOrderChange,
		onToggle: handleAuthMethodToggle,
		onSettings: handleAuthMethodSettings
	})))), /* @__PURE__ */ React.createElement("div", { className: "pos-operator-auth-footer" }, /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		size: "large",
		onClick: handleSave
	}, locales.getText("auth.button.save"))), /* @__PURE__ */ React.createElement(SettingsDrawer, {
		open: drawerOpen,
		method: selectedMethod,
		onClose: handleDrawerClose,
		onSave: handleSettingsSave,
		mode: "auth-methods",
		initialSettings: selectedMethod ? settingsMap[selectedMethod.id] : void 0
	}));
};
//#endregion
export { POSOperatorAuth as default };
