<template>
  <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
    <div v-for="(item, index) in meta" :key="index" >
      <el-form-item :label="item.title" :prop="item.name" v-if="!item.slots || item.slots == 'field'">
        <slot name="field" v-if="item.slots" v-bind="{ item, form }"></slot>
        <el-input :size="item.size || 'mini'" v-if="!item.formatter && !item.slots && item.type !== 'number'" v-model="form[item.name]" :placeholder="item.placeholder || `请输入${item.title}`" :disabled="item.disabled"></el-input>
        <el-input :size="item.size || 'mini'" v-if="!item.formatter && !item.slots && item.type == 'number'" v-model.number="form[item.name]" :placeholder="item.placeholder || `请输入${item.title}`" :disabled="item.disabled"></el-input>
        <el-select :size="item.size || 'mini'" v-if="item.formatter && !item.slots" v-model="form[item.name]" :placeholder="item.placeholder || `请选择${item.title}`" :disabled="item.disabled">
          <el-option v-for="(i, idx) in $dict(item.formatter)" :key="idx" :label="i.title" :value="i.value"></el-option>
        </el-select>
      </el-form-item>
      <slot name="end" v-if="item.slots == 'end'" v-bind="{ item, form }"></slot>
    </div>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      <el-button v-if="isresetForm" @click="resetForm('ruleForm')">重置</el-button>
      <el-button v-if="close" @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  components: {},
  props: {
    rules: Object,
    meta: Array,
    data: Object,
    isresetForm: {
      type: Boolean,
      default: false
    },
    close: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: {}
    }
  },
  methods: {
    reset () {
      this.form = { ...this.data }
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.meta.filter(p => {
            if (p.formatter) {
              const items = this.$dict(p.formatter)
              const item = items.filter(z => z.title === this.form[p.name])
              if (item.length > 0) this.form[p.name] = item[0].value
            }
          })
          this.$emit('save', this.form)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    formChage (name, val) {
      this.$set(this.form, name, val)
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    clearValidate (formName) {
      this.$refs.ruleForm.clearValidate()
    }
  },
  mounted () {
    this.reset()
  }
}
</script>

<style lang="less" scoped></style>
