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 { TeamOutlined } from "@ant-design/icons";
import "./DeviceAuth.less";
//#region src/components/authentication/admin/DeviceAuth/index.tsx
const { Title, Paragraph } = Typography;
/**
* 获取设备认证方法列表（支持多语言）
* 每次调用都会根据当前语言设置返回对应的文本
* @returns 设备认证方法数组
*/
const getDeviceAuthMethods = () => [{
	id: "team_member",
	type: AuthMethodType.TEAM_MEMBER,
	title: locales.getText("device.auth.method.team-member.title") || "Team Member",
	category: AuthMethodCategory.GENERAL,
	description: locales.getText("device.auth.method.team-member.description") || "Use Team Member authentication methods",
	inheritMessage: locales.getText("device.auth.method.team-member.inherit") || "Inherits from Team Member authentication settings",
	icon: /* @__PURE__ */ React.createElement(TeamOutlined, { style: {
		fontSize: 20,
		color: "#4096ff"
	} }),
	enabled: true,
	hasSettings: false
}];
getDeviceAuthMethods();
const convertApiDataToComponent = (apiData, currentMethods) => {
	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();
	methodsArray.forEach(({ key, enabled, setting }) => {
		processedKeys.add(key);
		const defaultMethod = currentMethods.find((m) => m.id === key);
		if (defaultMethod) {
			authMethods.push(_objectSpread2(_objectSpread2({}, defaultMethod), {}, { enabled }));
			if (setting) settingsMap[key] = setting;
		}
	});
	currentMethods.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}`);
		const setting = settingsMap[authMethod.id];
		method[authMethod.id] = _objectSpread2({
			sort: index + 1,
			enabled: authMethod.enabled
		}, setting && { setting });
	});
	console.log("最终的 method 对象:", method);
	return { method };
};
const DeviceAuth = ({ className, style, onSave }) => {
	const context = useEngineContext();
	const app = context.appHelper.utils.getApp();
	const { request, data } = context.appHelper.utils.getApp();
	const dataKey = "auth.device";
	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_device_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(getDeviceAuthMethods());
	}, []);
	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_device_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, getDeviceAuthMethods());
					setAuthMethods(convertedAuthMethods);
					setSettingsMap(convertedSettingsMap);
					console.log("Converted data:", {
						convertedAuthMethods,
						convertedSettingsMap
					});
				} else setAuthMethods(getDeviceAuthMethods());
				setLoading(false);
			}).catch((error) => {
				console.error("Error fetching tenant data:", error);
				setAuthMethods(getDeviceAuthMethods());
				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 apiData = convertComponentDataToApi(currentAuthMethods, currentSettingsMap);
		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_device_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) {
			updatedSettingsMap = _objectSpread2(_objectSpread2({}, updatedSettingsMap), {}, { [selectedMethod.id]: settings });
			setSettingsMap(updatedSettingsMap);
		}
		saveToApi(authMethods, updatedSettingsMap);
	};
	const handleSave = () => {
		saveToApi(authMethods, settingsMap);
	};
	const handleCancel = () => {
		console.log("Settings cancelled");
	};
	if (loading) return /* @__PURE__ */ React.createElement("div", {
		className: `device-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: `device-auth ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "device-auth-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 1,
		className: "device-auth-title"
	}, locales.getText("device.auth.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "device-auth-description" }, locales.getText("device.auth.description"))), /* @__PURE__ */ React.createElement("div", { className: "device-auth-section" }, /* @__PURE__ */ React.createElement("div", { className: "device-auth-section-layout" }, /* @__PURE__ */ React.createElement("div", { className: "device-auth-section-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "device-auth-section-title"
	}, locales.getText("device.auth.methods.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "device-auth-section-description" }, locales.getText("device.auth.methods.description"))), /* @__PURE__ */ React.createElement("div", { className: "device-auth-section-content" }, /* @__PURE__ */ React.createElement(AuthMethods, {
		methods: authMethods,
		onOrderChange: handleAuthMethodsOrderChange,
		onToggle: handleAuthMethodToggle,
		onSettings: handleAuthMethodSettings
	})))), /* @__PURE__ */ React.createElement("div", { className: "device-auth-footer" }, /* @__PURE__ */ React.createElement(Button, {
		size: "large",
		onClick: handleCancel
	}, locales.getText("auth.button.cancel")), /* @__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 { DeviceAuth as default };
