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 useEngineContext from "../../../../hooks/useEngineContext.js";
import { getDefaultAuthMethods, getPasswordRulesSetting } from "../AuthMethods/constants.js";
import SettingList from "../AuthMethods/SettingList.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 "./CustomerAuth.less";
//#region src/components/authentication/admin/CustomerAuth/index.tsx
const { Title, Paragraph } = Typography;
const getCustomerAuthMethods = () => getDefaultAuthMethods();
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();
	methodsArray.forEach(({ key, enabled, setting }) => {
		processedKeys.add(key);
		if (key === "email" && setting) {
			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: locales.getText("auth.login.method.password.title") || "Password",
					description: 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 = getCustomerAuthMethods().find((m) => m.id === "email");
			authMethods.push(_objectSpread2(_objectSpread2({}, emailMethod), {}, { enabled }));
			settingsMap["email"] = {
				enableRegistration: (setting === null || setting === void 0 ? void 0 : setting.register_enabled) || false,
				verificationType: (setting === null || setting === void 0 ? void 0 : setting.register_method) || "link",
				loginMethods
			};
		} else if (key === "phone" && setting) {
			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: locales.getText("auth.login.method.password.title") || "Password",
						description: locales.getText("auth.login.method.password.phone.description") || "Log in using phone and password"
					},
					code: {
						id: "sms",
						title: locales.getText("auth.login.method.sms.title") || "SMS Code",
						description: 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 = getCustomerAuthMethods().find((m) => m.id === "phone");
			authMethods.push(_objectSpread2(_objectSpread2({}, phoneMethod), {}, { enabled }));
			settingsMap["phone"] = {
				enableRegistration: (setting === null || setting === void 0 ? void 0 : setting.register_enabled) || false,
				verificationType: "sms",
				loginMethods
			};
		} else {
			const method = getCustomerAuthMethods().find((m) => m.id === key);
			if (method) authMethods.push(_objectSpread2(_objectSpread2({}, method), {}, { enabled }));
		}
	});
	getCustomerAuthMethods().forEach((defaultMethod) => {
		if (!processedKeys.has(defaultMethod.id)) authMethods.push(_objectSpread2(_objectSpread2({}, defaultMethod), {}, { enabled: false }));
	});
	return {
		authMethods,
		settingsMap,
		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 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 method[authMethod.id] = {
			sort: index + 1,
			enabled: authMethod.enabled
		};
	});
	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 CustomerAuth = ({ className, style, onSave }) => {
	const context = useEngineContext();
	const app = context.appHelper.utils.getApp();
	const { request, data, history } = context.appHelper.utils.getApp();
	const dataKey = "auth.customer";
	const [tenantId, setTenantId] = useState(null);
	const [loading, setLoading] = useState(true);
	const [authMethods, setAuthMethods] = useState([]);
	const [settingsMap, setSettingsMap] = useState({});
	const [passwordSettings, setPasswordSettings] = useState({
		minLength: 8,
		requireUppercase: false,
		requireLowercase: false,
		requireNumbers: false,
		requireSpecialChars: false
	});
	const [localesInitialized, setLocalesInitialized] = useState(false);
	useEffect(() => {
		var _context$engine;
		console.log("app_init_customer_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");
		setLocalesInitialized(true);
	}, []);
	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]);
	const checkOAuthConfigStatus = function() {
		var _ref = _asyncToGenerator(function* (providerId) {
			if (!tenantId) return false;
			const dataKey = `auth.oauth.${providerId}`;
			try {
				var _res$data, _res$data$;
				const res = yield request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`);
				if ((res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.length) > 0 && ((_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value)) {
					const configData = res.data[0].value;
					if (typeof configData === "object" && configData !== null) return Object.values(configData).some((val) => val !== null && val !== void 0 && val !== "");
					return !!configData;
				}
				return false;
			} catch (error) {
				console.error(`Error checking ${providerId} OAuth config:`, error);
				return false;
			}
		});
		return function checkOAuthConfigStatus(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	useEffect(() => {
		if (tenantId) {
			setLoading(true);
			request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`).then(function() {
				var _ref3 = _asyncToGenerator(function* (res) {
					var _res$data2;
					console.log("res_customer_auth_methods", res);
					if (res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length) {
						var _res$data$2;
						const { authMethods: convertedAuthMethods, settingsMap: convertedSettingsMap, passwordSettings: convertedPasswordSettings } = convertApiDataToComponent((_res$data$2 = res.data[0]) === null || _res$data$2 === void 0 ? void 0 : _res$data$2.value);
						const updatedAuthMethods = yield Promise.all(convertedAuthMethods.map(function() {
							var _ref2 = _asyncToGenerator(function* (method) {
								if (method.requiresOAuthConfig) {
									const isConfigured = yield checkOAuthConfigStatus(method.id);
									return _objectSpread2(_objectSpread2({}, method), {}, { enabled: isConfigured ? method.enabled : false });
								}
								return method;
							});
							return function(_x2) {
								return _ref2.apply(this, arguments);
							};
						}()));
						setAuthMethods(updatedAuthMethods);
						setSettingsMap(convertedSettingsMap);
						setPasswordSettings(convertedPasswordSettings);
						console.log("Converted data:", {
							authMethods: updatedAuthMethods,
							convertedSettingsMap,
							convertedPasswordSettings
						});
					} else setAuthMethods(getCustomerAuthMethods());
					setLoading(false);
				});
				return function(_x3) {
					return _ref3.apply(this, arguments);
				};
			}()).catch((error) => {
				console.error("Error fetching tenant data:", error);
				setAuthMethods(getCustomerAuthMethods());
				setLoading(false);
			});
		}
	}, [tenantId, request]);
	const [drawerOpen, setDrawerOpen] = useState(false);
	const [selectedMethod, setSelectedMethod] = 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 ? _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);
		history.push("/system-settings/auth/oauth-config");
	};
	const handleDrawerClose = () => {
		setDrawerOpen(false);
		setSelectedMethod(null);
	};
	const saveToApi = (currentAuthMethods, currentSettingsMap, currentPasswordSettings) => {
		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 === "email") {
					console.log("添加 email 默认设置");
					completeSettingsMap["email"] = {
						enableRegistration: true,
						verificationType: "link",
						loginMethods: [{
							id: "password",
							title: locales.getText("auth.login.method.password.title") || "Password",
							description: 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: locales.getText("auth.login.method.password.title") || "Password",
							description: locales.getText("auth.login.method.password.phone.description") || "Log in using phone and password",
							enabled: true
						}, {
							id: "sms",
							title: locales.getText("auth.login.method.sms.title") || "SMS Code",
							description: 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_customer_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);
		let updatedPasswordSettings = _objectSpread2({}, passwordSettings);
		if (selectedMethod) {
			if (selectedMethod.id === "email") {
				updatedSettingsMap = _objectSpread2(_objectSpread2({}, updatedSettingsMap), {}, { email: settings });
				setSettingsMap(updatedSettingsMap);
			} else if (selectedMethod.id === "phone") {
				updatedSettingsMap = _objectSpread2(_objectSpread2({}, updatedSettingsMap), {}, { phone: settings });
				setSettingsMap(updatedSettingsMap);
			} else if (selectedMethod.id === "customer_password_rules") {
				updatedPasswordSettings = settings;
				setPasswordSettings(updatedPasswordSettings);
			}
		}
		saveToApi(authMethods, updatedSettingsMap, updatedPasswordSettings);
	};
	const handleSave = () => {
		saveToApi(authMethods, settingsMap, passwordSettings);
	};
	if (loading) return /* @__PURE__ */ React.createElement("div", {
		className: `customer-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: `customer-auth ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "customer-auth-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 1,
		className: "customer-auth-title"
	}, locales.getText("customer.auth.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "customer-auth-description" }, locales.getText("customer.auth.description"))), /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section" }, /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section-layout" }, /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "customer-auth-section-title"
	}, locales.getText("customer.auth.methods.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "customer-auth-section-description" }, locales.getText("customer.auth.methods.description"))), /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section-content" }, /* @__PURE__ */ React.createElement(AuthMethods, {
		methods: authMethods,
		onOrderChange: handleAuthMethodsOrderChange,
		onToggle: handleAuthMethodToggle,
		onSettings: handleAuthMethodSettings,
		onConfigClick: handleConfigClick
	})))), /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section" }, /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section-layout" }, /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "customer-auth-section-title"
	}, locales.getText("customer.password.settings.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "customer-auth-section-description" }, locales.getText("customer.password.settings.description"))), /* @__PURE__ */ React.createElement("div", { className: "customer-auth-section-content" }, /* @__PURE__ */ React.createElement(SettingList, {
		methods: getPasswordRulesSetting("customer_password_rules"),
		onSettings: handlePasswordSettings
	})))), /* @__PURE__ */ React.createElement("div", { className: "customer-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 ? selectedMethod.id === "customer_password_rules" ? passwordSettings : settingsMap[selectedMethod.id] : void 0
	}));
};
//#endregion
export { CustomerAuth as default };
