"use strict";

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); }

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

var _vue = _interopRequireWildcard(require("vue"));

var _vueTypes = _interopRequireDefault(require("../_util/vue-types"));

var _classNames2 = _interopRequireDefault(require("../_util/classNames"));

var _Col = require("../grid/Col");

var _isRegExp = _interopRequireDefault(require("lodash/isRegExp"));

var _warning = _interopRequireDefault(require("../_util/warning"));

var _FormItem = _interopRequireDefault(require("./FormItem"));

var _propsUtil = require("../_util/props-util");

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

var _valueUtil = require("./utils/valueUtil");

var _messages = require("./utils/messages");

var _asyncUtil = require("./utils/asyncUtil");

var _typeUtil = require("./utils/typeUtil");

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

var _scrollIntoViewIfNeeded = _interopRequireDefault(require("scroll-into-view-if-needed"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

var FormProps = {
  layout: _vueTypes.default.oneOf(['horizontal', 'inline', 'vertical']),
  labelCol: _vueTypes.default.shape(_Col.ColProps).loose,
  wrapperCol: _vueTypes.default.shape(_Col.ColProps).loose,
  colon: _vueTypes.default.bool,
  labelAlign: _vueTypes.default.oneOf(['left', 'right']),
  prefixCls: _vueTypes.default.string,
  hideRequiredMark: _vueTypes.default.bool,
  model: _vueTypes.default.object,
  rules: _vueTypes.default.object,
  validateMessages: _vueTypes.default.any,
  validateOnRuleChange: _vueTypes.default.bool,
  // 提交失败自动滚动到第一个错误字段
  scrollToFirstError: _vueTypes.default.bool,
  onFinish: _vueTypes.default.func,
  onFinishFailed: _vueTypes.default.func,
  name: _vueTypes.default.name,
  validateTrigger: _vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.array])
};
exports.FormProps = FormProps;
var ValidationRule = {
  /** validation error message */
  message: _vueTypes.default.string,

  /** built-in validation type, available options: https://github.com/yiminghe/async-validator#type */
  type: _vueTypes.default.string,

  /** indicates whether field is required */
  required: _vueTypes.default.boolean,

  /** treat required fields that only contain whitespace as errors */
  whitespace: _vueTypes.default.boolean,

  /** validate the exact length of a field */
  len: _vueTypes.default.number,

  /** validate the min length of a field */
  min: _vueTypes.default.number,

  /** validate the max length of a field */
  max: _vueTypes.default.number,

  /** validate the value from a list of possible values */
  enum: _vueTypes.default.oneOfType([String, _vueTypes.default.arrayOf(String)]),

  /** validate from a regular expression */
  pattern: _vueTypes.default.custom(_isRegExp.default),

  /** transform a value before validation */
  transform: _vueTypes.default.func,

  /** custom validate function (Note: callback must be called) */
  validator: _vueTypes.default.func
};
exports.ValidationRule = ValidationRule;

function isEqualName(name1, name2) {
  return (0, _isEqual.default)((0, _typeUtil.toArray)(name1), (0, _typeUtil.toArray)(name2));
}

var Form = {
  name: 'AForm',
  inheritAttrs: false,
  props: (0, _propsUtil.initDefaultProps)(FormProps, {
    layout: 'horizontal',
    hideRequiredMark: false,
    colon: true
  }),
  Item: _FormItem.default,
  created: function created() {
    this.fields = [];
    this.form = undefined;
    this.lastValidatePromise = null;
    (0, _vue.provide)('FormContext', this);
  },
  setup: function setup() {
    return {
      configProvider: (0, _vue.inject)('configProvider', _configProvider.ConfigConsumerProps)
    };
  },
  watch: {
    rules: function rules() {
      if (this.validateOnRuleChange) {
        this.validateFields();
      }
    }
  },
  computed: {
    vertical: function vertical() {
      return this.layout === 'vertical';
    }
  },
  methods: {
    addField: function addField(field) {
      if (field) {
        this.fields.push(field);
      }
    },
    removeField: function removeField(field) {
      if (field.fieldName) {
        this.fields.splice(this.fields.indexOf(field), 1);
      }
    },
    handleSubmit: function handleSubmit(e) {
      var _this = this;

      e.preventDefault();
      e.stopPropagation();
      this.$emit('submit', e);
      var res = this.validateFields();
      res.then(function (values) {
        _this.$emit('finish', values);
      }).catch(function (errors) {
        _this.handleFinishFailed(errors);
      });
    },
    getFieldsByNameList: function getFieldsByNameList(nameList) {
      var provideNameList = !!nameList;
      var namePathList = provideNameList ? (0, _typeUtil.toArray)(nameList).map(_valueUtil.getNamePath) : [];

      if (!provideNameList) {
        return this.fields;
      } else {
        return this.fields.filter(function (field) {
          return namePathList.findIndex(function (namePath) {
            return isEqualName(namePath, field.fieldName);
          }) > -1;
        });
      }
    },
    resetFields: function resetFields(name) {
      if (!this.model) {
        (0, _warning.default)(false, 'Form', 'model is required for resetFields to work.');
        return;
      }

      this.getFieldsByNameList(name).forEach(function (field) {
        field.resetField();
      });
    },
    clearValidate: function clearValidate(name) {
      this.getFieldsByNameList(name).forEach(function (field) {
        field.clearValidate();
      });
    },
    handleFinishFailed: function handleFinishFailed(errorInfo) {
      var scrollToFirstError = this.scrollToFirstError;
      this.$emit('finishFailed', errorInfo);

      if (scrollToFirstError && errorInfo.errorFields.length) {
        this.scrollToField(errorInfo.errorFields[0].name);
      }
    },
    validate: function validate() {
      return this.validateField.apply(this, arguments);
    },
    scrollToField: function scrollToField(name) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var fields = this.getFieldsByNameList([name]);

      if (fields.length) {
        var fieldId = fields[0].fieldId;
        var node = fieldId ? document.getElementById(fieldId) : null;

        if (node) {
          (0, _scrollIntoViewIfNeeded.default)(node, _objectSpread({
            scrollMode: 'if-needed',
            block: 'nearest'
          }, options));
        }
      }
    },
    // eslint-disable-next-line no-unused-vars
    getFieldsValue: function getFieldsValue() {
      var nameList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      var values = {};
      this.fields.forEach(function (_ref) {
        var fieldName = _ref.fieldName,
            fieldValue = _ref.fieldValue;
        values[fieldName] = fieldValue;
      });

      if (nameList === true) {
        return values;
      } else {
        var res = {};
        (0, _typeUtil.toArray)(nameList).forEach(function (namePath) {
          return res[namePath] = values[namePath];
        });
        return res;
      }
    },
    validateFields: function validateFields(nameList, options) {
      var _this2 = this;

      (0, _warning.default)(!(nameList instanceof Function), 'Form', 'validateFields/validateField/validate not support callback, please use promise instead');

      if (!this.model) {
        (0, _warning.default)(false, 'Form', 'model is required for validateFields to work.');
        return Promise.reject('Form `model` is required for validateFields to work.');
      }

      var provideNameList = !!nameList;
      var namePathList = provideNameList ? (0, _typeUtil.toArray)(nameList).map(_valueUtil.getNamePath) : []; // Collect result in promise list

      var promiseList = [];
      this.fields.forEach(function (field) {
        // Add field if not provide `nameList`
        if (!provideNameList) {
          namePathList.push(field.getNamePath());
        } // Skip if without rule


        if (!field.getRules().length) {
          return;
        }

        var fieldNamePath = field.getNamePath(); // Add field validate rule in to promise list

        if (!provideNameList || (0, _valueUtil.containsNamePath)(namePathList, fieldNamePath)) {
          var promise = field.validateRules(_objectSpread({
            validateMessages: _objectSpread(_objectSpread({}, _messages.defaultValidateMessages), _this2.validateMessages)
          }, options)); // Wrap promise with field

          promiseList.push(promise.then(function () {
            return {
              name: fieldNamePath,
              errors: []
            };
          }).catch(function (errors) {
            return Promise.reject({
              name: fieldNamePath,
              errors: errors
            });
          }));
        }
      });
      var summaryPromise = (0, _asyncUtil.allPromiseFinish)(promiseList);
      this.lastValidatePromise = summaryPromise;
      var returnPromise = summaryPromise.then(function () {
        if (_this2.lastValidatePromise === summaryPromise) {
          return Promise.resolve(_this2.getFieldsValue(namePathList));
        }

        return Promise.reject([]);
      }).catch(function (results) {
        var errorList = results.filter(function (result) {
          return result && result.errors.length;
        });
        return Promise.reject({
          values: _this2.getFieldsValue(namePathList),
          errorFields: errorList,
          outOfDate: _this2.lastValidatePromise !== summaryPromise
        });
      }); // Do not throw in console

      returnPromise.catch(function (e) {
        return e;
      });
      return returnPromise;
    },
    validateField: function validateField() {
      return this.validateFields.apply(this, arguments);
    }
  },
  render: function render() {
    var _classNames;

    var customizePrefixCls = this.prefixCls,
        hideRequiredMark = this.hideRequiredMark,
        layout = this.layout,
        handleSubmit = this.handleSubmit;
    var getPrefixCls = this.configProvider.getPrefixCls;
    var prefixCls = getPrefixCls('form', customizePrefixCls);

    var _this$$attrs = this.$attrs,
        className = _this$$attrs.class,
        originSubmit = _this$$attrs.onSubmit,
        restProps = _objectWithoutProperties(_this$$attrs, ["class", "onSubmit"]);

    var formClassName = (0, _classNames2.default)(prefixCls, className, (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-horizontal"), layout === 'horizontal'), _defineProperty(_classNames, "".concat(prefixCls, "-vertical"), layout === 'vertical'), _defineProperty(_classNames, "".concat(prefixCls, "-inline"), layout === 'inline'), _defineProperty(_classNames, "".concat(prefixCls, "-hide-required-mark"), hideRequiredMark), _classNames));
    return _vue.createVNode("form", _vue.mergeProps(restProps, {
      "onSubmit": handleSubmit,
      "class": formClassName
    }), [(0, _propsUtil.getSlot)(this)]);
  }
};
var _default = Form;
exports.default = _default;