var _excluded = ["onBlur", "onChange", "rootDomain", "customDomain", "value", "tenantId", "fieldKey"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { Input as AntInput } from 'antd';
import { useTenantData } from "./serve";
import ReadPretty from "./ReadPretty";
import { withMode } from "../../dataSourceForm/utils";
import useDataSource from "../../hooks/useDataSource";
import useEngineContext from "../../../../hooks/useEngineContext";

// 定义组件的属性类型

/**
 * 子域名输入组件
 * 
 * 校验规则：
 * 1. 长度限制：
 *    - 最小长度：2个字符
 *    - 最大长度：60个字符
 * 
 * 2. 字符限制：
 *    - 只允许小写字母、数字和连字符(-)
 *    - 不能全为数字
 *    - 不能以连字符开头或结尾
 *    - 不能包含连续的连字符(--)
 * 
 * 格式示例：
 * - 有效：my-subdomain
 * - 有效：web123
 * - 无效：123 (全数字)
 * - 无效：-subdomain (以连字符开头)
 * - 无效：subdomain- (以连字符结尾)
 * - 无效：sub--domain (包含连续连字符)
 * 
 * 使用方式：
 * <Subdomain
 *   name="subdomain"
 *   label="子域名"
 *   typeobj={{
 *     type: 'subdomain',
 *     enabled: true
 *   }}
 * />
 */
var Subdomain = function Subdomain(props) {
  var _coreData$tenant;
  var propsOnBlur = props.onBlur,
    propsOnChange = props.onChange,
    _props$rootDomain = props.rootDomain,
    rootDomain = _props$rootDomain === void 0 ? 'xzero' : _props$rootDomain,
    customDomain = props.customDomain,
    value = props.value,
    tenantId = props.tenantId,
    fieldKey = props.fieldKey,
    rest = _objectWithoutProperties(props, _excluded);

  // 1. 所有的 hooks 调用放在最前面
  var _useDataSource = useDataSource(),
    __designMode = _useDataSource.__designMode;
  var context = useEngineContext();
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    subdomain = _useState2[0],
    setSubdomain = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    suffix = _useState4[0],
    setSuffix = _useState4[1];

  // 2. 获取 coreData
  var coreData = useMemo(function () {
    var _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3, _context$appHelper$ut4, _context$appHelper$ut5, _context$appHelper$ut6, _context$appHelper$ut7, _context$appHelper$ut8;
    return (_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 ? void 0 : (_context$appHelper$ut2 = _context$appHelper$ut.getApp) === null || _context$appHelper$ut2 === void 0 ? void 0 : (_context$appHelper$ut3 = _context$appHelper$ut2.call(_context$appHelper$ut)) === null || _context$appHelper$ut3 === void 0 ? void 0 : (_context$appHelper$ut4 = _context$appHelper$ut3.data) === null || _context$appHelper$ut4 === void 0 ? void 0 : (_context$appHelper$ut5 = _context$appHelper$ut4.store) === null || _context$appHelper$ut5 === void 0 ? void 0 : (_context$appHelper$ut6 = _context$appHelper$ut5.getStore) === null || _context$appHelper$ut6 === void 0 ? void 0 : (_context$appHelper$ut7 = _context$appHelper$ut6.call(_context$appHelper$ut5)) === null || _context$appHelper$ut7 === void 0 ? void 0 : (_context$appHelper$ut8 = _context$appHelper$ut7.getDataByModel) === null || _context$appHelper$ut8 === void 0 ? void 0 : _context$appHelper$ut8.call(_context$appHelper$ut7, 'core', 'core');
  }, [context]);
  // 3. 获取 tenantData
  var tenantData = useTenantData(rootDomain, coreData === null || coreData === void 0 ? void 0 : (_coreData$tenant = coreData.tenant) === null || _coreData$tenant === void 0 ? void 0 : _coreData$tenant.id);

  // 4. parseExternalValue 函数
  var parseExternalValue = function parseExternalValue(val) {
    // 如果值为空或只有空格或只有点号，返回默认值
    if (!val || !val.trim() || val.trim() === '.') {
      return {
        subdomain: '',
        suffix: suffixEmpty()
      };
    }
    try {
      // 将连续的点替换为单个点
      var normalizedVal = val.replace(/\.+/g, '.');
      var parts = normalizedVal.split('.');

      // 如果第一部分为空（以点号开头），且有后续部分
      if (parts[0] === '' && parts.length > 1) {
        return {
          subdomain: '',
          suffix: ".".concat(parts.slice(1).join('.'))
        };
      }

      // 如果只有一个部分，作为子域名
      if (parts.length === 1) {
        return {
          subdomain: parts[0].trim(),
          suffix: suffixEmpty()
        };
      }

      // 有多个部分，第一个作为子域名，其余作为后缀
      return {
        subdomain: parts[0].trim(),
        suffix: ".".concat(parts.slice(1).join('.'))
      };
    } catch (error) {
      console.error('Error parsing value:', error);
      return {
        subdomain: '',
        suffix: suffixEmpty()
      };
    }
  };

  // 5. 处理 value 和 domain 变化
  useEffect(function () {
    try {
      if (value) {
        var _parseExternalValue = parseExternalValue(value),
          newSubdomain = _parseExternalValue.subdomain,
          newSuffix = _parseExternalValue.suffix;
        setSubdomain(newSubdomain);
        setSuffix(newSuffix);
      } else {
        var _newSuffix = '';
        switch (rootDomain) {
          case 'xzero':
            _newSuffix = coreData !== null && coreData !== void 0 && coreData.tenant_domain ? ".".concat(coreData.tenant_domain) : suffixEmpty();
            break;
          case 'saas':
            _newSuffix = tenantData ? ".".concat(tenantData['saas.domain']) : suffixEmpty();
            break;
          case 'custom':
            if (customDomain) {
              var normalizedDomain = customDomain.replace(/\.+/g, '.');
              _newSuffix = normalizedDomain.startsWith('.') ? normalizedDomain : ".".concat(normalizedDomain);
            } else {
              _newSuffix = suffixEmpty();
            }
            break;
          default:
            _newSuffix = suffixEmpty();
        }
        setSuffix(_newSuffix);
      }
    } catch (error) {
      console.error('Error updating domain:', error);
      setSuffix(suffixEmpty());
    }
  }, [value, rootDomain, customDomain, tenantData, coreData]);

  // 6. 处理输入变化
  var handleChange = useCallback(function (e) {
    try {
      var inputValue = e.target.value.toLowerCase();
      var _parseExternalValue2 = parseExternalValue(inputValue),
        newSubdomain = _parseExternalValue2.subdomain;
      setSubdomain(newSubdomain);
      // 当输入为空时，传递空字符串而不是带后缀的值
      propsOnChange === null || propsOnChange === void 0 ? void 0 : propsOnChange(newSubdomain ? newSubdomain + suffix : '');
    } catch (error) {
      console.error('Error handling change:', error);
    }
  }, [suffix, propsOnChange, parseExternalValue]);

  // 7. 处理失焦
  var onBlur = useCallback(function (e) {
    try {
      propsOnBlur === null || propsOnBlur === void 0 ? void 0 : propsOnBlur(e);
      // 当输入为空时，传递空字符串而不是带后缀的值
      propsOnChange === null || propsOnChange === void 0 ? void 0 : propsOnChange(subdomain ? subdomain + suffix : '');
    } catch (error) {
      console.error('Error handling blur:', error);
    }
  }, [propsOnBlur, propsOnChange, subdomain, suffix]);
  var suffixEmpty = function suffixEmpty() {
    if (__designMode === 'design') {
      return '.root-domain.example';
    } else {
      return 'error';
    }
  };
  return /*#__PURE__*/React.createElement(AntInput, _extends({}, rest, {
    value: subdomain,
    onChange: handleChange,
    onBlur: onBlur,
    addonAfter: suffix
  }));
};

// 使用 withMode 高阶组件包装 Subdomain 组件
var SubdomainlWithMode = withMode(Subdomain, ReadPretty);
export default SubdomainlWithMode; // 导出组件