var _excluded = ["renderMode", "value", "onChange"],
  _excluded2 = ["name", "label", "mode", "renderMode", "tooltip", "noStyle", "extra", "required", "requiredobj", "minLengthobj", "maxLengthobj", "typeobj", "maxobj", "minobj", "normalize", "getValueProps", "validator", "style", "validateTrigger", "__designMode", "labelCol", "hideLabel", "innerStyle"];
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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 _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 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 _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, { useEffect, useMemo } from 'react';
import { isArr, isFunction, isNumber, isString } from '@pisell/utils';
import classNames from 'classnames';
import { parsePhoneNumberFromString } from 'libphonenumber-js';
import { getText } from "../../../locales";
import Form from "../../form";
import useDataSource from "../hooks/useDataSource";
import useFormSetting from "./provider/hooks/useFormSetting";
import useJsonPrefixPath from "./provider/hooks/useJsonPrefixPath";
import DataSourceProvider from "../provider/dataSource/DataSourceProvider";
import useTranslationOriginal from "../../../hooks/useTranslationOriginal";
import useVariables from "../hooks/useVariables";
import "./style.less";
/**
 * @title: 增加renderMode属性
 * @description: 基于renderMode属性控制渲染模式
 * @return: *
 * @Author: shengjie.zuo
 * @Date: 2024-11-23 17:13:18
 */
export var withMode = function withMode(FieldComponent, ReadPrettyComponent, transformProps) {
  return function (_ref) {
    var _ref$renderMode = _ref.renderMode,
      renderMode = _ref$renderMode === void 0 ? 'edit' : _ref$renderMode,
      value = _ref.value,
      onChange = _ref.onChange,
      props = _objectWithoutProperties(_ref, _excluded);
    var transformedProps = (transformProps === null || transformProps === void 0 ? void 0 : transformProps(_objectSpread(_objectSpread({}, props), {}, {
      value: value,
      onChange: onChange,
      renderMode: renderMode
    }), renderMode)) || _objectSpread(_objectSpread({}, props), {}, {
      value: value,
      onChange: onChange,
      renderMode: renderMode
    });
    if (['view', 'tableView'].includes(renderMode) && ReadPrettyComponent) {
      return /*#__PURE__*/React.createElement(ReadPrettyComponent, transformedProps);
    }
    if (renderMode === 'disabled') {
      return /*#__PURE__*/React.createElement(FieldComponent, _extends({}, transformedProps, {
        disabled: true
      }));
    }
    return /*#__PURE__*/React.createElement(FieldComponent, transformedProps);
  };
};
var FORM_ITEM_SPLIT_CHAR = '__zsj__';

// 替换name中的.为FORM_ITEM_SPLIT_CHAR
export var formItemNameReplace = function formItemNameReplace(name) {
  return name.replace(/\./g, FORM_ITEM_SPLIT_CHAR);
};

// 替换name中的FORM_ITEM_SPLIT_CHAR为.
export var formItemNameReverse = function formItemNameReverse(name) {
  return name.replace(new RegExp(FORM_ITEM_SPLIT_CHAR, 'g'), '.');
};

// 验证域名
export var isValidDomain = function isValidDomain(value) {
  return /^(?!.*--)[A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9](\.[A-Za-z]{2,})+$/.test(value);
};

/**
 * @title: 追加formItem层
 * @description:
 * @return: *
 * @Author: shengjie.zuo
 * @Date: 2024-11-23 17:14:25
 */
export var withFormItem = function withFormItem(WrappedComponent, overlayProps) {
  return function (_ref2) {
    var _field$uiSchema;
    var propsName = _ref2.name,
      propsLabel = _ref2.label,
      propsMode = _ref2.mode,
      propsRenderMode = _ref2.renderMode,
      tooltip = _ref2.tooltip,
      noStyle = _ref2.noStyle,
      extra = _ref2.extra,
      required = _ref2.required,
      requiredobj = _ref2.requiredobj,
      minLengthobj = _ref2.minLengthobj,
      maxLengthobj = _ref2.maxLengthobj,
      typeobj = _ref2.typeobj,
      maxobj = _ref2.maxobj,
      minobj = _ref2.minobj,
      normalize = _ref2.normalize,
      getValueProps = _ref2.getValueProps,
      _validator = _ref2.validator,
      style = _ref2.style,
      validateTrigger = _ref2.validateTrigger,
      __designMode = _ref2.__designMode,
      propsLabelCol = _ref2.labelCol,
      hideLabel = _ref2.hideLabel,
      innerStyle = _ref2.innerStyle,
      otherProps = _objectWithoutProperties(_ref2, _excluded2);
    var _useJsonPrefixPath = useJsonPrefixPath(),
      _useJsonPrefixPath$pa = _useJsonPrefixPath.path,
      prefixPath = _useJsonPrefixPath$pa === void 0 ? [] : _useJsonPrefixPath$pa;
    var _useDataSource = useDataSource(),
      dataSource = _useDataSource.dataSource;
    var _ref3 = dataSource || {},
      fields = _ref3.fields;
    var _useFormSetting = useFormSetting(),
      globalRenderMode = _useFormSetting.renderMode,
      size = _useFormSetting.size;
    var field = fields === null || fields === void 0 ? void 0 : fields.find(function (item) {
      return item.name === propsName;
    });

    // 优先级：外部传入 > schema 中的 title > 字段名
    var label = propsLabel || (field === null || field === void 0 || (_field$uiSchema = field.uiSchema) === null || _field$uiSchema === void 0 ? void 0 : _field$uiSchema.title) || propsName;

    // 模式优先级：外部传入 mode > 全局模式
    var effectiveMode = propsRenderMode || globalRenderMode;
    // 如果name是字符串，并且包含.，则将name转换为数组 否则提交时会转换为对象
    var name = isString(propsName) && propsName.includes('.') ? [propsName] : propsName;
    var renderComponent = useMemo(function () {
      var _overlayProps$innerPr;
      // 使用renderMode属性，避免和组件mode冲突
      return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.innerProps, otherProps, {
        mode: propsMode,
        renderMode: effectiveMode,
        style: _objectSpread(_objectSpread({}, (overlayProps === null || overlayProps === void 0 || (_overlayProps$innerPr = overlayProps.innerProps) === null || _overlayProps$innerPr === void 0 ? void 0 : _overlayProps$innerPr.style) || {}), innerStyle || {}),
        fieldKey: name,
        isVerification: typeobj === null || typeobj === void 0 ? void 0 : typeobj.enabled,
        size: size
      }));
    }, [effectiveMode, otherProps, propsMode, overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.innerProps, typeobj === null || typeobj === void 0 ? void 0 : typeobj.enabled, size, innerStyle, name]);
    var isDesignMode = __designMode === 'design';
    var isHidden = effectiveMode === 'hidden';
    var concatName = name !== undefined ? [].concat(_toConsumableArray(prefixPath), _toConsumableArray(toArr(name))) : undefined;
    var rules = [];
    if (requiredobj && requiredobj.required) {
      rules.push(_objectSpread(_objectSpread({}, requiredobj), {}, {
        message: requiredobj.message || getText('pisell-data-source-form-required-message')
      }));
    }
    if (typeobj && typeobj.enabled) {
      switch (typeobj.type) {
        case 'email':
          rules.push(_objectSpread(_objectSpread({}, typeobj), {}, {
            message: typeobj.message || getText('pisell-data-source-form-email-message')
          }));
          break;
        case 'pattern':
          rules.push(_objectSpread(_objectSpread({}, typeobj), {}, {
            pattern: new RegExp(typeobj.pattern),
            message: typeobj.message || getText('pisell-data-source-form-pattern-message')
          }));
          break;
        case 'phone':
          rules.push({
            validator: function validator(_, originValue) {
              var _value, _phone;
              var value = "";
              if (isString(originValue)) {
                value = originValue;
              } else if (originValue && 'phone' in originValue) {
                value = "".concat((originValue === null || originValue === void 0 ? void 0 : originValue.countryCallingCode) || "").concat(originValue.phone || "");
              }

              // 如果值为空或者只有空格，直接返回成功，不进行校验
              if (!((_value = value) !== null && _value !== void 0 && _value.trim())) {
                if ((requiredobj === null || requiredobj === void 0 ? void 0 : requiredobj.required) === false) {
                  return Promise.resolve();
                } else if (_typeof(originValue) == 'object') {
                  // 如果是object，存在phone和contryCallingCode都为空的场景，需要拦截
                  return Promise.reject(new Error(requiredobj.message || getText('pisell-data-source-form-required-message')));
                }
              }

              // 如果是object返回格式，非必填且phone为空，不进行校验
              if (typeof originValue !== 'string' && (requiredobj === null || requiredobj === void 0 ? void 0 : requiredobj.required) === false && (originValue === null || originValue === void 0 || (_phone = originValue.phone) === null || _phone === void 0 ? void 0 : _phone.trim()) === '') {
                return Promise.resolve();
              }
              try {
                // 清理输入值，移除空格、括号等字符
                var cleanedNumber = value.replace(/\s|\(|\)/g, '');
                // 使用 parsePhoneNumberFromString 验证 E.164 格式
                var parsedNumber = parsePhoneNumberFromString(cleanedNumber);
                if (!(parsedNumber !== null && parsedNumber !== void 0 && parsedNumber.isValid())) {
                  return Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-phone-message')));
                }
                return Promise.resolve();
              } catch (error) {
                return Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-phone-message')));
              }
            }
          });
          break;
        case 'mobile':
          rules.push({
            validator: function validator(_, originValue) {
              var _value2;
              var value = "";
              if (isString(originValue)) {
                value = originValue;
              } else if (originValue && 'phone' in originValue) {
                value = "".concat((originValue === null || originValue === void 0 ? void 0 : originValue.countryCallingCode) || "").concat(originValue.phone || "");
              }

              // 如果值为空或者只有空格，直接返回成功，不进行校验
              if (!((_value2 = value) !== null && _value2 !== void 0 && _value2.trim())) {
                return Promise.resolve();
              }
              try {
                // 清理输入值，移除空格和括号等
                var cleanedNumber = value.replace(/\s|\(|\)/g, '');

                // 如果超过15位，直接返回错误
                if (cleanedNumber.length > 15) {
                  return Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-mobile-message')));
                }

                // 根据号码前缀判断国家
                if (cleanedNumber.startsWith('+61')) {
                  // 澳大利亚手机号规则：
                  // 1. 以04开头必须是10位数字
                  // 2. 以4开头必须是9位数字
                  var numberWithoutPrefix = cleanedNumber.slice(3);
                  if (!/^(?:04\d{8}|4\d{8})$/.test(numberWithoutPrefix)) {
                    return Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-mobile-message')));
                  }
                } else if (cleanedNumber.startsWith('+86')) {
                  // 中国手机号规则
                  var _numberWithoutPrefix = cleanedNumber.slice(3);
                  if (!/^1[3-9]\d{9}$/.test(_numberWithoutPrefix)) {
                    return Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-mobile-message')));
                  }
                }
                return Promise.resolve();
              } catch (error) {
                // 如果解析出错，只验证长度
                var _cleanedNumber = value.replace(/\s|\(|\)/g, '');
                if (_cleanedNumber.length > 15) {
                  return Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-mobile-message')));
                }
                return Promise.resolve();
              }
            }
          });
          break;
        case 'url':
          rules.push(_objectSpread(_objectSpread({}, typeobj), {}, {
            message: typeobj.message || getText('pisell-data-source-form-url-message')
          }));
          break;
        case 'subdomain':
          rules.push({
            validator: function validator(_, value) {
              if (!value) return Promise.resolve();
              var subdomain = value.split('.')[0];
              if (!/^[a-z0-9-]+$/.test(subdomain)) {
                return Promise.reject(new Error(getText('subdomain-error-pattern')));
              }
              if (/^\d+$/.test(subdomain)) {
                return Promise.reject(new Error(getText('subdomain-error-numbers-only')));
              }
              if (subdomain.startsWith('-') || subdomain.endsWith('-')) {
                return Promise.reject(new Error(getText('subdomain-error-hyphen-ends')));
              }
              if (subdomain.includes('--')) {
                return Promise.reject(new Error(getText('subdomain-error-consecutive-hyphens')));
              }
              return Promise.resolve();
            }
          });
          break;
        case 'appIdentifier':
          rules.push({
            validator: function validator(_, value) {
              if (!value) return Promise.resolve();

              // 格式检查：只能包含小写字母、数字、连字符、点和下划线
              if (!/^[a-z0-9\-\._]+$/.test(value)) {
                return Promise.reject(new Error(getText('pisell-data-source-form-app-identifier-pattern')));
              }

              // 开头规则检查：必须以字母开头
              if (!/^[a-z]/.test(value)) {
                return Promise.reject(new Error(getText('pisell-data-source-form-app-identifier-start-with-letter')));
              }

              // 结尾规则检查：不能以连字符、点或下划线结尾
              if (/[\-\._]$/.test(value)) {
                return Promise.reject(new Error(getText('pisell-data-source-form-app-identifier-special-ends')));
              }

              // 连续特殊字符检查：不能使用连续的连字符、点或下划线
              if (/[\-]{2,}|[\.]{2,}|[\_]{2,}/.test(value)) {
                return Promise.reject(new Error(getText('pisell-data-source-form-app-identifier-consecutive-special')));
              }
              return Promise.resolve();
            }
          });
          break;
      }
    }
    if (maxLengthobj && maxLengthobj.enabled) {
      rules.push({
        // ...maxLengthobj,
        validator: function validator(_, value) {
          var length = 0;
          if (isString(value)) {
            length = value.length;
          } else if (isArr(value)) {
            length = value.length;
          } else if (isNumber(value)) {
            length = "".concat(value).length;
          }
          if (length > maxLengthobj.max) {
            return Promise.reject(new Error(maxLengthobj.message || getText('pisell-data-source-form-max-length-message')(maxLengthobj === null || maxLengthobj === void 0 ? void 0 : maxLengthobj.max)));
          }
          return Promise.resolve();
        }
      });
    }
    if (minLengthobj && minLengthobj.enabled) {
      rules.push({
        // ...minLengthobj,
        validator: function validator(_, value) {
          var length = 0;
          if (isString(value)) {
            length = value.length;
          } else if (isArr(value)) {
            length = value.length;
          } else if (isNumber(value)) {
            length = "".concat(value).length;
          }
          if (length < minLengthobj.min) {
            return Promise.reject(new Error(minLengthobj.message || getText('pisell-data-source-form-min-length-message')(minLengthobj === null || minLengthobj === void 0 ? void 0 : minLengthobj.min)));
          }
          return Promise.resolve();
        }
      });
    }
    if (maxobj && maxobj.enabled) {
      rules.push(_objectSpread(_objectSpread({}, maxobj), {}, {
        type: 'number',
        message: maxobj.message || getText('pisell-data-source-form-max-value-message')(maxobj === null || maxobj === void 0 ? void 0 : maxobj.max)
      }));
    }
    if (minobj && minobj.enabled) {
      rules.push(_objectSpread(_objectSpread({}, minobj), {}, {
        type: 'number',
        message: minobj.message || getText('pisell-data-source-form-min-value-message')(minobj === null || minobj === void 0 ? void 0 : minobj.min)
      }));
    }
    if (_validator) {
      rules.push({
        validator: function validator(_, value) {
          return _validator(value);
        }
      });
    }
    var labelCol = useMemo(function () {
      if (hideLabel) {
        return {
          span: 0
        };
      }
      return propsLabelCol;
    }, [hideLabel, propsLabelCol]);
    var otherFormItemProps = useMemo(function () {
      if (isFunction(overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps)) {
        return overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps(otherProps, {
          rules: rules
        });
      }
      return _objectSpread(_objectSpread(_objectSpread({}, otherProps || {}), (overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps) || {}), {}, {
        onChange: undefined
      });
    }, [overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps, otherProps]);
    return /*#__PURE__*/React.createElement(Form.Item, _extends({
      required: required,
      style: _objectSpread(_objectSpread({
        width: '100%'
      }, style), {}, {
        opacity: isDesignMode && isHidden ? '0.3' : 1
      }),
      name: concatName,
      label: label,
      tooltip: tooltip,
      noStyle: noStyle,
      extra: extra,
      hidden: isHidden && !isDesignMode,
      rules: rules,
      normalize: normalize,
      getValueProps: getValueProps,
      validateTrigger: validateTrigger || ['onChange', 'onBlur'],
      labelCol: labelCol,
      initialValue: otherProps === null || otherProps === void 0 ? void 0 : otherProps.defaultValue,
      className: classNames('pisell-data-source-form-item', {
        'pisell-data-source-form-item-view': effectiveMode === 'view'
      })
    }, otherFormItemProps), renderComponent);
  };
};
export var withDataSource = function withDataSource(WrappedComponent) {
  return function (props) {
    var dataSource = props.dataSource,
      extraParams = props.extraParams;
    return /*#__PURE__*/React.createElement(DataSourceProvider, {
      dataSource: dataSource,
      extraParams: {
        list: extraParams
      },
      requestOptions: {
        list: {
          cacheKey: "".concat(dataSource === null || dataSource === void 0 ? void 0 : dataSource.headerDataSource, "-").concat(dataSource === null || dataSource === void 0 ? void 0 : dataSource.name, "-").concat(dataSource === null || dataSource === void 0 ? void 0 : dataSource.tableName)
        }
      }
    }, /*#__PURE__*/React.createElement(WrappedComponent, props));
  };
};
export var withOptions = function withOptions(WrappedComponent) {
  return function (props) {
    var _list$data2;
    var translationOriginal = useTranslationOriginal();
    var propsOptions = props.options,
      optionSourceType = props.optionSourceType,
      labelField = props.labelField,
      valueField = props.valueField,
      extraParams = props.extraParams;
    var _useVariables = useVariables(),
      parseVariable = _useVariables.parseVariable;
    var _useDataSource2 = useDataSource(),
      list = _useDataSource2.list,
      getCurrentRecord = _useDataSource2.getCurrentRecord;
    var parseParams = useMemo(function () {
      var params = {};
      if (extraParams) {
        Object.keys(extraParams).forEach(function (key) {
          params[key] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(extraParams[key], {
            currentRecord: getCurrentRecord()
          });
        });
      }
      return params;
    }, [extraParams]);
    useEffect(function () {
      if (optionSourceType === 'api') {
        list.run(_objectSpread({
          page: 1,
          pageSize: 500
        }, parseParams));
      }
    }, []);
    var options = useMemo(function () {
      var _list$data, _list$data$filter;
      if (optionSourceType !== 'api') {
        return propsOptions;
      }
      return (((_list$data = list.data) === null || _list$data === void 0 || (_list$data = _list$data.data) === null || _list$data === void 0 || (_list$data$filter = _list$data.filter) === null || _list$data$filter === void 0 ? void 0 : _list$data$filter.call(_list$data, function (item) {
        return !['draft', 'inactive', 'disabled'].includes(item === null || item === void 0 ? void 0 : item.status);
      })) || []).map(function (item) {
        return {
          label: translationOriginal(item[labelField]),
          value: item[valueField]
        };
      }) || [];
    }, [propsOptions, optionSourceType, list === null || list === void 0 || (_list$data2 = list.data) === null || _list$data2 === void 0 ? void 0 : _list$data2.data]);
    return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, props, {
      options: options
    }));
  };
};

// 获取嵌套对象的值
export var getNestedValue = function getNestedValue(obj, path) {
  var keys = path.split('.');
  var value = obj;
  var _iterator = _createForOfIteratorHelper(keys),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var k = _step.value;
      if (!value) break;
      value = value[k];
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return value;
};

// 根据valueMap渲染value 用于ReadPretty组件 Select Radio Checkbox
export var renderValueWithMap = function renderValueWithMap(value, valueMap, renderMode) {
  var textStyle = renderMode === 'tableView' ? {
    fontSize: 14,
    fontWeight: 400
  } : {};
  if (isArr(value)) {
    return /*#__PURE__*/React.createElement("span", {
      className: "pisell-form-read-pretty-text"
    }, value.map(function (item, index) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
        key: item,
        className: "pisell-form-read-pretty-value",
        style: textStyle
      }, valueMap === null || valueMap === void 0 ? void 0 : valueMap[item]), index < value.length - 1 && ', ');
    }));
  } else if (isString(value) || isNumber(value)) {
    return /*#__PURE__*/React.createElement("span", {
      className: "pisell-form-read-pretty-text"
    }, /*#__PURE__*/React.createElement("span", {
      className: "pisell-form-read-pretty-value",
      style: textStyle
    }, (valueMap === null || valueMap === void 0 ? void 0 : valueMap[value]) || value));
  }
  return null;
};
export function toArr(str) {
  return Array.isArray(str) ? str : [str];
}
var systemFields = ['createdAt', 'updatedAt', 'createdBy', 'created_at', 'updated_at', 'deleted_at'];

// 提交时过滤系统字段
export var filterSystemFields = function filterSystemFields(params) {
  return Object.keys(params).reduce(function (acc, key) {
    if (!systemFields.includes(key)) {
      acc[key] = params[key];
    }
    return acc;
  }, {});
};

// 表单objvalue转换为数组 并且touched设置为false
export var transformFormObjToArrayWithUntouched = function transformFormObjToArrayWithUntouched(obj) {
  return Object.keys(obj).reduce(function (acc, key) {
    acc.push({
      name: key,
      value: obj[key],
      touched: false
    });
    return acc;
  }, []);
};

// 把表单中 touched设置为false
export var setFormFieldsUntouched = function setFormFieldsUntouched(form) {
  var fieldsErrorArray = form.getFieldsError();
  var fields = fieldsErrorArray.map(function (item) {
    return {
      name: item.name,
      value: form.getFieldValue(item.name),
      touched: false
    };
  });
  form.setFields(fields);
};