function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

import { __rest } from "tslib";
import classNames from 'classnames';
import React, { Component, createElement } from "react";
import Field from '../field';
import { isBoolean, makeChain, scrollToId } from '../utils';
import View from '../view';
import Context, { defaultContext } from './context';
import { removeFormAttrs } from './utils';

var Form = /*#__PURE__*/function (_Component) {
  _inherits(Form, _Component);

  var _super = _createSuper(Form);

  function Form(props) {
    var _this;

    _classCallCheck(this, Form);

    _this = _super.call(this, props);
    _this.mapNameToGuid = {};
    _this.validateCallback = [];
    _this.handleAfterValidate = _this.handleAfterValidate.bind(_assertThisInitialized(_this));

    if (props.field) {
      _this.field = props.field;
      props.field.afterValidateRerender = props.field.afterValidateRerender ? makeChain(_this.handleAfterValidate, props.field.afterValidateRerender) : _this.handleAfterValidate;
      props.field.setOptions({
        onChange: makeChain(props.field.options.onChange, _this.handleChange.bind(_assertThisInitialized(_this)))
      });
    } else {
      var _props$autoUnmount = props.autoUnmount,
          autoUnmount = _props$autoUnmount === void 0 ? true : _props$autoUnmount,
          _props$autoValidate = props.autoValidate,
          autoValidate = _props$autoValidate === void 0 ? true : _props$autoValidate,
          _props$scrollToFirstE = props.scrollToFirstError,
          scrollToFirstError = _props$scrollToFirstE === void 0 ? false : _props$scrollToFirstE;
      _this.field = new Field(_assertThisInitialized(_this), {
        autoUnmount: autoUnmount,
        autoValidate: autoValidate,
        values: props.value || props.defaultValue || {},
        onChange: _this.handleChange.bind(_assertThisInitialized(_this)),
        scrollToFirstError: scrollToFirstError,
        afterValidateRerender: _this.handleAfterValidate
      });
    }

    if (props.saveField) {
      props.saveField(_this.field);
    }

    return _this;
  }

  _createClass(Form, [{
    key: "submit",
    value: function submit() {
      var _this2 = this,
          _this$field;

      if (arguments.length === 0) {
        return this.field.validatePromise();
      }

      var names;
      var callback = null;
      var skipValidate = false;

      switch (arguments.length) {
        case 1:
          if (Array.isArray(arguments.length <= 0 ? undefined : arguments[0])) {
            names = arguments.length <= 0 ? undefined : arguments[0];
          } else if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'function') {
            callback = arguments.length <= 0 ? undefined : arguments[0];
          }

          break;

        case 2:
          if (isBoolean(arguments.length <= 1 ? undefined : arguments[1])) {
            callback = arguments.length <= 0 ? undefined : arguments[0];
            skipValidate = arguments.length <= 1 ? undefined : arguments[1];
          } else {
            names = arguments.length <= 0 ? undefined : arguments[0];
            callback = arguments.length <= 1 ? undefined : arguments[1];
          }

          break;

        case 3:
          names = arguments.length <= 0 ? undefined : arguments[0];
          callback = arguments.length <= 1 ? undefined : arguments[1];
          skipValidate = arguments.length <= 2 ? undefined : arguments[2];
          break;

        default:
          {
            console.error('调用 Form.submit 参数错误，期待参数 <names?: [], callback?: function>');
          }
      }

      var validateCb = function validateCb(errors, values) {
        var onSubmit = _this2.props.onSubmit;

        if (errors) {
          callback(null, errors, _this2.field);

          if (onSubmit) {
            onSubmit(null, errors, _this2.field);
          }
        } else {
          callback(values, null, _this2.field);

          if (onSubmit) {
            onSubmit(values, null, _this2.field);
          }
        }
      };

      var validateParams = names ? [names, validateCb] : [validateCb];

      if (skipValidate) {
        var onSubmit = this.props.onSubmit;
        callback(this.getValue(names), null, this.field);

        if (onSubmit) {
          onSubmit(this.getValue(names), null, this.field);
        }

        return;
      }

      return (_this$field = this.field).validateCallback.apply(_this$field, validateParams);
    }
  }, {
    key: "reset",
    value: function reset() {
      var toDefault = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      var names = arguments.length > 1 ? arguments[1] : undefined;

      if (toDefault) {
        this.field.resetToDefault(names);
      } else {
        this.field.reset(names);
      }
    }
  }, {
    key: "getValue",
    value: function getValue(names) {
      return this.field.getValues(names);
    }
  }, {
    key: "setValue",
    value: function setValue(values) {
      this.field.setValues(values);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (this.props.field && this.props.field !== prevProps.field) {
        this.field = this.props.field;
        this.forceUpdate();
      }

      if (this.props.scrollToFirstError !== prevProps.scrollToFirstError) {
        this.field.setOptions({
          scrollToFirstError: !!this.props.scrollToFirstError
        });
      }

      if ('value' in this.props) {
        var value = this.props.value;

        if (value === prevProps.value) {
          return;
        }

        if (value) {
          this.field.setValues(value);
        } else {
          this.field.resetToDefault();
        }
      }
    }
  }, {
    key: "handleChange",
    value: function handleChange(name, value) {
      var onChange = this.props.onChange;

      if (onChange) {
        onChange(this.field.getValues(), {
          name: name,
          value: value,
          field: this.field
        });
      }
    }
  }, {
    key: "handleAfterValidate",
    value: function handleAfterValidate(data) {
      var _this3 = this;

      var errorsGroup = data.errorsGroup;

      if (errorsGroup && this.props.scrollToFirstError) {
        var firstNodeId = null;

        for (var i in errorsGroup) {
          if (errorsGroup.hasOwnProperty(i) && typeof this.mapNameToGuid[i] !== 'undefined') {
            firstNodeId = this.mapNameToGuid[i];
            break;
          }
        }

        if (firstNodeId) {
          scrollToId(firstNodeId);
        }
      }

      this.validateCallback.forEach(function (it) {
        return it.apply(_this3);
      });
    }
  }, {
    key: "onValidate",
    value: function onValidate(cb) {
      var _this4 = this;

      if (!this.validateCallback.includes(cb)) {
        this.validateCallback.push(cb);
      }

      return function () {
        var index = _this4.validateCallback.indexOf(cb);

        if (index >= 0) {
          _this4.validateCallback.splice(index, 1);
        }
      };
    }
  }, {
    key: "render",
    value: function render() {
      var _a = this.props,
          _a$prefix = _a.prefix,
          prefix = _a$prefix === void 0 ? 'mt-' : _a$prefix,
          children = _a.children,
          className = _a.className,
          onSubmit = _a.onSubmit,
          _a$labelAlign = _a.labelAlign,
          labelAlign = _a$labelAlign === void 0 ? defaultContext.labelAlign : _a$labelAlign,
          _a$labelWidth = _a.labelWidth,
          labelWidth = _a$labelWidth === void 0 ? defaultContext.labelWidth : _a$labelWidth,
          _a$labelTextAlign = _a.labelTextAlign,
          labelTextAlign = _a$labelTextAlign === void 0 ? defaultContext.labelTextAlign : _a$labelTextAlign,
          _a$contentAlign = _a.contentAlign,
          contentAlign = _a$contentAlign === void 0 ? defaultContext.contentAlign : _a$contentAlign,
          _a$isPreview = _a.isPreview,
          isPreview = _a$isPreview === void 0 ? defaultContext.isPreview : _a$isPreview,
          _a$useLabelForErrorMe = _a.useLabelForErrorMessage,
          useLabelForErrorMessage = _a$useLabelForErrorMe === void 0 ? defaultContext.useLabelForErrorMessage : _a$useLabelForErrorMe,
          _a$size = _a.size,
          size = _a$size === void 0 ? defaultContext.size : _a$size,
          onChange = _a.onChange,
          others = __rest(_a, ["prefix", "children", "className", "onSubmit", "labelAlign", "labelWidth", "labelTextAlign", "contentAlign", "isPreview", "useLabelForErrorMessage", "size", "onChange"]);

      var field = this.field;
      var contextValue = {
        labelAlign: labelAlign,
        labelWidth: labelWidth,
        labelTextAlign: labelTextAlign,
        contentAlign: contentAlign,
        isPreview: isPreview,
        useLabelForErrorMessage: useLabelForErrorMessage,
        size: size,
        form: this,
        field: field
      };
      return /*#__PURE__*/React.createElement(Context.Provider, {
        value: contextValue
      }, /*#__PURE__*/React.createElement(View, _extends({}, removeFormAttrs(others), {
        className: classNames("".concat(prefix, "form"), className)
      }), children));
    }
  }]);

  return Form;
}(Component);

export { Form as default };