import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 _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 _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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import classNames from 'classnames';
import React, { createContext, createElement, forwardRef, useContext, useEffect, useMemo, useState, Children, cloneElement } from "react";
import { Text } from "@alifd/meet-react-component-one";
import Icon from '../icon';
import List from '../list/index';
import { isString, isUndef } from '../utils';
import { useGuid } from '../utils/hooks';
import View from '../view';
import Context from './context';
import { getValidationRules } from './utils';
export var FormItemContext = /*#__PURE__*/createContext({
  isInsideForm: false,
  labelAlign: 'top',
  validateState: 'normal',
  labelTextAlign: 'left',
  contentAlign: 'left',
  hasFeedback: true,
  size: 'medium'
});

var FormItem = function FormItem(props, ref) {
  var _classNames, _classNames3, _classNames5;

  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      label = props.label,
      labelWidthProp = props.labelWidth,
      labelAlignProp = props.labelAlign,
      labelTextAlignProp = props.labelTextAlign,
      contentAlignProp = props.contentAlign,
      helpProp = props.help,
      extra = props.extra,
      className = props.className,
      style = props.style,
      children = props.children,
      isPreviewProp = props.isPreview,
      renderPreview = props.renderPreview,
      validateStateProp = props.validateState,
      _props$hasFeedback = props.hasFeedback,
      hasFeedback = _props$hasFeedback === void 0 ? false : _props$hasFeedback,
      _props$embedded = props.embedded,
      embedded = _props$embedded === void 0 ? false : _props$embedded,
      previewClassNameProp = props.previewClassName,
      _props$previewStyle = props.previewStyle,
      previewStyle = _props$previewStyle === void 0 ? {} : _props$previewStyle,
      sizeProp = props.size,
      valuePropName = props.valuePropName,
      required = props.required,
      requiredMessage = props.requiredMessage,
      requiredTrigger = props.requiredTrigger,
      min = props.min,
      max = props.max,
      minmaxMessage = props.minmaxMessage,
      minmaxTrigger = props.minmaxTrigger,
      minLength = props.minLength,
      maxLength = props.maxLength,
      minmaxLengthMessage = props.minmaxLengthMessage,
      minmaxLengthTrigger = props.minmaxLengthTrigger,
      length = props.length,
      lengthMessage = props.lengthMessage,
      lengthTrigger = props.lengthTrigger,
      pattern = props.pattern,
      patternMessage = props.patternMessage,
      patternTrigger = props.patternTrigger,
      format = props.format,
      formatMessage = props.formatMessage,
      formatTrigger = props.formatTrigger,
      validator = props.validator,
      validatorTrigger = props.validatorTrigger;

  var _useContext = useContext(Context),
      contextLabelAlign = _useContext.labelAlign,
      contextLabelWidth = _useContext.labelWidth,
      contextLabelTextAlign = _useContext.labelTextAlign,
      useLabelForErrorMessage = _useContext.useLabelForErrorMessage,
      contextContentAlign = _useContext.contentAlign,
      form = _useContext.form,
      field = _useContext.field,
      sizeContext = _useContext.size,
      contextIsPreview = _useContext.isPreview;

  var itemId = useGuid('form-item-');
  var size = sizeProp || sizeContext;
  var valueNames = [];
  var validateName;

  if (label && useLabelForErrorMessage) {
    validateName = isString(label) ? label : label.toString();
  } else {
    validateName = valueNames.join(' ');
  }

  var _useState = useState(validateStateProp || 'normal'),
      _useState2 = _slicedToArray(_useState, 2),
      validateStateInner = _useState2[0],
      setValidateState = _useState2[1];

  var validateState = 'validateState' in props ? validateStateProp || 'normal' : validateStateInner;

  var _useState3 = useState(''),
      _useState4 = _slicedToArray(_useState3, 2),
      error = _useState4[0],
      setError = _useState4[1];

  var rules = useMemo(function () {
    return getValidationRules(validateName, props);
  }, [required, requiredMessage, requiredTrigger, min, max, minmaxMessage, minmaxTrigger, minLength, maxLength, minmaxLengthMessage, minmaxLengthTrigger, length, lengthMessage, lengthTrigger, pattern, patternMessage, patternTrigger, format, formatMessage, formatTrigger, validator, validatorTrigger]);
  var clsPrefix = "".concat(prefix, "form-item");
  var previewClassName = classNames(previewClassNameProp, "".concat(clsPrefix, "-input"), "".concat(clsPrefix, "-input--preview-").concat(size));
  var isPreview = !isUndef(isPreviewProp) ? isPreviewProp : contextIsPreview;
  var labelAlign = labelAlignProp || contextLabelAlign;

  if (labelAlign === 'left') {
    labelAlign = 'inset';
  }

  var labelWidth = labelWidthProp || contextLabelWidth || 'auto';
  var contentAlign = contentAlignProp || contextContentAlign || 'left';
  var labelTextAlign = labelTextAlignProp || contextLabelTextAlign || 'left';
  var help = helpProp;

  if (!help && validateState === 'error') {
    help = error;
  }

  var hasError = validateState === 'error';
  var hasHelp = !!help;
  var isInset = labelAlign === 'inset';
  useEffect(function () {
    if (validateStateProp && validateStateProp !== validateState) {
      setValidateState(validateStateProp);
    }
  }, [validateState, validateStateProp]);

  var getValidateResult = function getValidateResult() {
    if (rules.length === 0) {
      if (validateState !== 'normal') {
        setValidateState('normal');
      }

      return;
    }

    if (!('validateState' in props) && field) {
      var errors = [];
      Object.values(field.getErrors(valueNames)).forEach(function (err) {
        if (err && Array.isArray(err) && err.length > 0) {
          err.forEach(function (it) {
            return errors.push(it);
          });
        }
      });

      if (errors.length > 0) {
        if (validateState !== 'error') {
          setValidateState('error');
        }

        if (errors[0] !== error) {
          setError(errors[0]);
        }
      } else if (validateState !== 'success' && validateState !== 'normal') {
        setValidateState('success');
      }
    }
  };

  useEffect(function () {
    if (form) {
      return form.onValidate(getValidateResult);
    }
  }, []);
  useEffect(function () {
    return getValidateResult();
  });
  var newChildren = Children.map(children, function (child, index) {
    if (!field) {
      return child;
    }

    var valueName = valuePropName;

    if (!valueName) {
      if (child.type && child.type.valueName) {
        valueName = child.type.valueName;
      } else if ('checked' in child.props || 'defaultChecked' in child.props) {
        valueName = 'checked';
      } else {
        valueName = 'value';
      }
    }

    if ('name' in child.props) {
      var name = child.props.name;
      valueNames.push(name);

      if (form && form.mapNameToGuid) {
        form.mapNameToGuid[name] = itemId;
      }

      if (!('data-meta' in child.props)) {
        var init = field.init;
        var el = cloneElement(child, Object.assign(Object.assign(Object.assign({}, child.props), init(name, {
          valueName: valueName,
          rules: rules,
          props: Object.assign(Object.assign({}, child.props), {
            ref: child.ref
          })
        }, child.props)), {
          labelAlign: labelAlign,
          size: size,
          key: child.key || name || index
        }));
        return el;
      }
    }

    return child;
  });
  var previewElement = null;

  if (isPreview && field && renderPreview !== false) {
    var values = Object.values(field.getValues(valueNames));
    previewElement = /*#__PURE__*/React.createElement(View, {
      className: previewClassName,
      style: __rpx2vw__(Object.assign(Object.assign({}, previewStyle), {
        textAlign: contentAlign
      }))
    }, renderPreview ? renderPreview.apply(void 0, _toConsumableArray(values)) : values.join(','));
  }

  return /*#__PURE__*/React.createElement(List.Item, {
    id: itemId,
    className: classNames(clsPrefix, (_classNames = {}, _defineProperty(_classNames, "".concat(clsPrefix, "--inset"), isInset), _defineProperty(_classNames, "".concat(clsPrefix, "--error"), hasError), _defineProperty(_classNames, "".concat(clsPrefix, "--help"), hasHelp), _classNames), className),
    style: __rpx2vw__(style)
  }, /*#__PURE__*/React.createElement(List.ItemContent, null, /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-container"), _defineProperty({}, "".concat(clsPrefix, "-container--inset"), isInset))
  }, !embedded && label ? /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-label-container"), (_classNames3 = {}, _defineProperty(_classNames3, "".concat(clsPrefix, "-label-container--").concat(size), !isInset), _defineProperty(_classNames3, "".concat(clsPrefix, "-label-container--inset"), isInset), _defineProperty(_classNames3, "".concat(clsPrefix, "-label-container--right"), isInset && labelTextAlign === 'right'), _classNames3)),
    style: __rpx2vw__({
      width: labelWidth,
      flexShrink: 0
    })
  }, isInset && required && !isPreview ? /*#__PURE__*/React.createElement(Icon, {
    name: "asterisk",
    className: classNames("".concat(clsPrefix, "-required"), "".concat(clsPrefix, "-required--inset-").concat(size), _defineProperty({}, "".concat(clsPrefix, "-required--inset"), labelTextAlign !== 'right'))
  }) : null, isString(label) ? /*#__PURE__*/React.createElement(Text, {
    className: classNames("".concat(clsPrefix, "-label"), "".concat(clsPrefix, "-label--").concat(size), (_classNames5 = {}, _defineProperty(_classNames5, "".concat(clsPrefix, "-label--inset"), isInset), _defineProperty(_classNames5, "".concat(clsPrefix, "-label--inset--").concat(size), isInset), _defineProperty(_classNames5, "".concat(clsPrefix, "-label--error"), hasError), _classNames5))
  }, label) : label, !isInset && required && !isPreview ? /*#__PURE__*/React.createElement(Icon, {
    name: "asterisk",
    className: "".concat(clsPrefix, "-required ").concat(clsPrefix, "-required--").concat(size)
  }) : null) : null, /*#__PURE__*/React.createElement(FormItemContext.Provider, {
    value: {
      isInsideForm: true,
      labelAlign: labelAlign,
      labelTextAlign: labelTextAlign,
      validateState: validateState,
      hasFeedback: hasFeedback,
      contentAlign: contentAlign,
      size: size
    }
  }, previewElement, /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-input"), "".concat(clsPrefix, "-input--").concat(contentAlign)),
    style: __rpx2vw__({
      display: previewElement ? 'none' : 'flex'
    })
  }, newChildren))), /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-help"), "".concat(clsPrefix, "-help--").concat(contentAlign), "".concat(clsPrefix, "-help--").concat(hasError ? 'error' : 'help'))
  }, help ? /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-help-text"), "".concat(clsPrefix, "-help-text--").concat(size))
  }, help) : null, extra && /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-help-extra"), "".concat(clsPrefix, "-help-text--").concat(size))
  }, extra))));
};

export default /*#__PURE__*/forwardRef(FormItem);