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/DeviceAuth/index.tsx
var DeviceAuth_exports = {};
__export(DeviceAuth_exports, {
  default: () => DeviceAuth_default
});
module.exports = __toCommonJS(DeviceAuth_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_icons = require("@ant-design/icons");
var import_AuthMethods = __toESM(require("../AuthMethods"));
var import_SettingsDrawer = __toESM(require("../AuthMethods/SettingsDrawer"));
var import_types = require("../AuthMethods/types");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_locales = __toESM(require("./locales"));
var import_DeviceAuth = require("./DeviceAuth.less");
var { Title, Paragraph } = import_antd.Typography;
var getDeviceAuthMethods = () => [
  {
    id: "team_member",
    type: import_types.AuthMethodType.TEAM_MEMBER,
    title: import_utils.locales.getText("device.auth.method.team-member.title") || "Team Member",
    category: import_types.AuthMethodCategory.GENERAL,
    description: import_utils.locales.getText("device.auth.method.team-member.description") || "Use Team Member authentication methods",
    inheritMessage: import_utils.locales.getText("device.auth.method.team-member.inherit") || "Inherits from Team Member authentication settings",
    icon: /* @__PURE__ */ import_react.default.createElement(import_icons.TeamOutlined, { style: { fontSize: 20, color: "#4096ff" } }),
    enabled: true,
    hasSettings: false
  }
  // {
  //   id: 'device_passcode',
  //   type: AuthMethodType.DEVICE_PASSCODE,
  //   title: locales.getText('device.auth.method.device-passcode.title') || 'Device Passcode',
  //   category: AuthMethodCategory.PASSWORD_FREE,
  //   description: locales.getText('device.auth.method.device-passcode.description') || 'Password-free login with dynamic device passcode authentication',
  //   icon: <KeyOutlined style={{ fontSize: 20, color: '#52c41a' }} />,
  //   enabled: false,
  //   hasSettings: true,
  // },
];
var DEVICE_AUTH_METHODS = getDeviceAuthMethods();
var 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({
        ...defaultMethod,
        enabled
      });
      if (setting) {
        settingsMap[key] = setting;
      }
    }
  });
  currentMethods.forEach((defaultMethod) => {
    if (!processedKeys.has(defaultMethod.id)) {
      authMethods.push({
        ...defaultMethod,
        enabled: false
      });
    }
  });
  return { authMethods, settingsMap };
};
var 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] = {
      sort: index + 1,
      enabled: authMethod.enabled,
      ...setting && { setting }
    };
  });
  console.log("最终的 method 对象:", method);
  return { method };
};
var DeviceAuth = ({ 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.device";
  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 [drawerOpen, setDrawerOpen] = (0, import_react.useState)(false);
  const [selectedMethod, setSelectedMethod] = (0, import_react.useState)(null);
  (0, import_react.useEffect)(() => {
    var _a, _b;
    console.log("app_init_device_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");
    setAuthMethods(getDeviceAuthMethods());
  }, []);
  (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_device_auth_methods", res);
        if ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.length) {
          const apiData = (_b = res.data[0]) == null ? void 0 : _b.value;
          const currentDeviceMethods = getDeviceAuthMethods();
          const { authMethods: convertedAuthMethods, settingsMap: convertedSettingsMap } = convertApiDataToComponent(apiData, currentDeviceMethods);
          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 ? { ...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 ? void 0 : onSave(currentAuthMethods);
    request.post(`/tenant/core/meta/tenant/${tenantId}`, {
      [dataKey]: apiData
    }).then((res) => {
      console.log("res_device_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 };
    if (selectedMethod) {
      updatedSettingsMap = {
        ...updatedSettingsMap,
        [selectedMethod.id]: settings
      };
      setSettingsMap(updatedSettingsMap);
    }
    saveToApi(authMethods, updatedSettingsMap);
  };
  const handleSave = () => {
    saveToApi(authMethods, settingsMap);
  };
  const handleCancel = () => {
    console.log("Settings cancelled");
  };
  if (loading) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: `device-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: `device-auth ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "device-auth-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 1, className: "device-auth-title" }, import_utils.locales.getText("device.auth.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "device-auth-description" }, import_utils.locales.getText("device.auth.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "device-auth-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "device-auth-section-layout" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "device-auth-section-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 2, className: "device-auth-section-title" }, import_utils.locales.getText("device.auth.methods.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "device-auth-section-description" }, import_utils.locales.getText("device.auth.methods.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "device-auth-section-content" }, /* @__PURE__ */ import_react.default.createElement(
    import_AuthMethods.default,
    {
      methods: authMethods,
      onOrderChange: handleAuthMethodsOrderChange,
      onToggle: handleAuthMethodToggle,
      onSettings: handleAuthMethodSettings
    }
  )))), /* @__PURE__ */ import_react.default.createElement("div", { className: "device-auth-footer" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { size: "large", onClick: handleCancel }, import_utils.locales.getText("auth.button.cancel")), /* @__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 ? settingsMap[selectedMethod.id] : void 0
    }
  ));
};
var DeviceAuth_default = DeviceAuth;
