<template>
  <div class="doctor-custom-items">
    <div v-for="formData in formDataList" :key="formData.uuid" class="custom-section">
      <i class="el-icon-close remove" title="移除该项" @click="removeOne(formData)" />
      <el-form :ref="'form' + formData.uuid" :model="formData" :rules="rules" label-width="90px">
        <el-form-item label="字段名称" prop="name">
          <el-input v-model="formData.name" placeholder="字段名称" />
        </el-form-item>
        <el-form-item label="字段内容" prop="content">
          <el-input v-model="formData.content" type="textarea" placeholder="字段内容" rows="5" />
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" size="mini" round @click="insertOne">添加</el-button>
  </div>

</template>

<script>
export default {
  data() {
    return {
      uuid: 1,
      formDataList: [],
      rules: {
        name: [{ required: true, message: '字段名称不能为空', tiggers: ['blur'] }],
        content: [{ required: true, message: '字段内容不能为空', tiggers: ['blur'] }]
      }
    }
  },
  watch: {
    formDataList: {
      handler: function(nVal) {
        this.$emit('change', this.formDataList)
      },
      deep: true
    }
  },
  methods: {
    // 插入一条
    insertOne() {
      this.uuid++
      this.formDataList.push({
        uuid: this.uuid,
        name: '',
        content: ''
      })
    },
    setParamsItem(dataArray) {
      if (dataArray.length === 0) return
      this.formDataList = dataArray.map((item, index) => {
        this.uuid = index + 1
        return { ...item, uuid: this.uuid }
      })
    },
    // 删除一条
    removeOne(formData) {
      const uuid = formData.uuid
      const index = this.formDataList.findIndex(item => item.uuid === uuid)
      this.formDataList.splice(index, 1)
    },
    // 验证表单数据
    valideAllForm() {
      const validateList = []
      this.formDataList.forEach(formData => {
        const refName = 'form' + formData.uuid
        validateList.push(this.$refs[refName][0].validate())
      })
      return Promise.all(validateList)
    }
  }
}
</script>

<style lang="scss" scoped>
.doctor-custom-items{
  .custom-section{
    position: relative;
    border: 1px solid #eee;
    padding: 25px 25px 0 16px;
    margin-bottom: 16px;

    .el-form-item{
      padding-bottom: 25px;
    }

    .remove {
      position: absolute;
      right: 6px;
      top: 6px;
      font-size: 14px;
      cursor: pointer;
      background: #f56c6c;
      color: #fff;
      padding: 2px;
      border-radius: 50%;
      transition: all 0.2s;
      &:hover {
        background: red;
      }
    }
  }
}
</style>
