"use strict";

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

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _tslib = require("tslib");

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

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

var _mobxReact = require("mobx-react");

var _mobx = require("mobx");

var _isNumber = _interopRequireDefault(require("lodash/isNumber"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _defaultTo = _interopRequireDefault(require("lodash/defaultTo"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _raf = _interopRequireDefault(require("raf"));

var _Responsive = _interopRequireWildcard(require("../../../lib/responsive/Responsive"));

var _UnitConvertor = require("../../../lib/_util/UnitConvertor");

var _isFunction = _interopRequireDefault(require("lodash/isFunction"));

var _axios = _interopRequireDefault(require("../axios"));

var _autobind = _interopRequireDefault(require("../_util/autobind"));

var _isFragment = _interopRequireDefault(require("../_util/isFragment"));

var _FormField = require("../field/FormField");

var _FormContext = _interopRequireWildcard(require("./FormContext"));

var _DataSetComponent2 = _interopRequireDefault(require("../data-set/DataSetComponent"));

var _enum = require("./enum");

var _utils = require("./utils");

var _FormVirtualGroup = _interopRequireDefault(require("./FormVirtualGroup"));

var _enum2 = require("../data-set/enum");

var _Item = _interopRequireDefault(require("./Item"));

var _FormItemLabel = _interopRequireDefault(require("./FormItemLabel"));

var _ItemGroup = _interopRequireDefault(require("./ItemGroup"));

var _enum3 = require("../field/enum");

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

var _singleton = require("../tooltip/singleton");

var _excluded = ["children"],
    _excluded2 = ["rowSpan", "colSpan", "newLine", "className", "fieldClassName", "useColon", "requiredMarkAlign"];

/**
 * 表单name生成器
 */
var NameGen = /*#__PURE__*/_regenerator["default"].mark(function _callee(start) {
  return _regenerator["default"].wrap(function _callee$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          if (!true) {
            _context.next = 6;
            break;
          }

          start += 1;
          _context.next = 4;
          return "form-".concat(start);

        case 4:
          _context.next = 0;
          break;

        case 6:
        case "end":
          return _context.stop();
      }
    }
  }, _callee);
})(0);

var Form = /*#__PURE__*/function (_DataSetComponent) {
  (0, _inherits2["default"])(Form, _DataSetComponent);

  var _super = (0, _createSuper2["default"])(Form);

  function Form(props, context) {
    var _this;

    (0, _classCallCheck2["default"])(this, Form);
    _this = _super.call(this, props, context);
    _this.fields = [];
    _this.name = NameGen.next().value;
    _this.validating = false;
    _this.prepareForReport = {};
    (0, _mobx.runInAction)(function () {
      _this.responsiveItems = [];
    });
    return _this;
  }

  (0, _createClass2["default"])(Form, [{
    key: "axios",
    get: function get() {
      return this.observableProps.axios || this.getContextConfig('axios') || _axios["default"];
    }
  }, {
    key: "dataSet",
    get: function get() {
      var record = this.record;

      if (record) {
        return record.dataSet;
      }

      var observableProps = this.observableProps;

      if ('dataSet' in observableProps) {
        return observableProps.dataSet;
      }

      return observableProps.contextDataSet;
    }
  }, {
    key: "record",
    get: function get() {
      var observableProps = this.observableProps;

      if ('record' in observableProps) {
        return observableProps.record;
      }

      var dataSet = observableProps.dataSet,
          dataIndex = observableProps.dataIndex;

      if (dataSet) {
        if ((0, _isNumber["default"])(dataIndex)) {
          return dataSet.get(dataIndex);
        }

        return dataSet.current;
      }

      if ((0, _isNumber["default"])(dataIndex)) {
        var contextDataSet = observableProps.contextDataSet;

        if (contextDataSet) {
          return contextDataSet.get(dataIndex);
        }
      }

      return observableProps.contextRecord;
    }
  }, {
    key: "dataIndex",
    get: function get() {
      var _this$observableProps = this.observableProps,
          dataIndex = _this$observableProps.dataIndex,
          contextDataIndex = _this$observableProps.contextDataIndex;
      return (0, _defaultTo["default"])(dataIndex, contextDataIndex);
    }
  }, {
    key: "useColon",
    get: function get() {
      var useColon = this.observableProps.useColon;

      if (useColon !== undefined) {
        return useColon;
      }

      var configUseColon = this.getContextConfig('useColon');

      if (configUseColon !== undefined) {
        return configUseColon;
      }

      return false;
    }
  }, {
    key: "requiredMarkAlign",
    get: function get() {
      var requiredMarkAlign = this.observableProps.requiredMarkAlign;

      if ([_enum.RequiredMarkAlign.left, _enum.RequiredMarkAlign.right].includes(requiredMarkAlign)) {
        return requiredMarkAlign;
      }

      var configRequiredMarkAlign = this.getContextConfig('requiredMarkAlign');

      if ([_enum.RequiredMarkAlign.left, _enum.RequiredMarkAlign.right].includes(configRequiredMarkAlign)) {
        return configRequiredMarkAlign;
      }

      return _enum.RequiredMarkAlign.left;
    }
  }, {
    key: "excludeUseColonTagList",
    get: function get() {
      var excludeUseColonTagList = this.observableProps.excludeUseColonTagList;

      if (excludeUseColonTagList !== undefined) {
        return excludeUseColonTagList;
      }

      var configExcludeUseColonTagList = this.getContextConfig('excludeUseColonTagList');

      if (configExcludeUseColonTagList !== undefined) {
        return configExcludeUseColonTagList;
      }

      return _utils.defaultExcludeUseColonTag;
    }
  }, {
    key: "columns",
    get: function get() {
      var columns = this.observableProps.columns;

      if ((0, _isNumber["default"])(columns)) {
        return columns;
      }

      if (columns) {
        var responsiveColumns = this.responsiveItems[0];

        if (responsiveColumns) {
          return responsiveColumns;
        }
      }

      return _utils.defaultColumns;
    }
  }, {
    key: "labelWidth",
    get: function get() {
      var labelWidth = this.observableProps.labelWidth;

      if (labelWidth === 'auto') {
        return labelWidth;
      }

      if ((0, _isNumber["default"])(labelWidth) || (0, _mobx.isArrayLike)(labelWidth) && !(0, _Responsive.hasBreakPointMap)(labelWidth)) {
        return labelWidth;
      }

      if (labelWidth) {
        var responsiveWidth = this.responsiveItems[1];

        if (responsiveWidth !== undefined) {
          return responsiveWidth;
        }
      }

      return _utils.defaultLabelWidth;
    }
  }, {
    key: "labelAlign",
    get: function get() {
      var labelAlign = this.observableProps.labelAlign;

      if ((0, _isString["default"])(labelAlign)) {
        return labelAlign;
      }

      if (labelAlign) {
        var responsiveAlign = this.responsiveItems[2];

        if (responsiveAlign) {
          return responsiveAlign;
        }
      }

      return this.labelLayout === _enum.LabelLayout.vertical ? _enum.LabelAlign.left : this.getContextConfig('labelAlign') || _enum.LabelAlign.right;
    }
  }, {
    key: "labelLayout",
    get: function get() {
      var labelLayout = this.observableProps.labelLayout;

      if ((0, _isString["default"])(labelLayout)) {
        return labelLayout;
      }

      if (labelLayout) {
        var responsiveLabelLayout = this.responsiveItems[3];

        if (responsiveLabelLayout) {
          return responsiveLabelLayout;
        }
      }

      return this.getContextConfig('labelLayout') || _enum.LabelLayout.horizontal;
    }
  }, {
    key: "labelTooltip",
    get: function get() {
      var labelTooltip = this.observableProps.labelTooltip;

      if (labelTooltip) {
        return labelTooltip;
      }

      var getTooltip = this.context.getTooltip;
      return getTooltip('label');
    }
  }, {
    key: "readOnly",
    get: function get() {
      return this.observableProps.readOnly;
    }
  }, {
    key: "pristine",
    get: function get() {
      return this.observableProps.pristine;
    }
  }, {
    key: "fieldHighlightRenderer",
    get: function get() {
      return this.observableProps.fieldHighlightRenderer;
    }
  }, {
    key: "showValidation",
    get: function get() {
      return this.observableProps.showValidation;
    }
  }, {
    key: "showHelp",
    get: function get() {
      var showHelp = this.observableProps.showHelp;

      if ((0, _isString["default"])(showHelp)) {
        return showHelp;
      }

      return this.getContextConfig('showHelp') || _enum3.ShowHelp.newLine;
    }
  }, {
    key: "separateSpacing",
    get: function get() {
      var separateSpacing = this.observableProps.separateSpacing;

      if (separateSpacing) {
        var _normalizeSeparateSpa = (0, _utils.normalizeSeparateSpacing)(separateSpacing),
            _normalizeSeparateSpa2 = _normalizeSeparateSpa.width,
            width = _normalizeSeparateSpa2 === void 0 ? 0 : _normalizeSeparateSpa2,
            _normalizeSeparateSpa3 = _normalizeSeparateSpa.height,
            height = _normalizeSeparateSpa3 === void 0 ? 0 : _normalizeSeparateSpa3;

        if (width || height) {
          return {
            width: width,
            height: height
          };
        }

        if ((0, _Responsive.isBreakPointMap)(separateSpacing)) {
          var responsiveSeparateSpacing = this.responsiveItems[4];

          if (responsiveSeparateSpacing) {
            var _responsiveSeparateSp = responsiveSeparateSpacing.width,
                _width = _responsiveSeparateSp === void 0 ? 0 : _responsiveSeparateSp,
                _responsiveSeparateSp2 = responsiveSeparateSpacing.height,
                _height = _responsiveSeparateSp2 === void 0 ? 0 : _responsiveSeparateSp2;

            return {
              width: _width,
              height: _height
            };
          }
        }
      }

      return undefined;
    }
  }, {
    key: "spacingType",
    get: function get() {
      var spacingType = this.props.spacingType;
      return (0, _utils.normalizeSpacingType)(spacingType);
    }
  }, {
    key: "isReadOnly",
    value: function isReadOnly() {
      return this.readOnly;
    }
  }, {
    key: "isDisabled",
    value: function isDisabled() {
      var disabled = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "isDisabled", this).call(this);

      if (disabled) {
        return disabled;
      }

      var record = this.record;

      if (record) {
        return record.disabled;
      }

      return false;
    }
  }, {
    key: "getObservableProps",
    value: function getObservableProps(props, context) {
      var observableProps = (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "getObservableProps", this).call(this, props, context)), {}, {
        contextDataSet: context.dataSet,
        contextRecord: context.record,
        dataIndex: props.dataIndex,
        contextDataIndex: context.dataIndex,
        labelLayout: 'labelLayout' in props ? props.labelLayout : context.labelLayout,
        labelAlign: 'labelAlign' in props ? props.labelAlign : context.labelAlign,
        showValidation: 'showValidation' in props ? props.showValidation : context.showValidation,
        showHelp: 'showHelp' in props ? props.showHelp : context.showHelp,
        labelTooltip: 'labelTooltip' in props ? props.labelTooltip : context.labelTooltip,
        disabled: 'disabled' in props ? props.disabled : context.disabled,
        readOnly: 'readOnly' in props ? props.readOnly : context.readOnly,
        labelWidth: (0, _defaultTo["default"])(props.labelWidth, context.labelWidth),
        pristine: 'pristine' in props ? props.pristine : context.pristine,
        columns: props.columns,
        useColon: props.useColon,
        requiredMarkAlign: props.requiredMarkAlign,
        excludeUseColonTagList: props.excludeUseColonTagList,
        separateSpacing: props.separateSpacing,
        fieldHighlightRenderer: 'fieldHighlightRenderer' in props ? props.fieldHighlightRenderer : context.fieldHighlightRenderer
      });

      if ('record' in props) {
        observableProps.record = props.record;
      }

      return observableProps;
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "getOmitPropsKeys", this).call(this).concat(['record', 'dataIndex', 'onSuccess', 'onError', 'processParams', 'labelWidth', 'labelAlign', 'labelLayout', 'labelTooltip', 'columns', 'pristine', 'axios', 'useColon', 'requiredMarkAlign', 'excludeUseColonTagList', 'separateSpacing', 'spacingType', 'fieldHighlightRenderer', 'layout', 'showValidation', 'showHelp']);
    }
  }, {
    key: "getOtherProps",
    value: function getOtherProps() {
      var otherProps = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "getOtherProps", this).call(this);
      otherProps.onSubmit = this.handleSubmit;
      otherProps.onReset = this.handleReset;

      if (!otherProps.name) {
        otherProps.name = this.name;
      }

      return otherProps;
    }
  }, {
    key: "getHeader",
    value: function getHeader() {
      var header = this.props.header,
          prefixCls = this.prefixCls;

      if (header) {
        return /*#__PURE__*/_react["default"].createElement("div", {
          key: "form-header",
          className: "".concat(prefixCls, "-header")
        }, header);
      }
    }
  }, {
    key: "getClassName",
    value: function getClassName() {
      var _objectSpread2;

      var prefixCls = this.prefixCls,
          labelLayout = this.labelLayout,
          columns = this.columns;

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

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "getClassName", this).call(this, (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, props), {}, (_objectSpread2 = {}, (0, _defineProperty2["default"])(_objectSpread2, "".concat(prefixCls, "-float-label"), labelLayout === _enum.LabelLayout["float"]), (0, _defineProperty2["default"])(_objectSpread2, "".concat(prefixCls, "-").concat(labelLayout), !(0, _isNil["default"])(labelLayout)), (0, _defineProperty2["default"])(_objectSpread2, "".concat(prefixCls, "-").concat(columns > 1 ? "multi" : "single"), true), _objectSpread2)));
    }
  }, {
    key: "componentWillMount",
    value: function componentWillMount() {
      this.processDataSetListener(true);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.componentDidMountOrUpdate();
      this.handleFormFocus();
      (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "componentDidMount", this).call(this);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.componentDidMountOrUpdate();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.processDataSetListener(false);

      if (this.isTooltipShown) {
        (0, _singleton.hide)();
        delete this.isTooltipShown;
      }

      this.bubbleValidationReport(false);
    }
  }, {
    key: "handleFormFocus",
    value: function handleFormFocus() {
      // 聚焦到form内第一个可编辑组件上
      var fields = this.getFields();
      var editableField;

      for (var i = 0; i < fields.length; i++) {
        var field = fields[i];

        if (field.props.autoFocus) {
          break;
        }

        if (field.editable && !editableField) {
          editableField = field;
        }

        if (i === fields.length - 1 && editableField && this.getContextConfig('formAutoFocus')) {
          editableField.focus();
        }
      }
    }
  }, {
    key: "componentDidMountOrUpdate",
    value: function componentDidMountOrUpdate() {
      var formNode = this.context.formNode;
      var element = this.element;

      if (formNode && element) {
        var isUnderForm = (0, _utils.hasParentElement)(element.parentElement, 'form');

        if (isUnderForm !== this.isUnderForm) {
          this.isUnderForm = isUnderForm;
        }
      }
    }
  }, {
    key: "processDataSetListener",
    value: function processDataSetListener(flag) {
      var dataSet = this.dataSet;

      if (dataSet) {
        var handler = flag ? dataSet.addEventListener : dataSet.removeEventListener;
        handler.call(dataSet, _enum2.DataSetEvents.validate, this.handleDataSetValidate);
        handler.call(dataSet, _enum2.DataSetEvents.reset, this.handleDataSetReset);
        handler.call(dataSet, _enum2.DataSetEvents.remove, this.handleDataSetRemove);
      }
    }
  }, {
    key: "bubbleValidationReport",
    value: function bubbleValidationReport(showInvalid) {
      var pristine = this.props.pristine;

      if (!pristine) {
        var onComponentValidationReport = this.getContextConfig('onComponentValidationReport');

        if (onComponentValidationReport) {
          onComponentValidationReport({
            showInvalid: showInvalid,
            component: this
          });
        }
      }
    }
  }, {
    key: "handleDataSetReset",
    value: function handleDataSetReset(_ref) {
      var record = _ref.record,
          dataSet = _ref.dataSet;

      if (record) {
        var errors = dataSet.getAllValidationErrors();
        this.bubbleValidationReport(errors.dataSet.length > 0 || errors.records.length > 0);
      } else {
        this.bubbleValidationReport(false);
      }
    }
  }, {
    key: "handleDataSetRemove",
    value: function handleDataSetRemove(_ref2) {
      var records = _ref2.records,
          dataSet = _ref2.dataSet;

      if (records) {
        var errors = dataSet.getAllValidationErrors();
        this.bubbleValidationReport(errors.dataSet.length > 0 || errors.records.length > 0);
      }
    } // 处理校验失败定位

  }, {
    key: "handleDataSetValidate",
    value: function handleDataSetValidate(props) {
      var valid = props.valid,
          validationErrors = props.errors,
          noLocate = props.noLocate;
      this.bubbleValidationReport(!valid);
      var autoValidationLocate = this.props.autoValidationLocate;

      if (autoValidationLocate !== false && !noLocate && !valid) {
        var _validationErrors = (0, _slicedToArray2["default"])(validationErrors, 1),
            firstInvalidRecord = _validationErrors[0];

        if (firstInvalidRecord) {
          var errors = firstInvalidRecord.errors;

          if (errors.length) {
            var _errors = (0, _slicedToArray2["default"])(errors, 1),
                name = _errors[0].field.name;

            var field = this.getFields().find(function (item) {
              return item.props.name === name;
            });

            if (field) {
              (0, _raf["default"])(function () {
                field.focus();
              });
            }
          }
        }
      }
    }
  }, {
    key: "handleHelpMouseEnter",
    value: function handleHelpMouseEnter(e, help, helpTooltipProps) {
      var target = e.target;
      var _this$context = this.context,
          getTooltipTheme = _this$context.getTooltipTheme,
          getTooltipPlacement = _this$context.getTooltipPlacement;
      (0, _singleton.show)(target, (0, _objectSpread3["default"])({
        title: help,
        theme: getTooltipTheme('help'),
        placement: getTooltipPlacement('help')
      }, helpTooltipProps));
      this.isTooltipShown = true;
    }
  }, {
    key: "handleHelpMouseLeave",
    value: function handleHelpMouseLeave() {
      (0, _singleton.hide)();
    }
  }, {
    key: "renderTooltipHelp",
    value: function renderTooltipHelp(help, helpTooltipProps) {
      var _this2 = this;

      if (help) {
        return /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "help",
          onMouseEnter: function onMouseEnter(e) {
            return _this2.handleHelpMouseEnter(e, help, helpTooltipProps);
          },
          onMouseLeave: this.handleHelpMouseLeave
        });
      }
    }
  }, {
    key: "rasterizedChildren",
    value: function rasterizedChildren() {
      var _this3 = this;

      var dataSet = this.dataSet,
          record = this.record,
          columns = this.columns,
          labelLayout = this.labelLayout,
          labelAlign = this.labelAlign,
          labelTooltip = this.labelTooltip,
          useColon = this.useColon,
          requiredMarkAlign = this.requiredMarkAlign,
          excludeUseColonTagList = this.excludeUseColonTagList,
          formReadOnly = this.readOnly,
          showHelp = this.showHelp,
          children = this.props.children;
      var prefixCls = this.getContextProPrefixCls(_utils.FIELD_SUFFIX);
      var labelWidth = (0, _utils.normalizeLabelWidth)(this.labelWidth, columns);
      var rows = [];
      var cols = [];
      var rowIndex = 0;
      var colIndex = 0;
      var matrix = [[]];
      var noLabel = true;
      var childrenArray = [];
      var separateSpacing = this.separateSpacing;
      var isLabelLayoutHorizontal = labelLayout === _enum.LabelLayout.horizontal;
      var spacingProperties = separateSpacing ? (0, _utils.getSpacingProperties)(separateSpacing, this.spacingType, isLabelLayoutHorizontal) : undefined;
      var isAllOutputCom = true;

      _react.Children.forEach(children, function (child) {
        if ( /*#__PURE__*/(0, _react.isValidElement)(child)) {
          var setChild = function setChild(arr, outChild) {
            var groupProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
            var type = outChild.type,
                outChildProps = outChild.props;
            if (outChildProps.hidden) return null;

            if (type) {
              if (isAllOutputCom && (0, _isFunction["default"])(type) && !type.__PRO_OUTPUT && !(type.displayName === 'IntlField' && outChildProps && outChildProps.displayOutput)) {
                isAllOutputCom = false;
              }

              if (noLabel === true && isLabelLayoutHorizontal && (0, _utils.getProperty)(outChildProps, 'label', dataSet, record)) {
                noLabel = false;
              }

              var outChildChildren = outChildProps.children,
                  otherOutChildProps = (0, _objectWithoutProperties2["default"])(outChildProps, _excluded);
              var isFragmentElement = (0, _isFragment["default"])(outChild);

              if (isFragmentElement || type.__PRO_FORM_VIRTUAL_GROUP) {
                _react.Children.forEach(outChildChildren, function (c) {
                  if ( /*#__PURE__*/(0, _react.isValidElement)(c)) {
                    setChild(arr, c, isFragmentElement ? groupProps : (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, groupProps), otherOutChildProps));
                  }
                });
              } else {
                arr.push(Object.keys(groupProps).length ? /*#__PURE__*/(0, _react.cloneElement)(outChild, (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, groupProps), outChildProps)) : outChild);
              }
            }
          };

          setChild(childrenArray, child);
        }
      });

      function completeLine() {
        if (cols.length) {
          var maxRowSpan = Math.max.apply(Math, (0, _toConsumableArray2["default"])(cols.map(function (x) {
            return x.props.rowSpan;
          })));

          if (rows[rowIndex]) {
            rows[rowIndex] = /*#__PURE__*/_react["default"].createElement("tr", {
              key: "row-".concat(rowIndex)
            }, cols);
          } else {
            rows.push( /*#__PURE__*/_react["default"].createElement("tr", {
              key: "row-".concat(rowIndex)
            }, cols));
          }

          if (maxRowSpan > 1) {
            new Array(maxRowSpan - 1).fill(0).forEach(function () {
              return rows.push( /*#__PURE__*/_react["default"].createElement("tr", null));
            });
          }

          cols = [];
        }

        rowIndex++;
        colIndex = 0;
        matrix[rowIndex] = matrix[rowIndex] || [];
      }

      var _loop = function _loop(_index, len) {
        var _classNames, _classNames2;

        var _childrenArray$_index = childrenArray[_index],
            props = _childrenArray$_index.props,
            key = _childrenArray$_index.key,
            type = _childrenArray$_index.type,
            ref = _childrenArray$_index.ref;
        var TagName = (0, _isFunction["default"])(type) ? type.displayName : type;
        var label = (0, _utils.getProperty)(props, 'label', dataSet, record);
        var help = (0, _utils.getProperty)(props, 'help', dataSet, record);
        var fieldLabelWidth = (0, _utils.getProperty)(props, 'labelWidth', dataSet, record);
        var required = (0, _utils.getPropertyDSFirst)(props, 'required', dataSet, record);
        var readOnly = (0, _utils.getProperty)(props, 'readOnly', dataSet, record) || formReadOnly;
        var intlFieldOutput = TagName === 'IntlField' && props && props.displayOutput;
        var _props$rowSpan = props.rowSpan,
            rowSpan = _props$rowSpan === void 0 ? 1 : _props$rowSpan,
            _props$colSpan = props.colSpan,
            colSpan = _props$colSpan === void 0 ? 1 : _props$colSpan,
            newLine = props.newLine,
            className = props.className,
            fieldClassName = props.fieldClassName,
            _props$useColon = props.useColon,
            fieldUseColon = _props$useColon === void 0 ? useColon : _props$useColon,
            _props$requiredMarkAl = props.requiredMarkAlign,
            fieldRequiredMarkAlign = _props$requiredMarkAl === void 0 ? requiredMarkAlign : _props$requiredMarkAl,
            otherProps = (0, _objectWithoutProperties2["default"])(props, _excluded2);
        var newColSpan = colSpan;
        var currentRow = matrix[rowIndex];

        if (newLine) {
          if (colIndex !== 0) {
            completeLine();
            index = _index;
            return "continue";
          }
        }

        while (currentRow[colIndex]) {
          colIndex++;
        }

        if (colIndex >= columns) {
          completeLine();
          index = _index;
          return "continue";
        }

        if (newColSpan + colIndex > columns) {
          newColSpan = columns - colIndex;
        }

        for (var _i2 = colIndex, k = colIndex + newColSpan; _i2 < k; _i2++) {
          if (currentRow[_i2]) {
            newColSpan = _i2 - colIndex;
            break;
          }
        }

        for (var _i3 = rowIndex; _i3 < rowSpan + rowIndex; _i3++) {
          for (var j = colIndex, _k = newColSpan + colIndex; j < _k; j++) {
            if (!matrix[_i3]) {
              matrix[_i3] = [];
            }

            matrix[_i3][j] = true;
          }
        }

        var fieldElementProps = (0, _objectSpread3["default"])({
          ref: ref,
          key: key,
          className: (0, _classnames["default"])(prefixCls, className)
        }, otherProps);
        var isOutput = type.__PRO_OUTPUT || intlFieldOutput;
        var outputMix = !isAllOutputCom && isOutput ? 'mix' : '';
        var isLabelShowHelp = (fieldElementProps.showHelp || showHelp) === _enum3.ShowHelp.label;
        var labelClassName = (0, _classnames["default"])("".concat(prefixCls, "-label"), "".concat(prefixCls, "-label-").concat(labelAlign), fieldClassName, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-required"), required && !isOutput), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-readonly"), readOnly), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-label-vertical"), labelLayout === _enum.LabelLayout.vertical), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-label-output"), isLabelLayoutHorizontal && isOutput), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-label-output-").concat(outputMix), isLabelLayoutHorizontal && isOutput && outputMix), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-label-useColon"), label && fieldUseColon && !excludeUseColonTagList.find(function (v) {
          return v === TagName;
        })), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-label-required-mark-").concat((0, _utils.getRequiredMarkAlign)(fieldRequiredMarkAlign)), isLabelLayoutHorizontal && required && !isOutput && (0, _utils.getRequiredMarkAlign)(fieldRequiredMarkAlign)), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-label-help"), isLabelShowHelp), _classNames));
        var wrapperClassName = (0, _classnames["default"])("".concat(prefixCls, "-wrapper"), (_classNames2 = {}, (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-output"), isLabelLayoutHorizontal && isOutput), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-output-").concat(outputMix), isLabelLayoutHorizontal && isOutput && outputMix), _classNames2));

        if (!noLabel && !type.__PRO_FORM_ITEM) {
          var _columnLabelWidth = labelWidth[colIndex];

          if (!isNaN(fieldLabelWidth) && _columnLabelWidth !== 'auto') {
            labelWidth[colIndex] = Math.max(_columnLabelWidth, fieldLabelWidth);
          }

          var tooltip = 'labelTooltip' in props ? props.labelTooltip : labelTooltip;
          cols.push( /*#__PURE__*/_react["default"].createElement(_FormItemLabel["default"], {
            key: "row-".concat(rowIndex, "-col-").concat(colIndex, "-label"),
            className: labelClassName,
            rowSpan: rowSpan,
            style: spacingProperties ? (0, _utils.getSpacingLabelStyle)(spacingProperties, isLabelLayoutHorizontal, rowIndex) : undefined,
            tooltip: tooltip,
            help: isLabelShowHelp ? _this3.renderTooltipHelp(help, fieldElementProps.helpTooltipProps) : undefined
          }, (0, _mobx.toJS)(label)));
        }

        if (!(0, _isString["default"])(type)) {
          fieldElementProps.rowIndex = rowIndex;
          fieldElementProps.colIndex = colIndex;
        }

        var currentColSpan = noLabel ? newColSpan : newColSpan * 2 - (type.__PRO_FORM_ITEM ? 0 : 1);
        cols.push( /*#__PURE__*/_react["default"].createElement("td", {
          key: "row-".concat(rowIndex, "-col-").concat(colIndex, "-field"),
          colSpan: currentColSpan,
          rowSpan: rowSpan,
          className: fieldClassName,
          style: spacingProperties ? (0, _utils.getSpacingFieldStyle)(spacingProperties, isLabelLayoutHorizontal, rowIndex) : undefined
        }, labelLayout === _enum.LabelLayout.vertical && !!label && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("label", {
          className: labelClassName
        }, (0, _mobx.toJS)(label)), isLabelShowHelp ? _this3.renderTooltipHelp(help, fieldElementProps.helpTooltipProps) : null), /*#__PURE__*/_react["default"].createElement("div", {
          className: wrapperClassName
        }, /*#__PURE__*/(0, _react.createElement)(type, fieldElementProps))));

        if (_index === len - 1) {
          completeLine();
        } else {
          colIndex++;
        }

        _index++;
        index = _index;
      };

      for (var index = 0, len = childrenArray.length; index < len;) {
        var _ret = _loop(index, len);

        if (_ret === "continue") continue;
      }

      cols = [];
      var isAutoWidth = !noLabel && labelWidth.some(function (w) {
        return w === 'auto';
      });

      if (!noLabel) {
        for (var i = 0; i < columns; i++) {
          var key = "label-".concat(i);
          var columnLabelWidth = labelWidth[i % columns];

          if (columnLabelWidth === 'auto') {
            cols.push( /*#__PURE__*/_react["default"].createElement("col", {
              key: key
            }));
          } else {
            cols.push( /*#__PURE__*/_react["default"].createElement("col", {
              key: key,
              // 优化当使用 separateSpacing label 宽度太窄问题
              style: {
                width: (0, _UnitConvertor.pxToRem)(spacingProperties ? spacingProperties.paddingHorizontal + columnLabelWidth : columnLabelWidth)
              }
            }));
          }

          cols.push( /*#__PURE__*/_react["default"].createElement("col", {
            key: "wrapper-".concat(i),
            style: isAutoWidth ? {
              width: "".concat(100 / columns, "%")
            } : undefined
          }));
        }
      } else {
        for (var _i = 0; _i < columns; _i++) {
          cols.push( /*#__PURE__*/_react["default"].createElement("col", {
            key: "wrapper-".concat(_i)
          }));
        }
      }

      return /*#__PURE__*/_react["default"].createElement("table", {
        key: "form-body",
        style: spacingProperties && spacingProperties.style,
        className: "".concat(isAutoWidth ? 'auto-width' : '')
      }, cols.length ? /*#__PURE__*/_react["default"].createElement("colgroup", null, cols) : undefined, /*#__PURE__*/_react["default"].createElement("tbody", null, rows));
    }
  }, {
    key: "getMergedProps",
    value: function getMergedProps() {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var mergedProps = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Form.prototype), "getMergedProps", this).call(this, props);

      if (this.spacingType.width === _enum.SpacingType.between && this.separateSpacing && this.separateSpacing.width > 0) {
        mergedProps.style = (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, mergedProps.style), {}, {
          overflowX: 'hidden'
        });
      }

      return mergedProps;
    }
  }, {
    key: "render",
    value: function render() {
      var labelWidth = this.labelWidth,
          labelAlign = this.labelAlign,
          labelLayout = this.labelLayout,
          labelTooltip = this.labelTooltip,
          pristine = this.pristine,
          dataSet = this.dataSet,
          record = this.record,
          dataIndex = this.dataIndex,
          observableProps = this.observableProps,
          disabled = this.disabled,
          readOnly = this.readOnly,
          fieldHighlightRenderer = this.fieldHighlightRenderer,
          props = this.props,
          useColon = this.useColon,
          requiredMarkAlign = this.requiredMarkAlign,
          showValidation = this.showValidation,
          showHelp = this.showHelp;
      var _this$context2 = this.context,
          formNode = _this$context2.formNode,
          getConfig = _this$context2.getConfig,
          getProPrefixCls = _this$context2.getProPrefixCls,
          getPrefixCls = _this$context2.getPrefixCls,
          getCustomizable = _this$context2.getCustomizable,
          getTooltip = _this$context2.getTooltip,
          getTooltipTheme = _this$context2.getTooltipTheme,
          getTooltipPlacement = _this$context2.getTooltipPlacement;
      var value = {
        formNode: formNode || this,
        dataSet: dataSet,
        dataIndex: dataIndex,
        record: record,
        labelWidth: labelWidth,
        labelAlign: labelAlign,
        labelLayout: labelLayout,
        labelTooltip: labelTooltip,
        pristine: pristine,
        disabled: disabled,
        readOnly: readOnly,
        fieldHighlightRenderer: fieldHighlightRenderer,
        useColon: useColon,
        requiredMarkAlign: requiredMarkAlign,
        showValidation: showValidation,
        showHelp: showHelp,
        getConfig: getConfig,
        getPrefixCls: getPrefixCls,
        getProPrefixCls: getProPrefixCls,
        getCustomizable: getCustomizable,
        getTooltip: getTooltip,
        getTooltipTheme: getTooltipTheme,
        getTooltipPlacement: getTooltipPlacement
      };
      var children = [this.getHeader(), props.layout === _enum.FormLayout.table ? this.rasterizedChildren() : props.children];
      return /*#__PURE__*/_react["default"].createElement(_Responsive["default"], {
        items: [observableProps.columns, observableProps.labelWidth, observableProps.labelAlign, observableProps.labelLayout, observableProps.separateSpacing],
        onChange: this.handleResponsive
      }, /*#__PURE__*/_react["default"].createElement(_FormContext.FormProvider, {
        value: value
      }, this.isUnderForm ? children : formNode && this.isUnderForm === undefined ? /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({}, this.getMergedProps()), children) : /*#__PURE__*/_react["default"].createElement("form", (0, _extends2["default"])({}, this.getMergedProps(), {
        noValidate: true
      }), children)));
    }
  }, {
    key: "handleResponsive",
    value: function handleResponsive(items) {
      this.responsiveItems = items;
    }
  }, {
    key: "handleSubmit",
    value: function () {
      var _handleSubmit = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(e) {
        var _this$props, target, action, dataSet, method, _this$props$processPa, processParams, _this$props$onSuccess, onSuccess, _this$props$onError, onError, _this$props$onSubmit, onSubmit;

        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                e.preventDefault();
                e.persist();
                _context2.next = 4;
                return this.checkValidity();

              case 4:
                if (!_context2.sent) {
                  _context2.next = 31;
                  break;
                }

                _this$props = this.props, target = _this$props.target, action = _this$props.action, dataSet = _this$props.dataSet, method = _this$props.method, _this$props$processPa = _this$props.processParams, processParams = _this$props$processPa === void 0 ? _noop["default"] : _this$props$processPa, _this$props$onSuccess = _this$props.onSuccess, onSuccess = _this$props$onSuccess === void 0 ? _noop["default"] : _this$props$onSuccess, _this$props$onError = _this$props.onError, onError = _this$props$onError === void 0 ? _noop["default"] : _this$props$onError, _this$props$onSubmit = _this$props.onSubmit, onSubmit = _this$props$onSubmit === void 0 ? _noop["default"] : _this$props$onSubmit;
                onSubmit(e);
                _context2.prev = 7;

                if (!dataSet) {
                  _context2.next = 16;
                  break;
                }

                _context2.t0 = onSuccess;
                _context2.next = 12;
                return dataSet.submit();

              case 12:
                _context2.t1 = _context2.sent;
                (0, _context2.t0)(_context2.t1);
                _context2.next = 26;
                break;

              case 16:
                if (!action) {
                  _context2.next = 26;
                  break;
                }

                if (!(target && this.element)) {
                  _context2.next = 21;
                  break;
                }

                this.element.submit();
                _context2.next = 26;
                break;

              case 21:
                _context2.t2 = onSuccess;
                _context2.next = 24;
                return this.axios[method || 'get'](action, processParams(e));

              case 24:
                _context2.t3 = _context2.sent;
                (0, _context2.t2)(_context2.t3);

              case 26:
                _context2.next = 31;
                break;

              case 28:
                _context2.prev = 28;
                _context2.t4 = _context2["catch"](7);
                onError(_context2.t4);

              case 31:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[7, 28]]);
      }));

      function handleSubmit(_x) {
        return _handleSubmit.apply(this, arguments);
      }

      return handleSubmit;
    }()
  }, {
    key: "handleReset",
    value: function handleReset(e) {
      var _this$props$onReset = this.props.onReset,
          onReset = _this$props$onReset === void 0 ? _noop["default"] : _this$props$onReset;
      var record = this.record;
      onReset(e);

      if (!e.isDefaultPrevented()) {
        if (record) {
          record.reset();
        } else {
          this.getFields().forEach(function (field) {
            return field.reset();
          });
        }
      }
    }
  }, {
    key: "reportValidity",
    value: function reportValidity(result) {
      var _this4 = this;

      var prepareForReport = this.prepareForReport;

      if (!result) {
        prepareForReport.result = result;
      }

      if (prepareForReport.timeout) {
        window.clearTimeout(prepareForReport.timeout);
      }

      prepareForReport.timeout = window.setTimeout(function () {
        if (!prepareForReport.result) {
          var field = _this4.getFields().find(function (one) {
            return !one.valid;
          });

          if (field) {
            field.focus();
          }
        }

        _this4.prepareForReport = {};
      }, 200);
    }
  }, {
    key: "checkValidity",
    value: function checkValidity() {
      var _this5 = this;

      var dataSet = this.dataSet;

      if (dataSet) {
        if (!dataSet.length) {
          dataSet.create();
        }

        return dataSet.validate();
      }

      this.validating = true;
      return Promise.all(this.getFields().map(function (field) {
        return field.checkValidity();
      })).then(function (results) {
        var valid = results.every(function (result) {
          return result;
        });

        _this5.reportValidity(valid);

        _this5.validating = false;
        return valid;
      })["catch"](function (error) {
        _this5.validating = false;
        throw error;
      });
    }
  }, {
    key: "getFields",
    value: function getFields() {
      var id = this.props.id;

      if (id) {
        return [].concat(this.fields, (0, _FormField.getFieldsById)(id));
      }

      return this.fields;
    }
  }, {
    key: "getField",
    value: function getField(name) {
      return this.getFields().find(function (field) {
        return field.props.name === name;
      });
    }
  }, {
    key: "addField",
    value: function addField(field) {
      this.fields.push(field);
    }
  }, {
    key: "removeField",
    value: function removeField(field) {
      var index = this.fields.indexOf(field);

      if (index !== -1) {
        this.fields.splice(index, 1);
      }
    }
  }], [{
    key: "contextType",
    get: function get() {
      return _FormContext["default"];
    }
  }]);
  return Form;
}(_DataSetComponent2["default"]);

Form.displayName = 'Form';
Form.ItemGroup = _ItemGroup["default"];
Form.FormVirtualGroup = _FormVirtualGroup["default"];
Form.Item = _Item["default"];
Form.defaultProps = {
  suffixCls: 'form',
  columns: _utils.defaultColumns,
  labelWidth: _utils.defaultLabelWidth,
  layout: _enum.FormLayout.table
};
(0, _tslib.__decorate)([_mobx.observable], Form.prototype, "responsiveItems", void 0);
(0, _tslib.__decorate)([_mobx.observable], Form.prototype, "isUnderForm", void 0);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "axios", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "dataSet", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "record", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "dataIndex", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "useColon", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "requiredMarkAlign", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "excludeUseColonTagList", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "columns", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "labelWidth", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "labelAlign", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "labelLayout", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "labelTooltip", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "readOnly", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "pristine", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "fieldHighlightRenderer", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "showValidation", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "showHelp", null);
(0, _tslib.__decorate)([_mobx.computed], Form.prototype, "separateSpacing", null);
(0, _tslib.__decorate)([_mobx.action], Form.prototype, "componentDidMountOrUpdate", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleDataSetReset", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleDataSetRemove", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleDataSetValidate", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleHelpMouseEnter", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleHelpMouseLeave", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], Form.prototype, "handleResponsive", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleSubmit", null);
(0, _tslib.__decorate)([_autobind["default"]], Form.prototype, "handleReset", null);
Form = (0, _tslib.__decorate)([_mobxReact.observer], Form);
var _default = Form;
exports["default"] = _default;
//# sourceMappingURL=Form.js.map
