<template>
  <div class="form-form">
    <el-form v-bind="options" ref="form" :model="ruleForm" @submit.native.prevent v-on="$listeners">
      <template v-for="item in items">
        <component :is="item.type" v-bind:key="item.model" :item="item" :formData="ruleForm"></component>
      </template>
      <el-form-item v-if="hasButton">
        <slot>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </slot>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'FormForm',
  componentName: 'FormForm',
  props: {
    options: {
      type: Object,
      default() {
        return {}
      }
    },
    model: {
      type: Object,
      default() {
        return {}
      }
    },
    items: {
      type: Array,
      default() {
        return []
      }
    },
    hasButton: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      ruleForm: {}
    }
  },
  watch: {
    model: {
      immediate: true,
      deep: true,
      handler(value) {
        this.ruleForm = value
      }
    }
  },
  computed: {
    $form() {
      return this.$refs['form']
    }
  },
  methods: {
    validate() {
      return this.$form.validate(...arguments)
    },
    validateField() {
      return this.$form.validateField(...arguments)
    },
    resetFields() {
      return this.$form.resetFields(...arguments)
    },
    clearValidate() {
      return this.$form.clearValidate(...arguments)
    },
    onSubmit() {
      this.validate().then(() => {
        this.$emit('onSubmit', this.model)
      })
    }
  }
}
</script>
