/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

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

var isEmpty = require('lodash/isEmpty');
var utils_event = require('../../utils/event.js');
var components_configProvider_configReceiver = require('../config-provider/config-receiver.js');
var utils_mixins = require('../../utils/mixins.js');
var components_form_props = require('./props.js');
var components_form_const = require('./const.js');
require('../../utils/helper.js');
require('lodash/camelCase');
require('vue');
require('lodash/mergeWith');
require('lodash');
require('../config-provider/context.js');
require('../../chunks/zh_CN.js');
require('../../config.js');

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

var isEmpty__default = /*#__PURE__*/_interopDefaultLegacy(isEmpty);

const classPrefixMixins = components_configProvider_configReceiver.getClassPrefixMixins("form");
var _Form = utils_mixins["default"](classPrefixMixins).extend({
  name: "LForm",
  props: {
    ...components_form_props.FormProps
  },
  provide() {
    return {
      form: this
    };
  },
  data() {
    return {
      children: []
    };
  },
  computed: {
    formClass() {
      return [this.componentName, {
        [`${this.componentName}-inline`]: this.layout === "inline"
      }];
    },
    controlledComponents() {
      var _this$formControlledC;
      let fields = components_form_const.FORM_CONTROL_COMPONENTS;
      if ((_this$formControlledC = this.formControlledComponents) !== null && _this$formControlledC !== void 0 && _this$formControlledC.length) fields = fields.concat(this.formControlledComponents);
      return fields;
    }
  },
  created() {
    this.$on("form-item-created", formItem => {
      this.children.push(formItem);
    });
    this.$on("form-item-destroyed", formItem => {
      const index = this.children.findIndex(item => item === formItem);
      this.children.splice(index, 1);
    });
  },
  methods: {
    getFirstError(r) {
      if (r === true) return;
      const [firstKey] = Object.keys(r);
      if (this.scrollToFirstError) this.scrollTo(`.${this.componentName}-item__${firstKey}`);
      return r[firstKey][0].message;
    },
    scrollTo(selector) {
      const dom = this.$el.querySelector(selector);
      const behavior = this.scrollToFirstError;
      dom && dom.scrollIntoView({
        behavior
      });
    },
    isFunction(val) {
      return typeof val === "function";
    },
    needValidate(name, fields) {
      if (!fields || !Array.isArray(fields)) return true;
      return fields.includes(name);
    },
    formatValidateResult(arr) {
      const r = arr.reduce((r2, err) => Object.assign(r2 || {}, err));
      Object.keys(r).forEach(key => {
        if (r[key] === true) delete r[key];else r[key] = r[key].filter(fr => fr.result === false);
      });
      return isEmpty__default["default"](r) ? true : r;
    },
    async validate() {
      let param = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
        showErrorMessage: true
      };
      let source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "submit-function";
      const {
        fields,
        trigger = "all"
      } = param || {};
      const list = this.children.filter(child => this.isFunction(child.validate) && this.needValidate(String(child.name), fields)).map(child => child.validate(trigger, param.showErrorMessage, source));
      const arr = await Promise.all(list);
      const result = this.formatValidateResult(arr);
      utils_event.emitEvent(this, "validate", {
        validateResult: result,
        firstError: this.getFirstError(result)
      });
      return result;
    },
    async validateOnly(param) {
      const {
        fields,
        trigger = "all"
      } = param || {};
      const list = this.children.filter(child => this.isFunction(child.validate) && this.needValidate(String(child.name), fields)).map(child => child.validateOnly(trigger));
      const arr = await Promise.all(list);
      const result = this.formatValidateResult(arr);
      return result;
    },
    setValidateMessage(validateMessage) {
      const keys = Object.keys(validateMessage || {});
      if (!keys.length) return;
      const list = this.children.filter(child => this.isFunction(child.setValidateMessage) && keys.includes(String(child.name))).map(child => child.setValidateMessage(validateMessage[child.name]));
      Promise.all(list);
    },
    submitHandler(e) {
      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(r => {
        utils_event.emitEvent(this, "submit", {
          validateResult: r,
          firstError: this.getFirstError(r),
          e
        });
      });
    },
    resetHandler(e) {
      if (this.preventSubmitDefault) {
        e === null || e === void 0 ? void 0 : e.preventDefault();
        e === null || e === void 0 ? void 0 : e.stopPropagation();
      }
      this.children.filter(child => this.isFunction(child.resetField)).forEach(child => child.resetField(this.resetType || "initial"));
      utils_event.emitEvent(this, "reset", {
        e
      });
    },
    clearValidate(fields) {
      this.children.forEach(child => {
        if (this.isFunction(child.resetHandler) && this.needValidate(String(child.name), fields)) child.resetHandler();
      });
    },
    reset() {
      let params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.children.filter(child => this.isFunction(child.resetField)).forEach(child => {
        const resetType = params.type || this.resetType || "initial";
        if (!params.fields || params.fields && params.fields.includes(child.name)) child.resetField(resetType);
      });
      utils_event.emitEvent(this, "reset", {
        e: void 0
      });
    },
    submit(params) {
      this.validate({
        showErrorMessage: params === null || params === void 0 ? void 0 : params.showErrorMessage
      }, "submit-function").then(r => {
        utils_event.emitEvent(this, "submit", {
          validateResult: r,
          firstError: this.getFirstError(r)
        });
      });
    }
  },
  render() {
    const h = arguments[0];
    const on = {
      submit: this.submitHandler,
      reset: this.resetHandler
    };
    return h("form", {
      "ref": "form",
      "class": this.formClass,
      "on": {
        ...on
      }
    }, [this.$slots.default]);
  }
});

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