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 _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; }
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); }
import React, { useState, useEffect } from 'react';
import { Button, Radio, Alert, Typography, Spin } from 'antd';
import { InfoCircleOutlined, UserOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { locales } from '@pisell/utils';
import localeTexts from "./locales";
import useEngineContext from "../../../../../hooks/useEngineContext";
import AuthMethods from "../../AuthMethods";
import { getDefaultAuthMethods } from "../../AuthMethods/constants";
import "./AuthenticationMethods.less";
var Title = Typography.Title,
  Paragraph = Typography.Paragraph,
  Text = Typography.Text;

// 将API数据转换为组件数据格式
var convertApiDataToComponent = function convertApiDataToComponent(apiData) {
  var method = apiData.method;
  var processedKeys = new Set();

  // 将API数据转换为 AuthMethod[] 格式
  var authMethods = Object.keys(method).map(function (key) {
    processedKeys.add(key);
    var methodData = method[key];
    var methodId = key === 'phone' ? 'phone' : key;

    // 从 getDefaultAuthMethods() 中找到对应的基础配置
    var baseMethod = getDefaultAuthMethods().find(function (m) {
      return m.id === methodId;
    });
    if (!baseMethod) {
      return null;
    }
    return _objectSpread(_objectSpread({}, baseMethod), {}, {
      enabled: methodData.enabled,
      sort: methodData.sort
    });
  }).filter(Boolean);

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

  // 按照 sort 排序
  authMethods.sort(function (a, b) {
    var _a$sort, _b$sort;
    var sortA = (_a$sort = a.sort) !== null && _a$sort !== void 0 ? _a$sort : 0;
    var sortB = (_b$sort = b.sort) !== null && _b$sort !== void 0 ? _b$sort : 0;
    return sortA - sortB;
  });

  // 将 AuthMethod[] 转换为 GlobalAuthMethod[] 格式用于 default mode 显示
  var globalMethods = authMethods.map(function (method) {
    var methodKey = method.id === 'phone' ? 'phoneNumber' : method.id;

    // 为每个方法定义多语言标签
    var labelMap = {
      email: {
        en: 'Email',
        'zh-CN': '邮箱',
        'zh-HK': '郵箱',
        ja: 'メール',
        pt: 'E-mail'
      },
      phone: {
        en: 'Phone Number',
        'zh-CN': '手机号',
        'zh-HK': '手機號',
        ja: '電話番号',
        pt: 'Número de Telefone'
      },
      facebook: {
        en: 'Facebook',
        'zh-CN': 'Facebook',
        'zh-HK': 'Facebook',
        ja: 'Facebook',
        pt: 'Facebook'
      },
      apple: {
        en: 'Apple',
        'zh-CN': 'Apple',
        'zh-HK': 'Apple',
        ja: 'Apple',
        pt: 'Apple'
      },
      guest: {
        en: 'Guest',
        'zh-CN': '访客',
        'zh-HK': '訪客',
        ja: 'ゲスト',
        pt: 'Convidado'
      }
    };
    return {
      method: methodKey,
      enabled: method.enabled,
      label: labelMap[method.id] || {
        en: method.id,
        'zh-CN': method.id,
        'zh-HK': method.id
      }
    };
  });
  return {
    authMethods: authMethods,
    globalMethods: globalMethods
  };
};

// 模拟的全局认证方法数据
var mockGlobalMethods = [{
  method: 'email',
  enabled: true,
  label: {
    en: 'Email',
    'zh-CN': '邮箱',
    'zh-HK': '郵箱',
    ja: 'メール',
    pt: 'E-mail'
  }
}, {
  method: 'phoneNumber',
  enabled: true,
  label: {
    en: 'Phone Number',
    'zh-CN': '手机号',
    'zh-HK': '手機號',
    ja: '電話番号',
    pt: 'Número de Telefone'
  }
}, {
  method: 'facebook',
  enabled: true,
  label: {
    en: 'Facebook',
    'zh-CN': 'Facebook',
    'zh-HK': 'Facebook',
    ja: 'Facebook',
    pt: 'Facebook'
  }
}, {
  method: 'apple',
  enabled: true,
  label: {
    en: 'Apple',
    'zh-CN': 'Apple',
    'zh-HK': 'Apple',
    ja: 'Apple',
    pt: 'Apple'
  }
}];
var AuthenticationMethods = function AuthenticationMethods(_ref) {
  var _context$engine;
  var className = _ref.className,
    style = _ref.style,
    value = _ref.value,
    onChange = _ref.onChange,
    _ref$globalMethods = _ref.globalMethods,
    globalMethods = _ref$globalMethods === void 0 ? mockGlobalMethods : _ref$globalMethods,
    onConfigureGlobal = _ref.onConfigureGlobal;
  var context = useEngineContext();
  locales.init(localeTexts, (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');
  var _context$appHelper$ut = context.appHelper.utils.getApp(),
    request = _context$appHelper$ut.request,
    data = _context$appHelper$ut.data,
    history = _context$appHelper$ut.history;
  var dataKey = 'auth.customer';
  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('default'),
    _useState6 = _slicedToArray(_useState5, 2),
    mode = _useState6[0],
    setMode = _useState6[1];
  var _useState7 = useState(getDefaultAuthMethods()),
    _useState8 = _slicedToArray(_useState7, 2),
    authMethods = _useState8[0],
    setAuthMethods = _useState8[1];

  // 保存从API获取的数据用于 default mode 显示
  var _useState9 = useState(mockGlobalMethods),
    _useState10 = _slicedToArray(_useState9, 2),
    fetchedGlobalMethods = _useState10[0],
    setFetchedGlobalMethods = _useState10[1];

  // 解析 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 存在且变更时，发送请求获取数据
  // 注意：接口查询的数据只用于 default mode 显示
  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_customer_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,
            convertedGlobalMethods = _convertApiDataToComp.globalMethods;

          // 更新 fetchedGlobalMethods 用于 default mode 显示
          setFetchedGlobalMethods(convertedGlobalMethods);
          console.log('Converted data:', {
            authMethods: convertedAuthMethods,
            globalMethods: convertedGlobalMethods
          });
        }
        setLoading(false);
      }).catch(function (error) {
        console.error('Error fetching tenant data:', error);
        setLoading(false);
      });
    }
  }, [tenantId, request]);

  // 同步外部value变化
  // 注意：外部传入的 value.methods 才是 AuthMethods 组件最终使用的 methods 数组
  useEffect(function () {
    if (value) {
      setMode(value.mode || 'default');

      // 始终基于所有默认方法进行初始化，确保包含所有方法（如 guest）
      console.log('同步外部value - 输入的 value.methods:', value.methods);
      var updatedMethods = getDefaultAuthMethods().map(function (method, index) {
        var _value$methods, _method$sort;
        var methodKey = method.id === 'phone' ? 'phoneNumber' : method.id;
        var config = (_value$methods = value.methods) === null || _value$methods === void 0 ? void 0 : _value$methods[methodKey];
        if (config && _typeof(config) === 'object' && 'enabled' in config) {
          var _config$enabled, _config$sort;
          return _objectSpread(_objectSpread({}, method), {}, {
            enabled: (_config$enabled = config.enabled) !== null && _config$enabled !== void 0 ? _config$enabled : method.enabled,
            sort: (_config$sort = config.sort) !== null && _config$sort !== void 0 ? _config$sort : index
          });
        }
        // 即使外部没有配置，也保留默认方法（如 guest）
        return _objectSpread(_objectSpread({}, method), {}, {
          sort: (_method$sort = method.sort) !== null && _method$sort !== void 0 ? _method$sort : index
        });
      }).sort(function (a, b) {
        var _a$sort2, _b$sort2;
        var sortA = (_a$sort2 = a.sort) !== null && _a$sort2 !== void 0 ? _a$sort2 : 0;
        var sortB = (_b$sort2 = b.sort) !== null && _b$sort2 !== void 0 ? _b$sort2 : 0;
        return sortA - sortB;
      });
      console.log('同步外部value - 生成的 updatedMethods:', updatedMethods);
      setAuthMethods(updatedMethods);
    }
  }, [value]);

  // 将 AuthMethod[] 转换为配置对象
  var convertAuthMethodsToConfig = function convertAuthMethodsToConfig(methods) {
    console.log('convertAuthMethodsToConfig - 输入的 methods:', methods);
    var config = {};
    methods.forEach(function (method, index) {
      var _method$sort2;
      var key = method.id === 'phone' ? 'phoneNumber' : method.id;
      config[key] = {
        enabled: method.enabled,
        sort: (_method$sort2 = method.sort) !== null && _method$sort2 !== void 0 ? _method$sort2 : index // 优先使用 method.sort，如果没有则使用 index
      };
    });
    console.log('convertAuthMethodsToConfig - 输出的 config:', config);
    return config;
  };
  var handleModeChange = function handleModeChange(e) {
    setMode(e.target.value);
    onChange === null || onChange === void 0 || onChange({
      mode: e.target.value,
      methods: convertAuthMethodsToConfig(authMethods)
    });
  };
  var handleConfigureGlobal = function handleConfigureGlobal() {
    history.push('/system-settings/auth/customer');
  };
  var handleOAuthConfig = function handleOAuthConfig() {
    history.push('/system-settings/auth/oauth-config');
  };
  var handleAuthMethodsOrderChange = function handleAuthMethodsOrderChange(methods) {
    console.log('handleAuthMethodsOrderChange', methods);
    // 同步更新本地状态，确保包含所有方法
    setAuthMethods(methods);
    onChange === null || onChange === void 0 || onChange({
      mode: mode,
      methods: convertAuthMethodsToConfig(methods)
    });
  };
  var handleAuthMethodsToggle = function handleAuthMethodsToggle(method, enabled) {
    var updatedMethods = authMethods.map(function (m) {
      return m.id === method.id ? _objectSpread(_objectSpread({}, m), {}, {
        enabled: enabled
      }) : m;
    });
    // 同步更新本地状态
    setAuthMethods(updatedMethods);
    setTimeout(function () {
      onChange === null || onChange === void 0 || onChange({
        mode: mode,
        methods: convertAuthMethodsToConfig(updatedMethods)
      });
    }, 0);
  };

  // 渲染认证方法标签
  var renderMethodTag = function renderMethodTag(method) {
    var _context$engine2;
    var statusText = method.enabled ? locales.getText('auth.methods.status.enabled') : locales.getText('auth.methods.status.disabled');
    var locale = (context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale) || 'en';
    var label = method.label[locale] || method.label.en;
    return /*#__PURE__*/React.createElement("div", {
      key: method.method,
      className: "auth-method-item"
    }, /*#__PURE__*/React.createElement("span", {
      className: "auth-method-status ".concat(method.enabled ? 'enabled' : 'disabled')
    }, statusText), /*#__PURE__*/React.createElement(Text, null, label));
  };

  // 显示加载状态
  if (loading) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('authentication-methods', 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: classNames('authentication-methods', className),
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-upper"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 2,
    className: "authentication-methods-title"
  }, locales.getText('auth.methods.title'))), /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-mode"
  }, /*#__PURE__*/React.createElement(Radio.Group, {
    value: mode,
    onChange: handleModeChange
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-mode-wrapper"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-mode-option"
  }, /*#__PURE__*/React.createElement(Radio, {
    value: "default"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-mode-content"
  }, /*#__PURE__*/React.createElement(Text, {
    strong: true,
    className: "authentication-methods-mode-title"
  }, locales.getText('auth.methods.mode.default.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "authentication-methods-mode-description"
  }, locales.getText('auth.methods.mode.default.description')), /*#__PURE__*/React.createElement(Button, {
    type: "link",
    className: "authentication-methods-configure-link",
    onClick: handleConfigureGlobal,
    style: {
      padding: 0,
      height: 'auto'
    }
  }, locales.getText('auth.methods.mode.default.configure'))))), /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-mode-option"
  }, /*#__PURE__*/React.createElement(Radio, {
    value: "custom"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-mode-content"
  }, /*#__PURE__*/React.createElement(Text, {
    strong: true,
    className: "authentication-methods-mode-title"
  }, locales.getText('auth.methods.mode.custom.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "authentication-methods-mode-description"
  }, locales.getText('auth.methods.mode.custom.description'))))))))), /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-middle"
  }, mode === 'default' && /*#__PURE__*/React.createElement(Alert, {
    message: locales.getText('auth.methods.preview.title'),
    description: locales.getText('auth.methods.preview.description'),
    type: "info",
    showIcon: true,
    icon: /*#__PURE__*/React.createElement(InfoCircleOutlined, null)
  }), mode === 'custom' && /*#__PURE__*/React.createElement(Alert, {
    message: locales.getText('auth.methods.custom.warning.title'),
    description: locales.getText('auth.methods.custom.warning.description'),
    type: "warning",
    showIcon: true
  })), /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-lower"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-customer"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-customer-left"
  }, /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-customer-header"
  }, /*#__PURE__*/React.createElement(UserOutlined, {
    className: "authentication-methods-customer-icon"
  }), /*#__PURE__*/React.createElement(Title, {
    level: 4,
    className: "authentication-methods-customer-title"
  }, locales.getText('auth.methods.customer.title'))), /*#__PURE__*/React.createElement(Paragraph, {
    className: "authentication-methods-customer-description"
  }, locales.getText('auth.methods.customer.description'))), /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-customer-right"
  }, mode === 'default' ?
  /*#__PURE__*/
  // Default mode: Show inherited methods list
  React.createElement("div", {
    className: "authentication-methods-inherited"
  }, /*#__PURE__*/React.createElement(Paragraph, {
    className: "authentication-methods-inherited-title"
  }, locales.getText('auth.methods.preview.inherited')), /*#__PURE__*/React.createElement("div", {
    className: "authentication-methods-list"
  }, fetchedGlobalMethods.map(renderMethodTag))) :
  /*#__PURE__*/
  // Custom mode: Show AuthMethods component
  React.createElement(AuthMethods, {
    methods: authMethods,
    onOrderChange: handleAuthMethodsOrderChange,
    onToggle: handleAuthMethodsToggle,
    onConfigClick: handleOAuthConfig,
    enableSetting: false
  })))));
};
export default AuthenticationMethods;