var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/authentication/admin/SaaSAdminAuth/index.tsx
var SaaSAdminAuth_exports = {};
__export(SaaSAdminAuth_exports, {
  default: () => SaaSAdminAuth_default
});
module.exports = __toCommonJS(SaaSAdminAuth_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_AuthMethods = __toESM(require("../AuthMethods"));
var import_AuthMethods2 = require("../AuthMethods");
var import_SettingsDrawer = __toESM(require("../AuthMethods/SettingsDrawer"));
var import_constants = require("../AuthMethods/constants");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_locales = __toESM(require("./locales"));
var import_SaaSAdminAuth = require("./SaaSAdminAuth.less");
var { Title, Paragraph } = import_antd.Typography;
var getSaaSAdminAuthMethods = () => {
  const methods = (0, import_constants.getDefaultAuthMethods)();
  return methods.filter((m) => m.id === "email");
};
var 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: enabled2 }) => {
        const methodMap = {
          password: {
            id: "password",
            title: import_utils.locales.getText("auth.login.method.password.title") || "Password",
            description: import_utils.locales.getText("auth.login.method.password.email.description") || "Log in using email and password"
          }
          // link: {
          //     id: 'magic-link',
          //     title: locales.getText('auth.login.method.magic-link.title') || 'Magic Link',
          //     description: locales.getText('auth.login.method.magic-link.description') || 'Send a magic link to email',
          // },
          // code: {
          //     id: 'verification-code',
          //     title: locales.getText('auth.login.method.verification-code.title') || 'Verification Code',
          //     description: locales.getText('auth.login.method.verification-code.description') || 'Send a verification code to email',
          // },
        };
        const method = methodMap[methodKey];
        return {
          id: method.id,
          title: method.title,
          description: method.description,
          enabled: enabled2
        };
      });
      const emailMethod = getSaaSAdminAuthMethods().find((m) => m.id === "email");
      authMethods.push({
        ...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: enabled2 }) => {
        const methodMap = {
          password: {
            id: "password",
            title: import_utils.locales.getText("auth.login.method.password.title") || "Password",
            description: import_utils.locales.getText("auth.login.method.password.phone.description") || "Log in using phone and password"
          },
          code: {
            id: "sms",
            title: import_utils.locales.getText("auth.login.method.sms.title") || "SMS Code",
            description: import_utils.locales.getText("auth.login.method.sms.description") || "Send a verification code via SMS"
          }
        };
        const method = methodMap[methodKey];
        return {
          id: method.id,
          title: method.title,
          description: method.description,
          enabled: enabled2
        };
      });
      const phoneMethod = getSaaSAdminAuthMethods().find((m) => m.id === "phone");
      authMethods.push({
        ...phoneMethod,
        enabled
      });
      settingsMap["phone"] = {
        enableRegistration: setting.register_enabled,
        verificationType: "sms",
        loginMethods
      };
    } else {
      const oauthMethod = getSaaSAdminAuthMethods().find((m) => m.id === key);
      if (oauthMethod) {
        authMethods.push({
          ...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) => {
    const exists = authMethods.some((m) => m.id === defaultMethod.id);
    if (!exists) {
      finalAuthMethods.push({
        ...defaultMethod,
        enabled: false
      });
    }
  });
  return { authMethods: finalAuthMethods, settingsMap, passwordSettings };
};
var 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 methodKeyMap = {
            "password": "password",
            "magic-link": "link",
            "verification-code": "code"
          };
          const apiKey = methodKeyMap[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 methodKeyMap = {
            "password": "password",
            "sms": "code"
          };
          const apiKey = methodKeyMap[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
    }
  };
};
var SaaSAdminAuth = ({ className, style, onSave }) => {
  const context = (0, import_useEngineContext.default)();
  const app = context.appHelper.utils.getApp();
  const { request, data } = context.appHelper.utils.getApp();
  const dataKey = "auth.account";
  const [tenantId, setTenantId] = (0, import_react.useState)(null);
  const [loading, setLoading] = (0, import_react.useState)(true);
  const [authMethods, setAuthMethods] = (0, import_react.useState)([]);
  const [settingsMap, setSettingsMap] = (0, import_react.useState)({});
  const [passwordSettings, setPasswordSettings] = (0, import_react.useState)({
    minLength: 8,
    requireUppercase: false,
    requireLowercase: false,
    requireNumbers: false,
    requireSpecialChars: false
  });
  const [localesInitialized, setLocalesInitialized] = (0, import_react.useState)(false);
  (0, import_react.useEffect)(() => {
    var _a, _b;
    console.log("app_init_saas_admin_auth", app, context, data.storage);
    import_utils.locales.init(import_locales.default, ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en");
    setLocalesInitialized(true);
  }, []);
  (0, import_react.useEffect)(() => {
    var _a;
    const coreData = data.storage.getStorage("core");
    if (coreData) {
      try {
        const coreDataJson = JSON.parse(coreData);
        if ((_a = coreDataJson == null ? void 0 : coreDataJson.tenant) == null ? void 0 : _a.id) {
          setTenantId(coreDataJson.tenant.id);
        }
      } catch (error) {
        console.error("Error parsing core data:", error);
      }
    }
  }, [data.storage]);
  (0, import_react.useEffect)(() => {
    if (tenantId) {
      setLoading(true);
      request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`).then((res) => {
        var _a, _b;
        console.log("res_saas_admin_auth_methods", res);
        if ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.length) {
          const data2 = (_b = res.data[0]) == null ? void 0 : _b.value;
          const { authMethods: convertedAuthMethods, settingsMap: convertedSettingsMap, passwordSettings: convertedPasswordSettings } = convertApiDataToComponent(data2);
          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, import_react.useState)(false);
  const [selectedMethod, setSelectedMethod] = (0, import_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 ? { ...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 = { ...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: import_utils.locales.getText("auth.login.method.password.title") || "Password",
                description: import_utils.locales.getText("auth.login.method.password.email.description") || "Log in using email and password",
                enabled: true
              }
              // { 
              //     id: 'magic-link', 
              //     title: locales.getText('auth.login.method.magic-link.title') || 'Magic Link', 
              //     description: locales.getText('auth.login.method.magic-link.description') || 'Send a magic link to email', 
              //     enabled: true 
              // },
              // { 
              //     id: 'verification-code', 
              //     title: locales.getText('auth.login.method.verification-code.title') || 'Verification Code', 
              //     description: locales.getText('auth.login.method.verification-code.description') || 'Send a verification code to email', 
              //     enabled: false 
              // },
            ]
          };
        } else if (method.id === "phone") {
          console.log("添加 phone 默认设置");
          completeSettingsMap["phone"] = {
            enableRegistration: true,
            verificationType: "sms",
            loginMethods: [
              {
                id: "password",
                title: import_utils.locales.getText("auth.login.method.password.title") || "Password",
                description: import_utils.locales.getText("auth.login.method.password.phone.description") || "Log in using phone and password",
                enabled: true
              },
              {
                id: "sms",
                title: import_utils.locales.getText("auth.login.method.sms.title") || "SMS Code",
                description: import_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 ? void 0 : onSave(currentAuthMethods, {});
    request.post(`/tenant/core/meta/tenant/${tenantId}`, {
      [dataKey]: apiData
    }).then((res) => {
      console.log("res_saas_admin_auth_save", res);
      import_antd.message.success(import_utils.locales.getText("auth.save.success") || "保存成功");
    }).catch((error) => {
      console.error("Error saving tenant data:", error);
      import_antd.message.error(import_utils.locales.getText("auth.save.error") || "保存失败");
    });
  };
  const handleSettingsSave = (settings) => {
    console.log("Settings saved:", settings);
    let updatedSettingsMap = { ...settingsMap };
    let updatedPasswordSettings = { ...passwordSettings };
    if (selectedMethod) {
      if (selectedMethod.id === "email") {
        updatedSettingsMap = {
          ...updatedSettingsMap,
          email: settings
        };
        setSettingsMap(updatedSettingsMap);
      } else if (selectedMethod.id === "phone") {
        updatedSettingsMap = {
          ...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__ */ import_react.default.createElement("div", { className: `saas-admin-auth ${className || ""}`, style: { ...style, display: "flex", justifyContent: "center", alignItems: "center", minHeight: "400px" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { size: "large" }));
  }
  return /* @__PURE__ */ import_react.default.createElement("div", { className: `saas-admin-auth ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 1, className: "saas-admin-auth-title" }, import_utils.locales.getText("saas.admin.auth.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "saas-admin-auth-description" }, import_utils.locales.getText("saas.admin.auth.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section-layout" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 2, className: "saas-admin-auth-section-title" }, import_utils.locales.getText("saas.admin.auth.methods.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "saas-admin-auth-section-description" }, import_utils.locales.getText("saas.admin.auth.methods.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section-content" }, /* @__PURE__ */ import_react.default.createElement(
    import_AuthMethods.default,
    {
      methods: authMethods,
      onOrderChange: handleAuthMethodsOrderChange,
      onToggle: handleAuthMethodToggle,
      onSettings: handleAuthMethodSettings,
      onConfigClick: handleConfigClick
    }
  )))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section-layout" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 2, className: "saas-admin-auth-section-title" }, import_utils.locales.getText("saas.admin.password.settings.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "saas-admin-auth-section-description" }, import_utils.locales.getText("saas.admin.password.settings.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-section-content" }, /* @__PURE__ */ import_react.default.createElement(
    import_AuthMethods2.SettingList,
    {
      methods: (0, import_constants.getPasswordRulesSetting)("admin_password_rules"),
      onSettings: handlePasswordSettings
    }
  )))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-admin-auth-footer" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", size: "large", onClick: handleSave }, import_utils.locales.getText("auth.button.save"))), /* @__PURE__ */ import_react.default.createElement(
    import_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
    }
  ));
};
var SaaSAdminAuth_default = SaaSAdminAuth;
