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, useMemo, useCallback } from 'react';
import { Tabs, Button, Typography, message, Spin } from 'antd';
import classNames from 'classnames';
import { locales } from '@pisell/utils';
import useEngineContext from "../../../../../hooks/useEngineContext";
import PageSetting from "../PageSetting";
import localeTexts from "../locales";
import "./index.less";
var Title = Typography.Title,
  Paragraph = Typography.Paragraph;
var SaaSManagermentAuth = function SaaSManagermentAuth(_ref) {
  var _context$engine;
  var className = _ref.className,
    style = _ref.style,
    value = _ref.value,
    defaultActiveTab = _ref.defaultActiveTab,
    visibleTabs = _ref.visibleTabs,
    _ref$showRegisterPage = _ref.showRegisterPage,
    showRegisterPage = _ref$showRegisterPage === void 0 ? true : _ref$showRegisterPage,
    onSave = _ref.onSave;
  var context = useEngineContext();
  var useParams = context.appHelper.utils.getApp().history.useParams;
  var _useParams = useParams(),
    channel = _useParams.channel;
  var _context$appHelper$ut = context.appHelper.utils.getApp(),
    request = _context$appHelper$ut.request;
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    loading = _useState2[0],
    setLoading = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    channelData = _useState4[0],
    setChannelData = _useState4[1];
  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');

  // 所有可用的Tab
  var allTabs = ['pageSetting'];
  var saveData = function saveData(data) {
    debugger;
    request.post("/api/tenant_channel:update?filter=%7B%22channel_code%22%3A%22".concat(channel, "%22%7D"), _objectSpread(_objectSpread({}, channelData), {}, {
      metadata: _objectSpread(_objectSpread({}, channelData === null || channelData === void 0 ? void 0 : channelData.metadata), {}, {
        register_login: data
      })
    }), {
      isNocobase: true,
      headers: {
        "x-data-source": "pisell2"
      }
    }).then(function (res) {
      message.success(locales.getText('channel.auth.setting.message.saveSuccess'));
    }).catch(function (error) {
      console.error('Error saving channel data:', error);
      message.error(locales.getText('channel.auth.setting.message.saveError'));
    });
  };
  useEffect(function () {
    if (channel) {
      setLoading(true);
      request.get("/api/tenant_channel:get?filter=%7B%22channel_code%22%3A%22".concat(channel, "%22%7D&appends=channel"), {}, {
        isNocobase: true,
        headers: {
          "x-data-source": "pisell2"
        }
      }).then(function (res) {
        if (res !== null && res !== void 0 && res.data) {
          setChannelData(res === null || res === void 0 ? void 0 : res.data);
        }
        console.log('res_saas_management_auth', res);
        setLoading(false);
      }).catch(function (error) {
        console.error('Error fetching channel data:', error);
        setLoading(false);
      });
    }
  }, [request, channel]);

  // 确定实际显示的Tab
  var displayTabs = useMemo(function () {
    if (visibleTabs && visibleTabs.length > 0) {
      // 如果指定了visibleTabs，则过滤出有效的tab
      return allTabs.filter(function (tab) {
        return visibleTabs.includes(tab);
      });
    }
    // 否则显示所有tab
    return allTabs;
  }, [visibleTabs]);

  // 确定初始激活的Tab
  var initialActiveTab = useMemo(function () {
    // 如果指定了defaultActiveTab且在displayTabs中，使用它
    if (defaultActiveTab && displayTabs.includes(defaultActiveTab)) {
      return defaultActiveTab;
    }
    // 否则使用第一个可见的tab
    return displayTabs[0] || 'pageSetting';
  }, [defaultActiveTab, displayTabs]);
  var _useState5 = useState(initialActiveTab),
    _useState6 = _slicedToArray(_useState5, 2),
    activeTab = _useState6[0],
    setActiveTab = _useState6[1];
  var _useState7 = useState(value || {}),
    _useState8 = _slicedToArray(_useState7, 2),
    internalValue = _useState8[0],
    setInternalValue = _useState8[1];

  // 同步外部value变化
  useEffect(function () {
    if (value) {
      setInternalValue(value);
    }
  }, [value]);

  // 从channelData.metadata.register_login设置默认值
  useEffect(function () {
    var _channelData$metadata;
    if (channelData !== null && channelData !== void 0 && (_channelData$metadata = channelData.metadata) !== null && _channelData$metadata !== void 0 && _channelData$metadata.register_login) {
      var page = channelData.metadata.register_login.page;

      // 转换page数据到internalValue格式
      var pageSettingValue = {};
      if (page) {
        var _page$register, _page$register2, _page$login$same_as_r, _page$login, _page$login2, _page$login3, _page$login4;
        pageSettingValue.registerPage = {
          backgroundImage: ((_page$register = page.register) === null || _page$register === void 0 ? void 0 : _page$register.background_image_url) || '',
          termsConditions: ((_page$register2 = page.register) === null || _page$register2 === void 0 || (_page$register2 = _page$register2.terms) === null || _page$register2 === void 0 ? void 0 : _page$register2.map(function (term) {
            var _term$name, _term$name2, _term$name3, _term$name4, _term$name5, _term$name6;
            return {
              name: {
                original: ((_term$name = term.name) === null || _term$name === void 0 ? void 0 : _term$name.original) || '',
                en: ((_term$name2 = term.name) === null || _term$name2 === void 0 ? void 0 : _term$name2.en) || '',
                'zh-CN': ((_term$name3 = term.name) === null || _term$name3 === void 0 ? void 0 : _term$name3['zh-CN']) || '',
                'zh-HK': ((_term$name4 = term.name) === null || _term$name4 === void 0 ? void 0 : _term$name4['zh-HK']) || '',
                ja: ((_term$name5 = term.name) === null || _term$name5 === void 0 ? void 0 : _term$name5['ja']) || '',
                pt: ((_term$name6 = term.name) === null || _term$name6 === void 0 ? void 0 : _term$name6['pt']) || ''
              },
              url: term.url || ''
            };
          })) || []
        };
        pageSettingValue.loginPage = {
          sameAsRegister: (_page$login$same_as_r = (_page$login = page.login) === null || _page$login === void 0 ? void 0 : _page$login.same_as_register) !== null && _page$login$same_as_r !== void 0 ? _page$login$same_as_r : true,
          settings: (_page$login2 = page.login) !== null && _page$login2 !== void 0 && _page$login2.same_as_register ? undefined : {
            backgroundImage: ((_page$login3 = page.login) === null || _page$login3 === void 0 ? void 0 : _page$login3.background_image_url) || '',
            termsConditions: ((_page$login4 = page.login) === null || _page$login4 === void 0 || (_page$login4 = _page$login4.terms) === null || _page$login4 === void 0 ? void 0 : _page$login4.map(function (term) {
              var _term$name7, _term$name8, _term$name9, _term$name10, _term$name11, _term$name12;
              return {
                name: {
                  original: ((_term$name7 = term.name) === null || _term$name7 === void 0 ? void 0 : _term$name7.original) || '',
                  en: ((_term$name8 = term.name) === null || _term$name8 === void 0 ? void 0 : _term$name8.en) || '',
                  'zh-CN': ((_term$name9 = term.name) === null || _term$name9 === void 0 ? void 0 : _term$name9['zh-CN']) || '',
                  'zh-HK': ((_term$name10 = term.name) === null || _term$name10 === void 0 ? void 0 : _term$name10['zh-HK']) || '',
                  ja: ((_term$name11 = term.name) === null || _term$name11 === void 0 ? void 0 : _term$name11['ja']) || '',
                  pt: ((_term$name12 = term.name) === null || _term$name12 === void 0 ? void 0 : _term$name12['pt']) || ''
                },
                url: term.url || ''
              };
            })) || []
          }
        };
      }
      setInternalValue({
        pageSetting: pageSettingValue
      });
    }
  }, [channelData]);
  var handlePageSettingChange = useCallback(function (pageSettingValue) {
    setInternalValue(function (prev) {
      // 检查pageSetting是否发生了实质性变化
      var hasPageSettingChanged = JSON.stringify(prev.pageSetting) !== JSON.stringify(pageSettingValue);
      if (hasPageSettingChanged) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          pageSetting: pageSettingValue
        });
      }
      return prev;
    });
  }, []);

  // 将数据转换为新的格式
  var transformToNewFormat = function transformToNewFormat(value) {
    var _pageSetting$register, _pageSetting$register2, _pageSetting$loginPag, _pageSetting$loginPag2, _pageSetting$loginPag3, _pageSetting$loginPag4, _pageSetting$loginPag5, _pageSetting$loginPag6;
    var pageSetting = value.pageSetting;
    console.log('pageSetting data:', pageSetting);

    // 转换 Page Settings
    var pageData = {
      register: {
        background_image_url: (pageSetting === null || pageSetting === void 0 || (_pageSetting$register = pageSetting.registerPage) === null || _pageSetting$register === void 0 ? void 0 : _pageSetting$register.backgroundImage) || '',
        terms: (pageSetting === null || pageSetting === void 0 || (_pageSetting$register2 = pageSetting.registerPage) === null || _pageSetting$register2 === void 0 || (_pageSetting$register2 = _pageSetting$register2.termsConditions) === null || _pageSetting$register2 === void 0 ? void 0 : _pageSetting$register2.map(function (term) {
          return {
            name: {
              original: term.name.original || '',
              en: term.name.en || '',
              'zh-CN': term.name['zh-CN'] || '',
              'zh-HK': term.name['zh-HK'] || '',
              ja: term.name['ja'] || '',
              pt: term.name['pt'] || ''
            },
            url: term.url || ''
          };
        })) || []
      },
      login: {
        same_as_register: (_pageSetting$loginPag = pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag2 = pageSetting.loginPage) === null || _pageSetting$loginPag2 === void 0 ? void 0 : _pageSetting$loginPag2.sameAsRegister) !== null && _pageSetting$loginPag !== void 0 ? _pageSetting$loginPag : true,
        background_image_url: pageSetting !== null && pageSetting !== void 0 && (_pageSetting$loginPag3 = pageSetting.loginPage) !== null && _pageSetting$loginPag3 !== void 0 && _pageSetting$loginPag3.sameAsRegister ? null : (pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag4 = pageSetting.loginPage) === null || _pageSetting$loginPag4 === void 0 || (_pageSetting$loginPag4 = _pageSetting$loginPag4.settings) === null || _pageSetting$loginPag4 === void 0 ? void 0 : _pageSetting$loginPag4.backgroundImage) || null,
        terms: pageSetting !== null && pageSetting !== void 0 && (_pageSetting$loginPag5 = pageSetting.loginPage) !== null && _pageSetting$loginPag5 !== void 0 && _pageSetting$loginPag5.sameAsRegister ? [] : (pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag6 = pageSetting.loginPage) === null || _pageSetting$loginPag6 === void 0 || (_pageSetting$loginPag6 = _pageSetting$loginPag6.settings) === null || _pageSetting$loginPag6 === void 0 || (_pageSetting$loginPag6 = _pageSetting$loginPag6.termsConditions) === null || _pageSetting$loginPag6 === void 0 ? void 0 : _pageSetting$loginPag6.map(function (term) {
          return {
            name: {
              original: term.name.original || '',
              en: term.name.en || '',
              'zh-CN': term.name['zh-CN'] || '',
              'zh-HK': term.name['zh-HK'] || '',
              ja: term.name['ja'] || '',
              pt: term.name['pt'] || ''
            },
            url: term.url || ''
          };
        })) || []
      }
    };
    return {
      page: pageData
    };
  };
  var handleSave = function handleSave() {
    var transformedValue = transformToNewFormat(internalValue);
    console.log('transformedValue', transformedValue);
    saveData(transformedValue);
  };

  // 定义Tab配置
  var tabItems = useMemo(function () {
    return [{
      key: 'pageSetting',
      label: locales.getText('channel.auth.setting.tab.pageSetting'),
      children: /*#__PURE__*/React.createElement(PageSetting, {
        value: internalValue.pageSetting,
        onChange: handlePageSettingChange,
        showRegisterPage: showRegisterPage
      })
    }];
  }, [internalValue, showRegisterPage]);

  // 显示加载状态
  if (loading) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('channel-auth-setting', 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('saasmanagermentauth', className),
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "saasmanagermentauth-header"
  }, /*#__PURE__*/React.createElement(Title, {
    level: 1,
    className: "saasmanagermentauth-title"
  }, locales.getText('channel.auth.setting.title')), /*#__PURE__*/React.createElement(Paragraph, {
    className: "saasmanagermentauth-description"
  }, locales.getText('channel.auth.setting.description'))), /*#__PURE__*/React.createElement("div", {
    className: "saasmanagermentauth-tabs"
  }, /*#__PURE__*/React.createElement(Tabs, {
    activeKey: activeTab,
    onChange: setActiveTab,
    items: tabItems
  })), /*#__PURE__*/React.createElement("div", {
    className: "saasmanagermentauth-footer"
  }, /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    onClick: handleSave
  }, locales.getText('channel.auth.setting.button.save'))));
};
export default SaaSManagermentAuth;