/**
 * tdesign v0.39.1-alpha.1
 * (c) 2022 tdesign
 * @license MIT
 */

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import Vue from 'vue';
import isEmpty from 'lodash/isEmpty';
import { prefix } from '../config.js';
import props from './props.js';
import { CLASS_NAMES, FORM_CONTROLE_COMPONENTS, FORM_ITEM_CLASS_PREFIX } from './const.js';
import { emitEvent } from '../utils/event.js';
import '../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'lodash/camelCase';

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(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(prefix, "-form");
var _Form = Vue.extend({
  name: "TForm",
  props: _objectSpread({}, props),
  provide: function provide() {
    return {
      form: this
    };
  },
  data: function data() {
    return {
      children: []
    };
  },
  computed: {
    formClass: function formClass() {
      return [CLASS_NAMES.form, _defineProperty({}, "".concat(name, "-inline"), this.layout === "inline")];
    },
    controlledComponents: function controlledComponents() {
      var _this$formControlledC;

      var fields = FORM_CONTROLE_COMPONENTS;

      if ((_this$formControlledC = this.formControlledComponents) !== null && _this$formControlledC !== void 0 && _this$formControlledC.length) {
        fields = fields.concat(this.formControlledComponents);
      }

      return fields;
    }
  },
  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(_Object$keys, 1),
          firstKey = _Object$keys2[0];

      if (this.scrollToFirstError) {
        this.scrollTo(".".concat(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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _ref2, fields, _ref2$trigger, trigger, list, arr, r, result;

        return _regeneratorRuntime.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(r) ? true : r;
                emitEvent(_this2, "validate", {
                  validateResult: result,
                  firstError: _this2.getFirstError(result)
                });
                return _context.abrupt("return", result);

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

      var keys = Object.keys(validateMessage || {});
      if (!keys.length) return;
      var list = this.children.filter(function (child) {
        return _this3.isFunction(child.setValidateMessage) && keys.includes(child.name);
      }).map(function (child) {
        return child.setValidateMessage(validateMessage[child.name]);
      });
      Promise.all(list);
    },
    submitHandler: function submitHandler(e) {
      var _this4 = this;

      if (this.preventSubmitDefault) {
        e === null || e === void 0 ? void 0 : e.preventDefault();
        e === null || e === void 0 ? void 0 : e.stopPropagation();
      }

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

      if (this.preventSubmitDefault) {
        e === null || e === void 0 ? void 0 : e.preventDefault();
        e === null || e === void 0 ? void 0 : e.stopPropagation();
      }

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

      this.children.forEach(function (child) {
        if (_this6.isFunction(child.resetHandler) && _this6.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"]]);
  }
});

export { _Form as default };
//# sourceMappingURL=form.js.map
