<template lang="pug">
  div.form-tab-pane.relative(v-show="visible")
    slot
</template>

<script>
import { triggerResize } from '@/utils/dom-utils';
import _ from 'lodash';
export default {
  name: 'form-tab-pane',
  props: {
    label: String,
    name: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      default() {
        return false;
      }
    },
    errorCount: Number
  },
  mounted() {
    this.findFormComp();
    this.listenError();
  },
  data() {
    return {
      visible: false,
      invalid: this.errorCount || 0,
      formComp: []
    };
  },
  watch: {
    errorCount(nv) {
      this.invalid = nv || 0;
    },
    visible(nv) {
      if (nv) {
        triggerResize();
      }
    }
  },
  methods: {
    listenError() {
      if (this.formComp) {
        let fields = _.flatMap(this.formComp, a => a.fields);
        _.each(fields, formItem => {
          if (formItem._validUnwatch) {
            formItem._validUnwatch();
          }
          formItem._validUnwatch = formItem.$watch('validateState', (nv) => {
            this.invalid = _.filter(fields, field => field.validateState === 'error').length;
          });
        });
      }
    },
    findFormComp(children) {
      const items = children || this.$children;
      _.each(items, item => {
        if (item.$options.name === 'iForm') {
          this.formComp.push(item);
        }
        if (!_.isEmpty(item.$children)) {
          this.findFormComp(item.$children);
        }
      });
    }
  }
};
</script>
