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 { TeamOutlined } from '@ant-design/icons';
import AuthMethods from "../AuthMethods";
import SettingsDrawer from "../AuthMethods/SettingsDrawer";
import { AuthMethodType, AuthMethodCategory } from "../AuthMethods/types";
import useEngineContext from "../../../../hooks/useEngineContext";
// @ts-ignore
import localeTextsConfig from "./locales";
import "./DeviceAuth.less";
var Title = Typography.Title,
  Paragraph = Typography.Paragraph;

// 接口数据类型定义

/**
 * 获取设备认证方法列表（支持多语言）
 * 每次调用都会根据当前语言设置返回对应的文本
 * @returns 设备认证方法数组
 */
var getDeviceAuthMethods = function getDeviceAuthMethods() {
  return [{
    id: 'team_member',
    type: AuthMethodType.TEAM_MEMBER,
    title: locales.getText('device.auth.method.team-member.title') || 'Team Member',
    category: AuthMethodCategory.GENERAL,
    description: locales.getText('device.auth.method.team-member.description') || 'Use Team Member authentication methods',
    inheritMessage: locales.getText('device.auth.method.team-member.inherit') || 'Inherits from Team Member authentication settings',
    icon: /*#__PURE__*/React.createElement(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,
  // },
  ];
};

/**
 * 设备认证方法列表（已废弃，仅保留用于向后兼容）
 * @deprecated 请使用 getDeviceAuthMethods() 函数以获取实时的多语言支持
 */
var DEVICE_AUTH_METHODS = getDeviceAuthMethods();

// 将接口数据转换为组件数据
var convertApiDataToComponent = function convertApiDataToComponent(apiData, currentMethods) {
  // 转换认证方法
  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);
    var defaultMethod = currentMethods.find(function (m) {
      return m.id === key;
    });
    if (defaultMethod) {
      authMethods.push(_objectSpread(_objectSpread({}, defaultMethod), {}, {
        enabled: enabled
      }));
      if (setting) {
        settingsMap[key] = setting;
      }
    }
  });

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

// 将组件数据转换为接口数据
var convertComponentDataToApi = function convertComponentDataToApi(authMethods, settingsMap) {
  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));
    var setting = settingsMap[authMethod.id];
    method[authMethod.id] = _objectSpread({
      sort: index + 1,
      enabled: authMethod.enabled
    }, setting && {
      setting: setting
    });
  });
  console.log('最终的 method 对象:', method);
  return {
    method: method
  };
};
var DeviceAuth = function DeviceAuth(_ref4) {
  var className = _ref4.className,
    style = _ref4.style,
    onSave = _ref4.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.device';
  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(false),
    _useState10 = _slicedToArray(_useState9, 2),
    drawerOpen = _useState10[0],
    setDrawerOpen = _useState10[1];
  var _useState11 = useState(null),
    _useState12 = _slicedToArray(_useState11, 2),
    selectedMethod = _useState12[0],
    setSelectedMethod = _useState12[1];

  // 初始化 locales 并设置默认认证方法
  useEffect(function () {
    var _context$engine;
    console.log('app_init_device_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');
    // locales 初始化后，设置带有正确多语言的默认认证方法
    setAuthMethods(getDeviceAuthMethods());
  }, []);

  // 解析 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_device_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 apiData = (_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value;
          // 使用当前语言的认证方法定义
          var currentDeviceMethods = getDeviceAuthMethods();
          var _convertApiDataToComp = convertApiDataToComponent(apiData, currentDeviceMethods),
            convertedAuthMethods = _convertApiDataToComp.authMethods,
            convertedSettingsMap = _convertApiDataToComp.settingsMap;
          setAuthMethods(convertedAuthMethods);
          setSettingsMap(convertedSettingsMap);
          console.log('Converted data:', {
            convertedAuthMethods: convertedAuthMethods,
            convertedSettingsMap: convertedSettingsMap
          });
        } else {
          // 如果没有数据，使用默认值
          setAuthMethods(getDeviceAuthMethods());
        }
        setLoading(false);
      }).catch(function (error) {
        console.error('Error fetching tenant data:', error);
        // 即使出错，也使用默认值
        setAuthMethods(getDeviceAuthMethods());
        setLoading(false);
      });
    }
  }, [tenantId, request]);
  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 handleDrawerClose = function handleDrawerClose() {
    setDrawerOpen(false);
    setSelectedMethod(null);
  };

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

    // 将组件数据转换为接口数据
    var apiData = convertComponentDataToApi(currentAuthMethods, currentSettingsMap);

    // 打印转换后的接口数据
    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_device_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);
    if (selectedMethod) {
      updatedSettingsMap = _objectSpread(_objectSpread({}, updatedSettingsMap), {}, _defineProperty({}, selectedMethod.id, settings));
      setSettingsMap(updatedSettingsMap);
    }

    // 立即触发接口保存
    saveToApi(authMethods, updatedSettingsMap);
  };
  var handleSave = function handleSave() {
    saveToApi(authMethods, settingsMap);
  };
  var handleCancel = function handleCancel() {
    console.log('Settings cancelled');
  };

  // 显示加载状态
  if (loading) {
    return /*#__PURE__*/React.createElement("div", {
      className: "device-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: "device-auth ".concat(className || ''),
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "device-auth-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 1,
    className: "device-auth-title"
  }, locales.getText('device.auth.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "device-auth-description"
  }, locales.getText('device.auth.description'))), /*#__PURE__*/React.createElement("div", {
    className: "device-auth-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "device-auth-section-layout"
  }, /*#__PURE__*/React.createElement("div", {
    className: "device-auth-section-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 2,
    className: "device-auth-section-title"
  }, locales.getText('device.auth.methods.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "device-auth-section-description"
  }, locales.getText('device.auth.methods.description'))), /*#__PURE__*/React.createElement("div", {
    className: "device-auth-section-content"
  }, /*#__PURE__*/React.createElement(AuthMethods, {
    methods: authMethods,
    onOrderChange: handleAuthMethodsOrderChange,
    onToggle: handleAuthMethodToggle,
    onSettings: handleAuthMethodSettings
  })))), /*#__PURE__*/React.createElement("div", {
    className: "device-auth-footer"
  }, /*#__PURE__*/React.createElement(Button, {
    size: "large",
    onClick: handleCancel
  }, locales.getText('auth.button.cancel')), /*#__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 ? settingsMap[selectedMethod.id] : undefined
  }));
};
export default DeviceAuth;