const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_constants = require("../AuthMethods/constants.js");
const require_SettingList = require("../AuthMethods/SettingList.js");
const require_index = require("../AuthMethods/index.js");
const require_SettingsDrawer = require("../AuthMethods/SettingsDrawer.js");
const require_locales = require("./locales.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
require("./SaaSAdminAuth.less");
//#region src/components/authentication/admin/SaaSAdminAuth/index.tsx
const { Title, Paragraph } = antd.Typography;
const getSaaSAdminAuthMethods = () => {
	return require_constants.getDefaultAuthMethods().filter((m) => m.id === "email");
};
const convertApiDataToComponent = (apiData) => {
	const methodsArray = Object.entries(apiData.method).map(([key, value]) => ({
		key,
		sort: value.sort,
		enabled: value.enabled,
		setting: value.setting
	})).filter((m) => m.key === "email");
	methodsArray.sort((a, b) => a.sort - b.sort);
	const authMethods = [];
	const settingsMap = {};
	methodsArray.forEach(({ key, enabled, setting }) => {
		if (key === "email") {
			const loginMethodsArray = Object.entries(setting.login_method).map(([methodKey, methodValue]) => ({
				methodKey,
				enabled: methodValue.enabled,
				sort: methodValue.sort
			}));
			loginMethodsArray.sort((a, b) => a.sort - b.sort);
			const loginMethods = loginMethodsArray.map(({ methodKey, enabled }) => {
				const method = { password: {
					id: "password",
					title: _pisell_utils.locales.getText("auth.login.method.password.title") || "Password",
					description: _pisell_utils.locales.getText("auth.login.method.password.email.description") || "Log in using email and password"
				} }[methodKey];
				return {
					id: method.id,
					title: method.title,
					description: method.description,
					enabled
				};
			});
			const emailMethod = getSaaSAdminAuthMethods().find((m) => m.id === "email");
			authMethods.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, emailMethod), {}, { enabled }));
			settingsMap["email"] = {
				enableRegistration: setting.register_enabled,
				verificationType: setting.register_method,
				loginMethods
			};
		} else if (key === "phone") {
			const loginMethodsArray = Object.entries(setting.login_method).map(([methodKey, methodValue]) => ({
				methodKey,
				enabled: methodValue.enabled,
				sort: methodValue.sort
			}));
			loginMethodsArray.sort((a, b) => a.sort - b.sort);
			const loginMethods = loginMethodsArray.map(({ methodKey, enabled }) => {
				const method = {
					password: {
						id: "password",
						title: _pisell_utils.locales.getText("auth.login.method.password.title") || "Password",
						description: _pisell_utils.locales.getText("auth.login.method.password.phone.description") || "Log in using phone and password"
					},
					code: {
						id: "sms",
						title: _pisell_utils.locales.getText("auth.login.method.sms.title") || "SMS Code",
						description: _pisell_utils.locales.getText("auth.login.method.sms.description") || "Send a verification code via SMS"
					}
				}[methodKey];
				return {
					id: method.id,
					title: method.title,
					description: method.description,
					enabled
				};
			});
			const phoneMethod = getSaaSAdminAuthMethods().find((m) => m.id === "phone");
			authMethods.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, phoneMethod), {}, { enabled }));
			settingsMap["phone"] = {
				enableRegistration: setting.register_enabled,
				verificationType: "sms",
				loginMethods
			};
		} else {
			const oauthMethod = getSaaSAdminAuthMethods().find((m) => m.id === key);
			if (oauthMethod) authMethods.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, oauthMethod), {}, { enabled }));
		}
	});
	const passwordSettings = {
		minLength: apiData.password.min_length,
		requireUppercase: apiData.password.require_uppercase_letters,
		requireLowercase: apiData.password.require_lowercase_letters,
		requireNumbers: apiData.password.require_numbers,
		requireSpecialChars: apiData.password.require_special_characters
	};
	const finalAuthMethods = [...authMethods];
	getSaaSAdminAuthMethods().forEach((defaultMethod) => {
		if (!authMethods.some((m) => m.id === defaultMethod.id)) finalAuthMethods.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, defaultMethod), {}, { enabled: false }));
	});
	return {
		authMethods: finalAuthMethods,
		settingsMap,
		passwordSettings
	};
};
const convertComponentDataToApi = (authMethods, settingsMap, passwordSettings) => {
	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 === "email") {
			const emailSettings = settingsMap["email"];
			console.log("email settings:", emailSettings);
			if (emailSettings) {
				const loginMethod = {};
				emailSettings.loginMethods.forEach((loginMethodItem, loginIndex) => {
					const apiKey = {
						"password": "password",
						"magic-link": "link",
						"verification-code": "code"
					}[loginMethodItem.id];
					loginMethod[apiKey] = {
						enabled: loginMethodItem.enabled,
						sort: loginIndex + 1
					};
				});
				method["email"] = {
					sort: index + 1,
					enabled: authMethod.enabled,
					setting: {
						register_enabled: emailSettings.enableRegistration,
						register_method: emailSettings.verificationType,
						login_method: loginMethod
					}
				};
				console.log("添加了 email 到 method");
			} else console.log("email settings 不存在，跳过");
		} else if (authMethod.id === "phone") {
			const phoneSettings = settingsMap["phone"];
			console.log("phone settings:", phoneSettings);
			if (phoneSettings) {
				const loginMethod = {};
				phoneSettings.loginMethods.forEach((loginMethodItem, loginIndex) => {
					const apiKey = {
						"password": "password",
						"sms": "code"
					}[loginMethodItem.id];
					loginMethod[apiKey] = {
						enabled: loginMethodItem.enabled,
						sort: loginIndex + 1
					};
				});
				method["phone"] = {
					sort: index + 1,
					enabled: authMethod.enabled,
					setting: {
						register_enabled: phoneSettings.enableRegistration,
						register_method: "code",
						login_method: loginMethod
					}
				};
				console.log("添加了 phone 到 method");
			} else console.log("phone settings 不存在，跳过");
		} else {
			console.log(`OAuth method: ${authMethod.id}`);
			method[authMethod.id] = {
				sort: index + 1,
				enabled: authMethod.enabled,
				setting: {
					register_enabled: false,
					register_method: "",
					login_method: {}
				}
			};
			console.log(`添加了 ${authMethod.id} 到 method`);
		}
	});
	console.log("最终的 method 对象:", method);
	return {
		method,
		password: {
			min_length: passwordSettings.minLength,
			require_uppercase_letters: passwordSettings.requireUppercase,
			require_lowercase_letters: passwordSettings.requireLowercase,
			require_numbers: passwordSettings.requireNumbers,
			require_special_characters: passwordSettings.requireSpecialChars
		}
	};
};
const SaaSAdminAuth = ({ className, style, onSave }) => {
	const context = require_useEngineContext.default();
	const app = context.appHelper.utils.getApp();
	const { request, data } = context.appHelper.utils.getApp();
	const dataKey = "auth.account";
	const [tenantId, setTenantId] = (0, react.useState)(null);
	const [loading, setLoading] = (0, react.useState)(true);
	const [authMethods, setAuthMethods] = (0, react.useState)([]);
	const [settingsMap, setSettingsMap] = (0, react.useState)({});
	const [passwordSettings, setPasswordSettings] = (0, react.useState)({
		minLength: 8,
		requireUppercase: false,
		requireLowercase: false,
		requireNumbers: false,
		requireSpecialChars: false
	});
	const [localesInitialized, setLocalesInitialized] = (0, react.useState)(false);
	(0, react.useEffect)(() => {
		var _context$engine;
		console.log("app_init_saas_admin_auth", app, context, data.storage);
		_pisell_utils.locales.init(require_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");
		setLocalesInitialized(true);
	}, []);
	(0, react.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]);
	(0, react.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_saas_admin_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, passwordSettings: convertedPasswordSettings } = convertApiDataToComponent((_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value);
					setAuthMethods(convertedAuthMethods);
					setSettingsMap(convertedSettingsMap);
					setPasswordSettings(convertedPasswordSettings);
					console.log("Converted data:", {
						convertedAuthMethods,
						convertedSettingsMap,
						convertedPasswordSettings
					});
				} else setAuthMethods(getSaaSAdminAuthMethods());
				setLoading(false);
			}).catch((error) => {
				console.error("Error fetching tenant data:", error);
				setAuthMethods(getSaaSAdminAuthMethods());
				setLoading(false);
			});
		}
	}, [tenantId, request]);
	const [drawerOpen, setDrawerOpen] = (0, react.useState)(false);
	const [selectedMethod, setSelectedMethod] = (0, react.useState)(null);
	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 ? require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, m), {}, { enabled }) : m));
	};
	const handleAuthMethodSettings = (method) => {
		setSelectedMethod(method);
		setDrawerOpen(true);
	};
	const handlePasswordSettings = (method) => {
		setSelectedMethod(method);
		setDrawerOpen(true);
	};
	const handleConfigClick = (method) => {
		console.log("Config link clicked:", method.id);
	};
	const handleDrawerClose = () => {
		setDrawerOpen(false);
		setSelectedMethod(null);
	};
	const saveToApi = (currentAuthMethods, currentSettingsMap, currentPasswordSettings) => {
		console.log("=== 开始保存到接口 ===");
		console.log("authMethods:", currentAuthMethods);
		console.log("settingsMap:", currentSettingsMap);
		const completeSettingsMap = require_objectSpread2._objectSpread2({}, currentSettingsMap);
		currentAuthMethods.forEach((method) => {
			console.log(`检查 method: ${method.id}, 当前有设置: ${!!completeSettingsMap[method.id]}`);
			if (!completeSettingsMap[method.id]) {
				if (method.id === "email") {
					console.log("添加 email 默认设置");
					completeSettingsMap["email"] = {
						enableRegistration: true,
						verificationType: "link",
						loginMethods: [{
							id: "password",
							title: _pisell_utils.locales.getText("auth.login.method.password.title") || "Password",
							description: _pisell_utils.locales.getText("auth.login.method.password.email.description") || "Log in using email and password",
							enabled: true
						}]
					};
				} else if (method.id === "phone") {
					console.log("添加 phone 默认设置");
					completeSettingsMap["phone"] = {
						enableRegistration: true,
						verificationType: "sms",
						loginMethods: [{
							id: "password",
							title: _pisell_utils.locales.getText("auth.login.method.password.title") || "Password",
							description: _pisell_utils.locales.getText("auth.login.method.password.phone.description") || "Log in using phone and password",
							enabled: true
						}, {
							id: "sms",
							title: _pisell_utils.locales.getText("auth.login.method.sms.title") || "SMS Code",
							description: _pisell_utils.locales.getText("auth.login.method.sms.description") || "Send a verification code via SMS",
							enabled: true
						}]
					};
				}
			}
		});
		console.log("完整的 settingsMap:", completeSettingsMap);
		const apiData = convertComponentDataToApi(currentAuthMethods, completeSettingsMap, currentPasswordSettings);
		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_saas_admin_auth_save", res);
			antd.message.success(_pisell_utils.locales.getText("auth.save.success") || "保存成功");
		}).catch((error) => {
			console.error("Error saving tenant data:", error);
			antd.message.error(_pisell_utils.locales.getText("auth.save.error") || "保存失败");
		});
	};
	const handleSettingsSave = (settings) => {
		console.log("Settings saved:", settings);
		let updatedSettingsMap = require_objectSpread2._objectSpread2({}, settingsMap);
		let updatedPasswordSettings = require_objectSpread2._objectSpread2({}, passwordSettings);
		if (selectedMethod) {
			if (selectedMethod.id === "email") {
				updatedSettingsMap = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, updatedSettingsMap), {}, { email: settings });
				setSettingsMap(updatedSettingsMap);
			} else if (selectedMethod.id === "phone") {
				updatedSettingsMap = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, updatedSettingsMap), {}, { phone: settings });
				setSettingsMap(updatedSettingsMap);
			} else if (selectedMethod.id === "admin_password_rules") {
				updatedPasswordSettings = settings;
				setPasswordSettings(updatedPasswordSettings);
			}
		}
		saveToApi(authMethods, updatedSettingsMap, updatedPasswordSettings);
	};
	const handleSave = () => {
		saveToApi(authMethods, settingsMap, passwordSettings);
	};
	if (loading) return /* @__PURE__ */ react.default.createElement("div", {
		className: `saas-admin-auth ${className || ""}`,
		style: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, style), {}, {
			display: "flex",
			justifyContent: "center",
			alignItems: "center",
			minHeight: "400px"
		})
	}, /* @__PURE__ */ react.default.createElement(antd.Spin, { size: "large" }));
	return /* @__PURE__ */ react.default.createElement("div", {
		className: `saas-admin-auth ${className || ""}`,
		style
	}, /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-header" }, /* @__PURE__ */ react.default.createElement(Title, {
		level: 1,
		className: "saas-admin-auth-title"
	}, _pisell_utils.locales.getText("saas.admin.auth.title")), /* @__PURE__ */ react.default.createElement(Paragraph, { className: "saas-admin-auth-description" }, _pisell_utils.locales.getText("saas.admin.auth.description"))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section" }, /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section-layout" }, /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section-header" }, /* @__PURE__ */ react.default.createElement(Title, {
		level: 2,
		className: "saas-admin-auth-section-title"
	}, _pisell_utils.locales.getText("saas.admin.auth.methods.title")), /* @__PURE__ */ react.default.createElement(Paragraph, { className: "saas-admin-auth-section-description" }, _pisell_utils.locales.getText("saas.admin.auth.methods.description"))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section-content" }, /* @__PURE__ */ react.default.createElement(require_index.default, {
		methods: authMethods,
		onOrderChange: handleAuthMethodsOrderChange,
		onToggle: handleAuthMethodToggle,
		onSettings: handleAuthMethodSettings,
		onConfigClick: handleConfigClick
	})))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section" }, /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section-layout" }, /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section-header" }, /* @__PURE__ */ react.default.createElement(Title, {
		level: 2,
		className: "saas-admin-auth-section-title"
	}, _pisell_utils.locales.getText("saas.admin.password.settings.title")), /* @__PURE__ */ react.default.createElement(Paragraph, { className: "saas-admin-auth-section-description" }, _pisell_utils.locales.getText("saas.admin.password.settings.description"))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-section-content" }, /* @__PURE__ */ react.default.createElement(require_SettingList.default, {
		methods: require_constants.getPasswordRulesSetting("admin_password_rules"),
		onSettings: handlePasswordSettings
	})))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-admin-auth-footer" }, /* @__PURE__ */ react.default.createElement(antd.Button, {
		type: "primary",
		size: "large",
		onClick: handleSave
	}, _pisell_utils.locales.getText("auth.button.save"))), /* @__PURE__ */ react.default.createElement(require_SettingsDrawer.default, {
		open: drawerOpen,
		method: selectedMethod,
		onClose: handleDrawerClose,
		onSave: handleSettingsSave,
		mode: "auth-methods",
		initialSettings: selectedMethod ? selectedMethod.id === "admin_password_rules" ? passwordSettings : settingsMap[selectedMethod.id] : void 0
	}));
};
//#endregion
exports.default = SaaSAdminAuth;
