<template>
  <div>
    <div class="img-view" v-if="dialogImageUrl">
      <img :src="dialogImageUrl" alt="" srcset="" />
    </div>
    <div class="placeholder-box" v-else>
      <img src="~@/assets/img/upload-placeholder.svg" alt="" />
    </div>
    <div class="btn-box">
      <el-upload
        class="avatar-div"
        action="#"
        :show-file-list="false"
        ref="uploadRef"
        :on-exceed="handleExceed"
        :limit="1"
        :http-request="handlSuccess"
        :multiple="false"
      >
        <el-button type="text">上传{{assetName}}图片</el-button>
      </el-upload>
      <el-button type="text" @click="clearImg">清除图片</el-button>
    </div>
  </div>
</template>

<script>
import common from '@/api/data'
export default {
  props: {
    assetName:{
      type:String,
      default:'设备'
    },
    dialogImage:{
      type:String,
      default:''
    },
  },
  data () {
    return {
      dialogImageUrl: ''
    }
  },
  watch: {
    dialogImage (val) {
      if (val) {
         this.dialogImageUrl = val
      }
    }
  },
  methods: {
    setImg(url){
      this.dialogImageUrl = url
    },
    // 清空已上传的文件列表
    clearUploadFiles () {},
    //图片添加
    handlSuccess (param) {
      console.log(param)

      const fd = new FormData()
      fd.append('file', param.file)
      fd.append('module', this.module)
      let res = common.upload(fd)
      if (res?.success) {
        // console.log("添加上传：", res);
        let info = res.data
        info.type = info.type.id
        this.$emit('getImgs', [info])
        this.dialogImageUrl = window.URL.createObjectURL(new Blob([param.file]))
      }
    },
    clearImg () {
      this.$emit('getImgs', [])
      this.$refs.uploadRef.clearFiles()
      this.dialogImageUrl = ''
    },
    // 限制上传的数量
    handleExceed (files, fileList) {
      console.log(111)
      this.$message.warning(`最多允许上传一张图片！`)
    }
  }
}
</script>
<style lang="scss" scoped>
.img-view {
  width: 280px;
  height: 342px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(215, 215, 215, 1);
  img {
    max-width: 100%;
  }
}
.placeholder-box {
  width: 280px;
  height: 342px;
  text-align: center;

  background-color: rgba(242, 242, 242, 1);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(215, 215, 215, 1);
  padding-top: 60px;
  img {
    width: 158px;
    height: 158px;
  }
}

.btn-box {
  display: flex;
  justify-content: space-around;
}
</style>
