"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _react = _interopRequireDefault(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

var _context = require("../config-provider/context");

var _grid = _interopRequireDefault(require("../grid"));

var _tooltip = _interopRequireDefault(require("../tooltip"));

var _popover = _interopRequireDefault(require("../popover"));

var _icon = _interopRequireDefault(require("../icon"));

var _rcFieldForm = require("../components/rc-field-form");

var _context2 = require("./context");

var _util = require("./util");

var _useFrameState3 = _interopRequireDefault(require("./hooks/useFrameState"));

var Row = _grid.default.Row,
    Col = _grid.default.Col;
var QuestionFill = _icon.default.QuestionFill;
var NAME_SPLIT = '_SPLIT_';

var FormItem = function FormItem(props) {
  var customPrefixCls = props.prefixCls,
      children = props.children,
      labelName = props.label,
      itemCenter = props.itemCenter,
      labelWidth = props.labelWidth,
      required = props.required,
      tips = props.tips,
      trigger = props.trigger,
      name = props.name,
      rules = props.rules,
      shouldUpdate = props.shouldUpdate,
      dependencies = props.dependencies,
      validateTrigger = props.validateTrigger,
      htmlFor = props.htmlFor,
      noStyle = props.noStyle,
      labelCol = props.labelCol,
      wrapperCol = props.wrapperCol,
      fieldKey = props.fieldKey,
      tooltip = props.tooltip,
      popover = props.popover,
      className = props.className,
      style = props.style,
      extra = props.extra,
      messageVariables = props.messageVariables,
      rightExtra = props.rightExtra,
      reset = (0, _objectWithoutProperties2.default)(props, ["prefixCls", "children", "label", "itemCenter", "labelWidth", "required", "tips", "trigger", "name", "rules", "shouldUpdate", "dependencies", "validateTrigger", "htmlFor", "noStyle", "labelCol", "wrapperCol", "fieldKey", "tooltip", "popover", "className", "style", "extra", "messageVariables", "rightExtra"]);

  var _React$useContext = _react.default.useContext(_context.ConfigContext),
      getPrefixClassName = _React$useContext.getPrefixClassName;

  var _React$useContext2 = _react.default.useContext(_context2.FormItemContext),
      updateItemErrors = _React$useContext2.updateItemErrors;

  var formContext = _react.default.useContext(_context2.FormContext);

  var formName = formContext.name,
      contextLabelCol = formContext.labelCol,
      contextWrapperCol = formContext.wrapperCol,
      disabled = formContext.disabled,
      layout = formContext.layout;

  var _useFrameState = (0, _useFrameState3.default)({}),
      _useFrameState2 = (0, _slicedToArray2.default)(_useFrameState, 2),
      inlineErrors = _useFrameState2[0],
      setInlineErrors = _useFrameState2[1];

  var nameRef = _react.default.useRef([]);

  var prefixCls = getPrefixClassName('form-item', customPrefixCls);
  var isRenderProps = typeof children === 'function';
  var nameIsExit = name !== undefined && name !== null;
  var updateChildItemErrors = noStyle ? updateItemErrors : function (subName, subErrors, originSubName) {
    setInlineErrors(function () {
      var prevInlineErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      // Clean up origin error when name changed
      if (originSubName !== subName) {
        delete prevInlineErrors[originSubName];
      }

      if (!(0, _isEqual.default)(prevInlineErrors[subName], subErrors)) {
        return (0, _objectSpread3.default)((0, _objectSpread3.default)({}, prevInlineErrors), {}, (0, _defineProperty2.default)({}, subName, subErrors));
      }

      return prevInlineErrors;
    });
  };

  var renderTooltip = function renderTooltip() {
    var defaultIcon = /*#__PURE__*/_react.default.createElement(QuestionFill, null);

    if (!tooltip) return null;
    /* eslint-disable no-unneeded-ternary */

    if ((0, _typeof2.default)(tooltip) === 'object' && ! /*#__PURE__*/_react.default.isValidElement(tooltip)) {
      var icon = tooltip.icon,
          resetToolTipProps = (0, _objectWithoutProperties2.default)(tooltip, ["icon"]);
      return /*#__PURE__*/_react.default.createElement(_tooltip.default, Object.assign({}, resetToolTipProps), icon ? icon : defaultIcon);
    }

    return /*#__PURE__*/_react.default.createElement(_tooltip.default, {
      title: tooltip
    }, defaultIcon);
  };

  var renderPopover = function renderPopover() {
    var defaultIcon = /*#__PURE__*/_react.default.createElement(QuestionFill, null);

    if (!popover) return null;
    /* eslint-disable no-unneeded-ternary */

    if ((0, _typeof2.default)(popover) === 'object' && ! /*#__PURE__*/_react.default.isValidElement(popover)) {
      var icon = popover.icon,
          resetPopoverProps = (0, _objectWithoutProperties2.default)(popover, ["icon"]);
      return /*#__PURE__*/_react.default.createElement(_popover.default, Object.assign({}, resetPopoverProps), icon ? icon : defaultIcon);
    }

    return /*#__PURE__*/_react.default.createElement(_popover.default, {
      title: popover
    }, defaultIcon);
  };

  var renderRowItem = function renderRowItem(childrenWithNewProps, isRequired, meta, fieldItemName) {
    var _classNames;

    if (noStyle) return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, childrenWithNewProps);
    var endLabelCol = labelCol || contextLabelCol || {};
    var endWrapperCol = wrapperCol || contextWrapperCol || {};
    var subErrorList = [];
    Object.keys(inlineErrors).forEach(function (subName) {
      subErrorList = [].concat((0, _toConsumableArray2.default)(subErrorList), (0, _toConsumableArray2.default)(inlineErrors[subName] || []));
    });
    var mergedErrors; // if (help !== undefined && help !== null) {
    //   mergedErrors = toArray(help);
    // } else {

    mergedErrors = meta ? meta.errors : [];
    mergedErrors = [].concat((0, _toConsumableArray2.default)(mergedErrors), (0, _toConsumableArray2.default)(subErrorList)); // }

    var endFormItemCls = (0, _classnames.default)((_classNames = {}, (0, _defineProperty2.default)(_classNames, prefixCls, true), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-error"), mergedErrors.length > 0), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-validating"), meta === null || meta === void 0 ? void 0 : meta.validating), (0, _defineProperty2.default)(_classNames, "".concat(className), !!className), _classNames));
    var labelColClass = (0, _classnames.default)("".concat(prefixCls, "-label"), JSON.stringify(endLabelCol) === '{}' && "".concat(prefixCls, "-label-normal"), (0, _defineProperty2.default)({}, "".concat(prefixCls, "-no-centered"), !itemCenter));
    var controllCls = (0, _classnames.default)("".concat(prefixCls, "-controll"), (0, _defineProperty2.default)({}, "".concat(prefixCls, "-no-centered"), !itemCenter));
    var controllChild = (0, _classnames.default)("".concat(prefixCls, "-controll-content-child"), {
      'has-rightExtra': rightExtra
    });
    var rightExtraCls = (0, _classnames.default)("".concat(prefixCls, "-rightExtra"), (0, _defineProperty2.default)({}, "".concat(prefixCls, "-no-centered"), !itemCenter));
    var labeExtraCls = (0, _classnames.default)((0, _defineProperty2.default)({}, "".concat(prefixCls, "-label-required"), isRequired), "".concat(prefixCls, "-label-extra"));

    var childElement = /*#__PURE__*/_react.default.createElement(_context2.FormItemContext.Provider, {
      value: {
        updateItemErrors: updateChildItemErrors
      }
    }, childrenWithNewProps); // 去除子formItem的栅格布局属性


    var childFormContext = (0, _objectSpread3.default)({}, formContext);
    delete childFormContext.labelCol;
    delete childFormContext.wrapperCol;
    return /*#__PURE__*/_react.default.createElement(Row, {
      className: endFormItemCls,
      style: style
    }, labelName ? /*#__PURE__*/_react.default.createElement(Col, Object.assign({
      className: labelColClass
    }, endLabelCol), /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(prefixCls, "-label-content"),
      style: layout === 'vertical' && !isRequired ? {
        paddingLeft: 0
      } : undefined
    }, /*#__PURE__*/_react.default.createElement("label", {
      style: {
        width: labelWidth
      },
      htmlFor: htmlFor
    }, labelName), /*#__PURE__*/_react.default.createElement("div", {
      className: labeExtraCls
    }, tooltip && renderTooltip(), popover && renderPopover()))) : null, /*#__PURE__*/_react.default.createElement(_context2.FormContext.Provider, {
      value: childFormContext
    }, /*#__PURE__*/_react.default.createElement(Col, Object.assign({
      className: controllCls
    }, endWrapperCol), /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(prefixCls, "-controll-content")
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: controllChild
    }, rightExtra ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(prefixCls, "-controll-element")
    }, childElement), /*#__PURE__*/_react.default.createElement("span", {
      className: rightExtraCls
    }, rightExtra)) : childElement)), mergedErrors.length > 0 ?
    /*#__PURE__*/

    /* eslint-disable react/no-array-index-key */
    _react.default.createElement(_react.default.Fragment, null, mergedErrors.map(function (error, index) {
      return /*#__PURE__*/_react.default.createElement("div", {
        key: index,
        className: "".concat(prefixCls, "-error-tips")
      }, error);
    })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, tips && /*#__PURE__*/_react.default.createElement("span", {
      className: "".concat(prefixCls, "-controll-tips")
    }, tips)), extra ? /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(prefixCls, "-controll-extra")
    }, extra) : null)));
  };

  var renderFieldChild = function renderFieldChild(control, meta, context) {
    var mergedName = (0, _util.toArray)(name).length && meta ? meta.name : [];
    var errors = meta.errors;

    if (noStyle) {
      var originErrorName = nameRef.current.join(NAME_SPLIT);
      nameRef.current = (0, _toConsumableArray2.default)(mergedName);

      if (fieldKey) {
        var fieldKeys = Array.isArray(fieldKey) ? fieldKey : [fieldKey];
        nameRef.current = [].concat((0, _toConsumableArray2.default)(mergedName.slice(0, -1)), (0, _toConsumableArray2.default)(fieldKeys));
      }

      updateItemErrors(nameRef.current.join(NAME_SPLIT), errors, originErrorName);
    }

    var isRequired = required !== undefined ? required : !!(rules && rules.some(function (rule) {
      if (rule && rule.required) {
        return true;
      }

      if (typeof rule === 'function') {
        return rule(context) && rule(context).required;
      }

      return false;
    }));
    var fieldItemName = "".concat(formName, "_").concat((0, _util.getFieldId)(meta.name));
    var childNode = children;

    if ( /*#__PURE__*/_react.default.isValidElement(children)) {
      var childProps = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, children.props), control);

      if (disabled) {
        childProps.disabled = disabled;
      }

      if (!childProps.id) {
        childProps.id = fieldItemName;
      }

      var triggers = new Set([].concat((0, _toConsumableArray2.default)((0, _util.toArray)(trigger)), (0, _toConsumableArray2.default)((0, _util.toArray)(validateTrigger))));
      triggers.forEach(function (eventName) {
        childProps[eventName] = function () {
          var _control$eventName, _children$props$event, _children$props;

          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          (_control$eventName = control[eventName]) === null || _control$eventName === void 0 ? void 0 : _control$eventName.call.apply(_control$eventName, [control].concat(args));
          (_children$props$event = (_children$props = children.props)[eventName]) === null || _children$props$event === void 0 ? void 0 : _children$props$event.call.apply(_children$props$event, [_children$props].concat(args));
        };
      });
      childNode = /*#__PURE__*/_react.default.cloneElement(children, childProps);
    } else if (isRenderProps && (shouldUpdate || dependencies) && !nameIsExit && typeof children === 'function') {
      childNode = children(context);
    }

    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, renderRowItem(childNode, isRequired, meta, fieldItemName));
  };

  if (!nameIsExit && !isRenderProps && !dependencies) {
    return renderRowItem(children, required);
  }

  var variables = {};

  if (typeof labelName === 'string') {
    variables.label = labelName;
  }

  if (messageVariables) {
    variables = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, variables), messageVariables);
  }

  return /*#__PURE__*/_react.default.createElement(_rcFieldForm.Field, Object.assign({
    rules: rules,
    name: name,
    trigger: trigger,
    validateTrigger: validateTrigger,
    messageVariables: variables,
    dependencies: dependencies,
    shouldUpdate: shouldUpdate
  }, reset), renderFieldChild);
};

FormItem.defaultProps = {
  itemCenter: true,
  trigger: 'onChange',
  validateTrigger: 'onChange'
};
FormItem.displayName = 'FormItem';
var _default = FormItem;
exports.default = _default;