<template>
  <div class="device-section">
    <div v-for="formData in formDataList" :key="formData.key" class="section">
      <i v-if="formDataList.length > 1" class="el-icon-close remove" title="移除该项" @click="removeOne(formData)" />
      <el-form :ref="'form' + formData.uuid" label-width="90px" :model="formData" :rules="rules">
        <el-form-item label="设备名称:" prop="equipmentName">
          <el-input v-model="formData.equipmentName" placeholder="设备名称" :maxlength="50" type="text" />
        </el-form-item>
        <el-form-item label="所属品牌:" prop="brand">
          <el-input v-model="formData.brand" placeholder="所属品牌" />
        </el-form-item>
        <el-form-item label="设备图片:" prop="image">
          <el-input v-show="false" v-model="formData.image" placeholder="设备图片" />
          <upload-image
            tip="建议尺寸：542px * 542px"
            :image-list="formData.imageList"
            :before-upload="beforeImageUpload"
            @success="uploadImageSuccess($event, formData)"
            @remove="handleImageRemove($event, formData)"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" size="mini" round @click="insertOne">添加设备</el-button>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage'
export default {
  name: 'DeviceSection',
  components: {
    UploadImage
  },
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      uuid: 0, // key
      formDataList: [],
      rules: {
        equipmentName: [{ required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }],
        brand: [{ required: true, message: '所属品牌不能为空', trigger: ['blur', 'change'] }],
        image: [{ required: true, message: '请上传设备图片', trigger: 'change' }]
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // 监听表单数据列表边变化
      this.$watch(
        () => this.formDataList,
        newVal => {
          this.$emit('change', newVal)
        }, { deep: true }
      )
      // 初始化表单列表
      this.initFormData()
    },
    // 表单验证
    valideAllForm() {
      const validateList = []
      for (const key in this.$refs) {
        if (key.indexOf('form') > -1 && Object.hasOwnProperty.call(this.$refs, key)) {
          const form = this.$refs[key][0]
          if (form) {
            validateList.push(form.validate())
          }
        }
      }
      return Promise.all(validateList)
    },
    // 初始化表单
    initFormData() {
      if (this.list.length <= 0) {
        this.insertOne()
      } else {
        this.formDataList = this.makeUuid(this.list)
      }
    },
    // 出入一条表单数据
    insertOne() {
      this.uuid++
      this.formDataList.push({
        uuid: this.uuid,
        equipmentName: '',
        brand: '',
        image: '',
        imageList: []
      })
    },
    // 删除一条表单数据
    removeOne(formData) {
      const findIndex = this.formDataList.findIndex(item => item.uuid === formData.uuid)
      this.formDataList.splice(findIndex, 1)
      console.log(this.formDataList)
    },
    // 初始化列表uuid
    makeUuid(list = []) {
      return list.map((item, index) => {
        const obj = { uuid: index, imageList: [], ...item }
        if (item.image) {
          obj.imageList.push({ name: '', url: item.image })
        }
        return obj
      })
    },
    // 设备图片上传
    uploadImageSuccess({ response, file, fileList }, current) {
      current.image = response.data
      current.imageList.splice(0, current.imageList.length, ...fileList)
    },
    // 设备图片移除
    handleImageRemove({ file, fileList }, current) {
      current.image = ''
      current.imageList.splice(0, current.imageList.length, ...fileList)
    },
    // 上传图片限制
    beforeImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('上传banner图片大小不能超过 1MB!')
      }
      return flag
    }
  }
}
</script>

<style scoped lang="scss">
.device-section {
  .section {
    position: relative;
    border: 1px solid #eee;
    padding: 25px 25px 0 16px;
    margin-bottom: 16px;
    .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;
      }
    }
  }
  .el-form-item {
    padding-bottom: 25px;
  }
}
</style>
