function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
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 _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(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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, isNumber, isString } from '@pisell/utils';
import classNames from 'classnames';
import { parsePhoneNumberFromString, isValidPhoneNumber } 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 "./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'), '.');
};

/**
 * @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 ? void 0 : (_field$uiSchema = field.uiSchema) === null || _field$uiSchema === void 0 ? void 0 : _field$uiSchema.title) || propsName;

    // 模式优先级：外部传入 mode > 全局模式
    var effectiveMode = propsRenderMode || globalRenderMode;
    var renderComponent = useMemo(function () {
      var _overlayProps$innerPr;
      // 使用renderMode属性，避免和组件mode冲突
      return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, otherProps, {
        mode: propsMode,
        renderMode: effectiveMode
      }, overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.innerProps, {
        style: _objectSpread(_objectSpread({}, innerStyle || {}), (overlayProps === null || overlayProps === void 0 ? void 0 : (_overlayProps$innerPr = overlayProps.innerProps) === null || _overlayProps$innerPr === void 0 ? void 0 : _overlayProps$innerPr.style) || {}),
        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]);
    var isDesignMode = __designMode === 'design';
    var isHidden = effectiveMode === 'hidden';

    // 如果name是字符串，并且包含.，则将name转换为数组 否则提交时会转换为对象
    var name = isString(propsName) && propsName.includes('.') ? [propsName] : propsName;
    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) {
      if (typeobj.type === 'email') {
        rules.push(_objectSpread(_objectSpread({}, typeobj), {}, {
          message: typeobj.message || getText('pisell-data-source-form-email-message')
        }));
      }
      if (typeobj.type === 'url' && typeobj.enabled) {
        rules.push(_objectSpread(_objectSpread({}, typeobj), {}, {
          message: typeobj.message || getText('pisell-data-source-form-url-message')
        }));
      }
      if (typeobj.type === 'phone' && typeobj.enabled) {
        rules.push({
          validator: function validator(_, value) {
            var _parsePhoneNumberFrom;
            return isValidPhoneNumber(value) && (_parsePhoneNumberFrom = parsePhoneNumberFromString(value)) !== null && _parsePhoneNumberFrom !== void 0 && _parsePhoneNumberFrom.isValid() ? Promise.resolve() : Promise.reject(new Error(typeobj.message || getText('pisell-data-source-form-phone-message')));
          }
        });
      }
    }
    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]);
    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
      // validator={validator}
      ,
      validateTrigger: validateTrigger,
      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'
      })
    }, overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps), renderComponent);
  };
};
export var withDataSource = function withDataSource(WrappedComponent) {
  return function (props) {
    var dataSource = props.dataSource;
    return /*#__PURE__*/React.createElement(DataSourceProvider, {
      dataSource: dataSource
    }, /*#__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;
    var _useDataSource2 = useDataSource(),
      list = _useDataSource2.list;
    useEffect(function () {
      if (optionSourceType === 'api') {
        list.run({
          page: 1,
          pageSize: 200
        });
      }
    }, []);
    var options = useMemo(function () {
      var _list$data, _list$data$data;
      if (optionSourceType !== 'api') {
        return propsOptions;
      }
      return (((_list$data = list.data) === null || _list$data === void 0 ? void 0 : (_list$data$data = _list$data.data) === null || _list$data$data === void 0 ? void 0 : _list$data$data.map(function (item) {
        return {
          label: translationOriginal(item[labelField]),
          value: item[valueField]
        };
      })) || []).sort(function (a, b) {
        return a.label.localeCompare(b.label);
      });
    }, [propsOptions, optionSourceType, list === null || list === void 0 ? 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)) {
    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];
}