/**
 * ldesign v0.4.6
 * (c) 2023 ldesign
 * @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 isEmpty from 'lodash/isEmpty';
import keys from 'lodash/keys';
import { emitEvent } from '../utils/event.js';
import { getClassPrefixMixins } from '../config-provider/config-receiver.js';
import mixins from '../utils/mixins.js';
import props from './props.js';
import { FORM_CONTROL_COMPONENTS } from './const.js';
import '../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'lodash/camelCase';
import 'vue';
import 'lodash/mergeWith';
import '../config-provider/context.js';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '@babel/runtime/helpers/typeof';
import '../_chunks/dep-be599ec8.js';
import 'dayjs';
import '../_chunks/dep-67ff4010.js';
import '../config-provider/type.js';

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 classPrefixMixins = getClassPrefixMixins("form");
var _Form = mixins(classPrefixMixins).extend({
  name: "TForm",
  props: _objectSpread({}, props),
  provide: function provide() {
    return {
      form: this
    };
  },
  data: function data() {
    return {
      children: []
    };
  },
  computed: {
    formClass: function formClass() {
      return [this.componentName, _defineProperty({}, "".concat(this.componentName, "-inline"), this.layout === "inline")];
    },
    controlledComponents: function controlledComponents() {
      var _this$formControlledC;
      var fields = FORM_CONTROL_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(this.componentName, "-item__").concat(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(name, fields) {
      if (!fields || !Array.isArray(fields)) return true;
      return fields.includes(name);
    },
    formatValidateResult: function formatValidateResult(arr) {
      if (!arr || !arr.length) return true;
      var 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;
        });
      });
      return isEmpty(r) ? true : r;
    },
    validate: function validate() {
      var _arguments = arguments,
        _this2 = this;
      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var param, source, _ref2, fields, _ref2$trigger, trigger, list, arr, result;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              param = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {
                showErrorMessage: true
              };
              source = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : "submit-function";
              _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(String(child.name), fields);
              }).map(function (child) {
                return child.validate(trigger, param.showErrorMessage, source);
              });
              _context.next = 6;
              return Promise.all(list);
            case 6:
              arr = _context.sent;
              result = _this2.formatValidateResult(arr);
              emitEvent(_this2, "validate", {
                validateResult: result,
                firstError: _this2.getFirstError(result)
              });
              return _context.abrupt("return", result);
            case 10:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }))();
    },
    validateOnly: function validateOnly(param) {
      var _this3 = this;
      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _ref3, fields, _ref3$trigger, trigger, list, arr, result;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _ref3 = param || {}, fields = _ref3.fields, _ref3$trigger = _ref3.trigger, trigger = _ref3$trigger === void 0 ? "all" : _ref3$trigger;
              list = _this3.children.filter(function (child) {
                return _this3.isFunction(child.validate) && _this3.needValidate(String(child.name), fields);
              }).map(function (child) {
                return child.validateOnly(trigger);
              });
              _context2.next = 4;
              return Promise.all(list);
            case 4:
              arr = _context2.sent;
              result = _this3.formatValidateResult(arr);
              return _context2.abrupt("return", result);
            case 7:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }))();
    },
    setValidateMessage: function setValidateMessage(validateMessage) {
      var _this4 = this;
      var keys2 = Object.keys(validateMessage || {});
      if (!keys2.length) return;
      var list = this.children.filter(function (child) {
        return _this4.isFunction(child.setValidateMessage) && keys2.includes(String(child.name));
      }).map(function (child) {
        return child.setValidateMessage(validateMessage[child.name]);
      });
      Promise.all(list);
    },
    submitHandler: function submitHandler(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.validate({
        showErrorMessage: true
      }, "submit-event").then(function (r) {
        emitEvent(_this5, "submit", {
          validateResult: r,
          firstError: _this5.getFirstError(r),
          e: e
        });
      });
    },
    resetHandler: function resetHandler(e) {
      var _this6 = this;
      if (this.preventSubmitDefault) {
        e === null || e === void 0 ? void 0 : e.preventDefault();
        e === null || e === void 0 ? void 0 : e.stopPropagation();
      }
      var fields = keys(this.data);
      this.children.filter(function (child) {
        return _this6.isFunction(child.resetField) && _this6.needValidate(String(child.name), fields);
      }).forEach(function (child) {
        return child.resetField(_this6.resetType || "initial");
      });
      emitEvent(this, "reset", {
        e: e
      });
    },
    clearValidate: function clearValidate(fields) {
      var _this7 = this;
      this.children.forEach(function (child) {
        if (_this7.isFunction(child.resetHandler) && _this7.needValidate(String(child.name), fields)) child.resetHandler();
      });
    },
    reset: function reset() {
      var _this8 = this;
      var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.children.filter(function (child) {
        return _this8.isFunction(child.resetField);
      }).forEach(function (child) {
        var resetType = params.type || _this8.resetType || "initial";
        if (!params.fields || params.fields && params.fields.includes(child.name)) child.resetField(resetType);
      });
      emitEvent(this, "reset", {
        e: void 0
      });
    },
    submit: function submit(params) {
      var _this9 = this;
      this.validate({
        showErrorMessage: params === null || params === void 0 ? void 0 : params.showErrorMessage
      }, "submit-function").then(function (r) {
        emitEvent(_this9, "submit", {
          validateResult: r,
          firstError: _this9.getFirstError(r)
        });
      });
    }
  },
  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
