import * as _vue from "vue";

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

import { inject, provide } from 'vue';
import PropTypes from '../_util/vue-types';
import classNames from '../_util/classNames';
import { ColProps } from '../grid/Col';
import isRegExp from 'lodash/isRegExp';
import warning from '../_util/warning';
import FormItem from './FormItem';
import { initDefaultProps, getSlot } from '../_util/props-util';
import { ConfigConsumerProps } from '../config-provider';
import { getNamePath, containsNamePath } from './utils/valueUtil';
import { defaultValidateMessages } from './utils/messages';
import { allPromiseFinish } from './utils/asyncUtil';
import { toArray } from './utils/typeUtil';
import isEqual from 'lodash/isEqual';
import scrollIntoView from 'scroll-into-view-if-needed';
export var FormProps = {
  layout: PropTypes.oneOf(['horizontal', 'inline', 'vertical']),
  labelCol: PropTypes.shape(ColProps).loose,
  wrapperCol: PropTypes.shape(ColProps).loose,
  colon: PropTypes.bool,
  labelAlign: PropTypes.oneOf(['left', 'right']),
  prefixCls: PropTypes.string,
  hideRequiredMark: PropTypes.bool,
  model: PropTypes.object,
  rules: PropTypes.object,
  validateMessages: PropTypes.any,
  validateOnRuleChange: PropTypes.bool,
  // 提交失败自动滚动到第一个错误字段
  scrollToFirstError: PropTypes.bool,
  onFinish: PropTypes.func,
  onFinishFailed: PropTypes.func,
  name: PropTypes.name,
  validateTrigger: PropTypes.oneOfType([PropTypes.string, PropTypes.array])
};
export var ValidationRule = {
  /** validation error message */
  message: PropTypes.string,

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

  /** indicates whether field is required */
  required: PropTypes.boolean,

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

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

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

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

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

  /** validate from a regular expression */
  pattern: PropTypes.custom(isRegExp),

  /** transform a value before validation */
  transform: PropTypes.func,

  /** custom validate function (Note: callback must be called) */
  validator: PropTypes.func
};

function isEqualName(name1, name2) {
  return isEqual(toArray(name1), toArray(name2));
}

var Form = {
  name: 'AForm',
  inheritAttrs: false,
  props: initDefaultProps(FormProps, {
    layout: 'horizontal',
    hideRequiredMark: false,
    colon: true
  }),
  Item: FormItem,
  created: function created() {
    this.fields = [];
    this.form = undefined;
    this.lastValidatePromise = null;
    provide('FormContext', this);
  },
  setup: function setup() {
    return {
      configProvider: inject('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 ? toArray(nameList).map(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) {
        warning(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) {
          scrollIntoView(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 = {};
        toArray(nameList).forEach(function (namePath) {
          return res[namePath] = values[namePath];
        });
        return res;
      }
    },
    validateFields: function validateFields(nameList, options) {
      var _this2 = this;

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

      if (!this.model) {
        warning(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 ? toArray(nameList).map(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 || containsNamePath(namePathList, fieldNamePath)) {
          var promise = field.validateRules(_objectSpread({
            validateMessages: _objectSpread(_objectSpread({}, 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 = 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 = classNames(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
    }), [getSlot(this)]);
  }
};
export default Form;