/**
 * tdesign v0.32.0
 * (c) 2021 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var Vue = require('vue');
var isEmpty = require('lodash/isEmpty');
var config = require('../config.js');
var form_props = require('./props.js');
var form_const = require('./const.js');
var utils_event = require('../utils/event.js');
require('../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('lodash/camelCase');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var Vue__default = /*#__PURE__*/_interopDefaultLegacy(Vue);
var isEmpty__default = /*#__PURE__*/_interopDefaultLegacy(isEmpty);

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var name = "".concat(config.prefix, "-form");
var _Form = Vue__default["default"].extend({
  name: "TForm",
  props: _objectSpread({}, form_props["default"]),
  provide: function provide() {
    return {
      form: this
    };
  },
  data: function data() {
    return {
      children: []
    };
  },
  computed: {
    formClass: function formClass() {
      return [form_const.CLASS_NAMES.form, _defineProperty__default["default"]({}, "".concat(name, "-inline"), this.layout === "inline")];
    }
  },
  created: function created() {
    var _this = this;

    this.$on("form-item-created", function (formItem) {
      _this.children.push(formItem);
    });
    this.$on("form-item-destroyed", function (formItem) {
      var index = _this.children.findIndex(function (item) {
        return item === formItem;
      });

      _this.children.splice(index, 1);
    });
  },
  methods: {
    getFirstError: function getFirstError(r) {
      if (r === true) return;

      var _Object$keys = Object.keys(r),
          _Object$keys2 = _slicedToArray__default["default"](_Object$keys, 1),
          firstKey = _Object$keys2[0];

      if (this.scrollToFirstError) {
        this.scrollTo(".".concat(form_const.FORM_ITEM_CLASS_PREFIX + firstKey));
      }

      return r[firstKey][0].message;
    },
    scrollTo: function scrollTo(selector) {
      var dom = this.$el.querySelector(selector);
      var behavior = this.scrollToFirstError;
      dom && dom.scrollIntoView({
        behavior: behavior
      });
    },
    isFunction: function isFunction(val) {
      return typeof val === "function";
    },
    needValidate: function needValidate(name2, fields) {
      if (!fields || !Array.isArray(fields)) return true;
      return fields.indexOf(name2) !== -1;
    },
    validate: function validate(param) {
      var _this2 = this;

      return _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
        var _ref2, fields, _ref2$trigger, trigger, list, arr, r, result;

        return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _ref2 = param || {}, fields = _ref2.fields, _ref2$trigger = _ref2.trigger, trigger = _ref2$trigger === void 0 ? "all" : _ref2$trigger;
                list = _this2.children.filter(function (child) {
                  return _this2.isFunction(child.validate) && _this2.needValidate(child.name, fields);
                }).map(function (child) {
                  return child.validate(trigger);
                });
                _context.next = 4;
                return Promise.all(list);

              case 4:
                arr = _context.sent;
                r = arr.reduce(function (r2, err) {
                  return Object.assign(r2 || {}, err);
                });
                Object.keys(r).forEach(function (key) {
                  if (r[key] === true) {
                    delete r[key];
                  } else {
                    r[key] = r[key].filter(function (fr) {
                      return fr.result === false;
                    });
                  }
                });
                result = isEmpty__default["default"](r) ? true : r;
                utils_event.emitEvent(_this2, "validate", {
                  validateResult: result,
                  firstError: _this2.getFirstError(result)
                });
                return _context.abrupt("return", result);

              case 10:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }))();
    },
    submitHandler: function submitHandler(e) {
      var _this3 = this;

      if (this.preventSubmitDefault) {
        e && e.preventDefault();
        e && e.stopPropagation();
      }

      this.validate().then(function (r) {
        utils_event.emitEvent(_this3, "submit", {
          validateResult: r,
          firstError: _this3.getFirstError(r),
          e: e
        });
      });
    },
    resetHandler: function resetHandler(e) {
      var _this4 = this;

      if (this.preventSubmitDefault) {
        e && e.preventDefault();
        e && e.stopPropagation();
      }

      this.children.filter(function (child) {
        return _this4.isFunction(child.resetField);
      }).map(function (child) {
        return child.resetField();
      });
      utils_event.emitEvent(this, "reset", {
        e: e
      });
    },
    clearValidate: function clearValidate(fields) {
      var _this5 = this;

      this.children.forEach(function (child) {
        if (_this5.isFunction(child.resetHandler) && _this5.needValidate(child.name, fields)) {
          child.resetHandler();
        }
      });
    },
    reset: function reset() {
      this.resetHandler();
    },
    submit: function submit() {
      this.submitHandler();
    }
  },
  render: function render() {
    var h = arguments[0];
    var on = {
      submit: this.submitHandler,
      reset: this.resetHandler
    };
    return h("form", {
      "ref": "form",
      "class": this.formClass,
      "on": _objectSpread({}, on)
    }, [this.$slots["default"]]);
  }
});

exports["default"] = _Form;
//# sourceMappingURL=form.js.map
