<template>
  <div class="upload-container">
    <el-upload
    v-show="!imageUrl"
      ref="upload"
      drag
      v-loading="uploading"
      action="#"
      :http-request="onUploadRequest"
      :show-file-list="false"
      :multiple="false"
      :limit="1">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__text">只能上传1个文件</div>
    </el-upload>
    <div class="image-preview" v-show="imageUrl">
      <div class="image-preview-wrapper">
        <img :src="imageUrl" />
        <div class="image-preview-action">
          <i @click="rmImage" class="el-icon-delete"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 预览效果见专题
import { uploadFile } from "@/api/website/newsCategory/index";
export default {
  name: "singleImageUpload2",
  props: {
    //图片地址
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploading: false
    };
  },
  computed: {
    imageUrl() {
      return (!!this.value) ? this.value : ""
    }
  },
  methods: {
    //删除图片
    rmImage() {
      this.$refs.upload.clearFiles()
      this.emitFunc("");
    },
    //上传请求
    onUploadRequest(data) {
      this.uploading = true;
      let fileObj = data.file;
      // FormData 对象
      let form = new FormData();
      // 文件对象
      form.append("file", fileObj);

      uploadFile(form).then(res => {
        this.uploading = false;

        if (res.status == 200) {
          this.emitFunc(res.data)
        } else {
          this.emitFunc("");
          this.$message.error(res.message)
        }
      })
    },
    //组件通信
    emitFunc(val) {
      this.$emit('input', val)
    }
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/mixin.scss";
.upload-container {
  width: 100%;
  display: flex;
  @include clearfix;
  .image-uploader {
    width: 60%;
    float: left;
  }
  .image-preview {
    width: 200px;
    height: 200px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    .image-preview-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .image-preview-action {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, 0.5);
      transition: opacity 0.3s;
      cursor: pointer;
      text-align: center;
      line-height: 200px;
      .el-icon-delete {
        font-size: 36px;
      }
    }
    &:hover {
      .image-preview-action {
        opacity: 1;
      }
    }
  }
}
</style>
