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/POSOperatorAuth/index.tsx
var POSOperatorAuth_exports = {};
__export(POSOperatorAuth_exports, {
  default: () => POSOperatorAuth_default
});
module.exports = __toCommonJS(POSOperatorAuth_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_POSOperatorAuth = require("./POSOperatorAuth.less");
var { Title, Paragraph } = import_antd.Typography;
var getPOSOperatorAuthMethods = () => [
  {
    id: "digit_id_pin",
    type: import_types.AuthMethodType.DIGIT_ID_PIN,
    title: import_utils.locales.getText("auth.method.digit_id_pin.title") || "Digit ID + PIN",
    category: import_types.AuthMethodCategory.GENERAL,
    description: import_utils.locales.getText("auth.method.digit_id_pin.description") || "Quick login with employee ID and PIN code",
    icon: /* @__PURE__ */ import_react.default.createElement(import_icons.NumberOutlined, { style: { fontSize: 20, color: "#4096ff" } }),
    enabled: true,
    hasSettings: true,
    disableToggle: true
    // 禁用开关
  }
];
var POS_OPERATOR_AUTH_METHODS = getPOSOperatorAuthMethods();
var 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();
  const currentAuthMethods = getPOSOperatorAuthMethods();
  methodsArray.forEach(({ key, enabled, setting }) => {
    processedKeys.add(key);
    if (key === "digit_id_pin") {
      const digitIdPinMethod = currentAuthMethods.find((m) => m.id === "digit_id_pin");
      authMethods.push({
        ...digitIdPinMethod,
        enabled
      });
      settingsMap["digit_id_pin"] = setting;
    }
  });
  currentAuthMethods.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}`);
    if (authMethod.id === "digit_id_pin") {
      const digitIdPinSettings = settingsMap["digit_id_pin"] || {};
      console.log("digit_id_pin settings:", digitIdPinSettings);
      method["digit_id_pin"] = {
        sort: index + 1,
        enabled: authMethod.enabled,
        setting: digitIdPinSettings
      };
      console.log("添加了 digit_id_pin 到 method");
    }
  });
  console.log("最终的 method 对象:", method);
  return {
    method
  };
};
var POSOperatorAuth = ({ 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.pos_operator";
  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_pos_operator_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(getPOSOperatorAuthMethods());
  }, []);
  (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_pos_operator_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 { authMethods: convertedAuthMethods, settingsMap: convertedSettingsMap } = convertApiDataToComponent(apiData);
          setAuthMethods(convertedAuthMethods);
          setSettingsMap(convertedSettingsMap);
          console.log("Converted data:", { convertedAuthMethods, convertedSettingsMap });
        } else {
          setAuthMethods(getPOSOperatorAuthMethods());
        }
        setLoading(false);
      }).catch((error) => {
        console.error("Error fetching tenant data:", error);
        setAuthMethods(getPOSOperatorAuthMethods());
        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 completeSettingsMap = { ...currentSettingsMap };
    currentAuthMethods.forEach((method) => {
      console.log(`检查 method: ${method.id}, 当前有设置: ${!!completeSettingsMap[method.id]}`);
      if (!completeSettingsMap[method.id]) {
        if (method.id === "digit_id_pin") {
          console.log("添加 digit_id_pin 默认设置");
          completeSettingsMap["digit_id_pin"] = {
            digit_length: 4,
            pin_length: 4
          };
        }
      }
    });
    console.log("完整的 settingsMap:", completeSettingsMap);
    const apiData = convertComponentDataToApi(currentAuthMethods, completeSettingsMap);
    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_pos_operator_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) {
      if (selectedMethod.id === "digit_id_pin") {
        updatedSettingsMap = {
          ...updatedSettingsMap,
          digit_id_pin: settings
        };
        setSettingsMap(updatedSettingsMap);
      }
    }
    saveToApi(authMethods, updatedSettingsMap);
  };
  const handleSave = () => {
    saveToApi(authMethods, settingsMap);
  };
  if (loading) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: `pos-operator-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: `pos-operator-auth ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pos-operator-auth-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 1, className: "pos-operator-auth-title" }, import_utils.locales.getText("pos.operator.auth.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "pos-operator-auth-description" }, import_utils.locales.getText("pos.operator.auth.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pos-operator-auth-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pos-operator-auth-section-layout" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pos-operator-auth-section-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 2, className: "pos-operator-auth-section-title" }, import_utils.locales.getText("pos.operator.auth.methods.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "pos-operator-auth-section-description" }, import_utils.locales.getText("pos.operator.auth.methods.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pos-operator-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: "pos-operator-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 ? settingsMap[selectedMethod.id] : void 0
    }
  ));
};
var POSOperatorAuth_default = POSOperatorAuth;
