function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useState, useEffect } from 'react';
import { Button, Typography, message, Spin } from 'antd';
import { locales } from '@pisell/utils';
import AuthMethods from "../AuthMethods";
import { SettingList } from "../AuthMethods";
import SettingsDrawer from "../AuthMethods/SettingsDrawer";
import { getDefaultAuthMethods, getPasswordRulesSetting } from "../AuthMethods/constants";
import useEngineContext from "../../../../hooks/useEngineContext";
// @ts-ignore
import localeTextsConfig from "./locales";
import "./OrgAdminAuth.less";
var Title = Typography.Title,
  Paragraph = Typography.Paragraph;

// 接口数据类型定义

// 为组织用户定义的认证方法（只包含Email和Phone）
var getOrgAdminAuthMethods = function getOrgAdminAuthMethods() {
  return getDefaultAuthMethods().filter(function (method) {
    return method.id === 'email';
  });
};

// 将接口数据转换为组件数据
var convertApiDataToComponent = function convertApiDataToComponent(apiData) {
  // 转换认证方法
  var methodsArray = Object.entries(apiData.method).map(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      key = _ref2[0],
      value = _ref2[1];
    return {
      key: key,
      sort: value.sort,
      enabled: value.enabled,
      setting: value.setting
    };
  });

  // 按 sort 排序
  methodsArray.sort(function (a, b) {
    return a.sort - b.sort;
  });

  // 创建认证方法数组
  var authMethods = [];
  var settingsMap = {};
  var processedKeys = new Set();
  methodsArray.forEach(function (_ref3) {
    var key = _ref3.key,
      enabled = _ref3.enabled,
      setting = _ref3.setting;
    processedKeys.add(key);
    if (key === 'email') {
      // 转换 Email 登录方法
      var loginMethodsArray = Object.entries(setting.login_method).map(function (_ref4) {
        var _ref5 = _slicedToArray(_ref4, 2),
          methodKey = _ref5[0],
          methodValue = _ref5[1];
        return {
          methodKey: methodKey,
          enabled: methodValue.enabled,
          sort: methodValue.sort
        };
      }).filter(function (m) {
        return m.methodKey === 'password';
      });
      loginMethodsArray.sort(function (a, b) {
        return a.sort - b.sort;
      });
      var loginMethods = loginMethodsArray.map(function (_ref6) {
        var methodKey = _ref6.methodKey,
          enabled = _ref6.enabled;
        var methodMap = {
          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'
          }
          // 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',
          // },
        };
        var method = methodMap[methodKey];
        return {
          id: method.id,
          title: method.title,
          description: method.description,
          enabled: enabled
        };
      });
      var emailMethod = getOrgAdminAuthMethods().find(function (m) {
        return m.id === 'email';
      });
      authMethods.push(_objectSpread(_objectSpread({}, emailMethod), {}, {
        enabled: enabled
      }));
      settingsMap['email'] = {
        enableRegistration: setting.register_enabled,
        verificationType: setting.register_method,
        loginMethods: loginMethods
      };
    }
  });

  // 添加所有在 ORG_ADMIN_AUTH_METHODS 中定义但 API 未返回的方法
  getOrgAdminAuthMethods().forEach(function (defaultMethod) {
    if (!processedKeys.has(defaultMethod.id)) {
      authMethods.push(_objectSpread(_objectSpread({}, defaultMethod), {}, {
        enabled: false // 默认未启用
      }));
    }
  });

  // 转换密码规则
  var 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
  };
  return {
    authMethods: authMethods,
    settingsMap: settingsMap,
    passwordSettings: passwordSettings
  };
};

// 将组件数据转换为接口数据
var convertComponentDataToApi = function convertComponentDataToApi(authMethods, settingsMap, passwordSettings) {
  console.log('convertComponentDataToApi 被调用');
  console.log('authMethods:', authMethods);
  console.log('settingsMap:', settingsMap);
  var method = {};
  authMethods.forEach(function (authMethod, index) {
    console.log("\u5904\u7406 authMethod: ".concat(authMethod.id, ", index: ").concat(index));
    if (authMethod.id === 'email') {
      var emailSettings = settingsMap['email'];
      console.log('email settings:', emailSettings);
      if (emailSettings) {
        var loginMethod = {};
        emailSettings.loginMethods.forEach(function (loginMethodItem, loginIndex) {
          var methodKeyMap = {
            'password': 'password',
            'magic-link': 'link',
            'verification-code': 'code'
          };
          var 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') {
      var phoneSettings = settingsMap['phone'];
      console.log('phone settings:', phoneSettings);
      if (phoneSettings) {
        var _loginMethod = {};
        phoneSettings.loginMethods.forEach(function (loginMethodItem, loginIndex) {
          var methodKeyMap = {
            'password': 'password',
            'sms': 'code'
          };
          var 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 不存在，跳过');
      }
    }
  });
  console.log('最终的 method 对象:', method);
  return {
    method: 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 OrgAdminAuth = function OrgAdminAuth(_ref7) {
  var className = _ref7.className,
    style = _ref7.style,
    onSave = _ref7.onSave;
  var context = useEngineContext();
  var app = context.appHelper.utils.getApp();
  var _context$appHelper$ut = context.appHelper.utils.getApp(),
    request = _context$appHelper$ut.request,
    data = _context$appHelper$ut.data;
  var dataKey = 'auth.organization.account';
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    tenantId = _useState2[0],
    setTenantId = _useState2[1];
  var _useState3 = useState(true),
    _useState4 = _slicedToArray(_useState3, 2),
    loading = _useState4[0],
    setLoading = _useState4[1];
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    authMethods = _useState6[0],
    setAuthMethods = _useState6[1];
  var _useState7 = useState({}),
    _useState8 = _slicedToArray(_useState7, 2),
    settingsMap = _useState8[0],
    setSettingsMap = _useState8[1];
  var _useState9 = useState({
      minLength: 8,
      requireUppercase: false,
      requireLowercase: false,
      requireNumbers: false,
      requireSpecialChars: false
    }),
    _useState10 = _slicedToArray(_useState9, 2),
    passwordSettings = _useState10[0],
    setPasswordSettings = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    localesInitialized = _useState12[0],
    setLocalesInitialized = _useState12[1];

  // 初始化 locales
  useEffect(function () {
    var _context$engine;
    console.log('app_init_org_admin_auth', app, context, data.storage);
    locales.init(localeTextsConfig, (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); // 标记 locales 已初始化，触发重新渲染
  }, []);

  // 解析 coreData 并设置 tenantId
  useEffect(function () {
    var coreData = data.storage.getStorage('core');
    if (coreData) {
      try {
        var _coreDataJson$tenant;
        var coreDataJson = JSON.parse(coreData);
        if (coreDataJson !== null && coreDataJson !== void 0 && (_coreDataJson$tenant = coreDataJson.tenant) !== null && _coreDataJson$tenant !== void 0 && _coreDataJson$tenant.id) {
          setTenantId(coreDataJson.tenant.id);
        }
      } catch (error) {
        console.error('Error parsing core data:', error);
      }
    }
  }, [data.storage]);

  // 当 tenantId 存在且变更时，发送请求获取数据
  useEffect(function () {
    if (tenantId) {
      setLoading(true);
      request.get("/tenant/core/meta?key=".concat(dataKey, "&metable_type=tenant&metable_id=").concat(tenantId)).then(function (res) {
        var _res$data;
        console.log('res_org_admin_auth_methods', res);
        if (res !== null && res !== void 0 && (_res$data = res.data) !== null && _res$data !== void 0 && _res$data.length) {
          var _res$data$;
          var _data = (_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value;
          var _convertApiDataToComp = convertApiDataToComponent(_data),
            convertedAuthMethods = _convertApiDataToComp.authMethods,
            convertedSettingsMap = _convertApiDataToComp.settingsMap,
            convertedPasswordSettings = _convertApiDataToComp.passwordSettings;
          setAuthMethods(convertedAuthMethods);
          setSettingsMap(convertedSettingsMap);
          setPasswordSettings(convertedPasswordSettings);
          console.log('Converted data:', {
            convertedAuthMethods: convertedAuthMethods,
            convertedSettingsMap: convertedSettingsMap,
            convertedPasswordSettings: convertedPasswordSettings
          });
        } else {
          // 如果没有数据，使用默认值
          setAuthMethods(getOrgAdminAuthMethods());
        }
        setLoading(false);
      }).catch(function (error) {
        console.error('Error fetching tenant data:', error);
        // 即使出错，也使用默认值
        setAuthMethods(getOrgAdminAuthMethods());
        setLoading(false);
      });
    }
  }, [tenantId, request]);
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    drawerOpen = _useState14[0],
    setDrawerOpen = _useState14[1];
  var _useState15 = useState(null),
    _useState16 = _slicedToArray(_useState15, 2),
    selectedMethod = _useState16[0],
    setSelectedMethod = _useState16[1];
  var handleAuthMethodsOrderChange = function handleAuthMethodsOrderChange(methods) {
    setAuthMethods(methods);
  };
  var handleAuthMethodToggle = function handleAuthMethodToggle(method, enabled) {
    console.log('Auth method toggled:', method.id, enabled);

    // 更新 authMethods 中对应方法的 enabled 状态
    setAuthMethods(function (prevMethods) {
      return prevMethods.map(function (m) {
        return m.id === method.id ? _objectSpread(_objectSpread({}, m), {}, {
          enabled: enabled
        }) : m;
      });
    });
  };
  var handleAuthMethodSettings = function handleAuthMethodSettings(method) {
    setSelectedMethod(method);
    setDrawerOpen(true);
  };
  var handlePasswordSettings = function handlePasswordSettings(method) {
    setSelectedMethod(method);
    setDrawerOpen(true);
  };
  var handleConfigClick = function handleConfigClick(method) {
    console.log('Config link clicked:', method.id);
    // 可以导航到OAuth配置页面
  };
  var handleDrawerClose = function handleDrawerClose() {
    setDrawerOpen(false);
    setSelectedMethod(null);
  };

  // 保存到接口的通用方法
  var saveToApi = function saveToApi(currentAuthMethods, currentSettingsMap, currentPasswordSettings) {
    console.log('=== 开始保存到接口 ===');
    console.log('authMethods:', currentAuthMethods);
    console.log('settingsMap:', currentSettingsMap);

    // 确保 settingsMap 包含所有认证方法的默认设置
    var completeSettingsMap = _objectSpread({}, currentSettingsMap);
    currentAuthMethods.forEach(function (method) {
      console.log("\u68C0\u67E5 method: ".concat(method.id, ", \u5F53\u524D\u6709\u8BBE\u7F6E: ").concat(!!completeSettingsMap[method.id]));
      if (!completeSettingsMap[method.id]) {
        if (method.id === 'email') {
          console.log('添加 email 默认设置');
          completeSettingsMap['email'] = {
            enableRegistration: true,
            verificationType: 'link',
            loginMethods: [{
              id: 'password',
              title: 'Password',
              description: 'Log in using email and password',
              enabled: true
            }, {
              id: 'magic-link',
              title: 'Magic Link',
              description: 'Send a magic link to email',
              enabled: true
            }, {
              id: 'verification-code',
              title: '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: 'Password',
              description: 'Log in using phone and password',
              enabled: true
            }, {
              id: 'sms',
              title: 'SMS Code',
              description: 'Send a verification code via SMS',
              enabled: true
            }]
          };
        }
      }
    });
    console.log('完整的 settingsMap:', completeSettingsMap);

    // 将组件数据转换为接口数据
    var 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/".concat(tenantId), _defineProperty({}, dataKey, apiData)).then(function (res) {
      console.log('res_org_admin_auth_save', res);
      message.success(locales.getText('auth.save.success') || '保存成功');
    }).catch(function (error) {
      console.error('Error saving tenant data:', error);
      message.error(locales.getText('auth.save.error') || '保存失败');
    });
  };
  var handleSettingsSave = function handleSettingsSave(settings) {
    console.log('Settings saved:', settings);

    // 根据当前选中的方法类型保存设置
    var updatedSettingsMap = _objectSpread({}, settingsMap);
    var updatedPasswordSettings = _objectSpread({}, passwordSettings);
    if (selectedMethod) {
      if (selectedMethod.id === 'email') {
        updatedSettingsMap = _objectSpread(_objectSpread({}, updatedSettingsMap), {}, {
          email: settings
        });
        setSettingsMap(updatedSettingsMap);
      } else if (selectedMethod.id === 'phone') {
        updatedSettingsMap = _objectSpread(_objectSpread({}, updatedSettingsMap), {}, {
          phone: settings
        });
        setSettingsMap(updatedSettingsMap);
      } else if (selectedMethod.id === 'org_user_password_rules') {
        updatedPasswordSettings = settings;
        setPasswordSettings(updatedPasswordSettings);
      }
    }

    // 立即触发接口保存
    saveToApi(authMethods, updatedSettingsMap, updatedPasswordSettings);
  };
  var handleSave = function handleSave() {
    saveToApi(authMethods, settingsMap, passwordSettings);
  };

  // 显示加载状态
  if (loading) {
    return /*#__PURE__*/React.createElement("div", {
      className: "org-admin-auth ".concat(className || ''),
      style: _objectSpread(_objectSpread({}, style), {}, {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '400px'
      })
    }, /*#__PURE__*/React.createElement(Spin, {
      size: "large"
    }));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth ".concat(className || ''),
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 1,
    className: "org-admin-auth-title"
  }, locales.getText('org.admin.auth.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "org-admin-auth-description"
  }, locales.getText('org.admin.auth.description'))), /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section-layout"
  }, /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 2,
    className: "org-admin-auth-section-title"
  }, locales.getText('org.admin.auth.methods.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "org-admin-auth-section-description"
  }, locales.getText('org.admin.auth.methods.description'))), /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section-content"
  }, /*#__PURE__*/React.createElement(AuthMethods, {
    methods: authMethods,
    onOrderChange: handleAuthMethodsOrderChange,
    onToggle: handleAuthMethodToggle,
    onSettings: handleAuthMethodSettings,
    onConfigClick: handleConfigClick
  })))), /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section-layout"
  }, /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 2,
    className: "org-admin-auth-section-title"
  }, locales.getText('org.admin.password.settings.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "org-admin-auth-section-description"
  }, locales.getText('org.admin.password.settings.description'))), /*#__PURE__*/React.createElement("div", {
    className: "org-admin-auth-section-content"
  }, /*#__PURE__*/React.createElement(SettingList, {
    methods: getPasswordRulesSetting('org_user_password_rules'),
    onSettings: handlePasswordSettings
  })))), /*#__PURE__*/React.createElement("div", {
    className: "org-admin-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 === 'org_user_password_rules' ? passwordSettings : settingsMap[selectedMethod.id] : undefined
  }));
};
export default OrgAdminAuth;