<template>
  <form
    :class="classes"
  >
    <slot />
  </form>
</template>

<script>
const name = 'hive-form';

export default {
  name,
  props: {
    /**
     * 表单项目列表
     */
    model: Object,
    /**
     * 定义规则
     */
    rules: Object,
    /**
     * 是否进行输入检查
     */
    errorLocation: Boolean,
    /**
     * 布局方式
     */
    layout: String,
    /**
     * 标签对齐方式
     * @member right
     */
    layoutAlign: String
  },
  provide() {
    return {
      form: this
    };
  },
  data() {
    return {
      fields: []
    };
  },
  computed: {
    classes() {
      return [
        `${name}`,
        {
          [`${name}--${this.layout}`]: this.layout,
          [`${name}-${this.size}`]: this.size
        }
      ];
    }
  },
  watch: {
    rules() {
      this.validate();
    }
  },

  created() {
    this.$on('form-item.add', (field) => {
      if (field) this.fields.push(field);
      return false;
    });
    this.$on('form-item.remove', (field) => {
      if (field.prop) this.fields.splice(this.fields.indexOf(field), 1);
      return false;
    });
  },

  methods: {
    validate(callback) {
      return new Promise(resolve => {
        let valid = true;
        let count = 0;
        this.fields.forEach(field => {
          field.validate('', errors => {
            if (errors) {
              valid = false;
            }
            if (++count === this.fields.length) {
              resolve(valid);
              if (typeof callback === 'function') {
                callback(valid, errors);
              }
            }
          });
        });
      });
    }
  }
};
</script>
