<template>
  <div class="upload-container">
    <el-upload class="image-uploader" action="#" :data="dataObj" drag :multiple="false" :limit="1" :show-file-list="false" :auto-upload="false" v-show="imageUrl==''" :http-request="onUploadRequest"  :on-success="onSuccess">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></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="changeImage" class="el-icon-delete"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadFile } from '@/api/website/newsCategory/index';
export default {
  name: "singleImageUpload",
  props: {
    value: String,
  },
  computed: {
    imageUrl() {
      return (!!this.value) ? this.value : '';
    },
  },
  data() {
    return {
      tempUrl: "",
      dataObj: { token: "", key: "" },
    };
  },
  methods: {
    changeImage(file="") {
      this.$emit("imagePreview",file)
    },
    onSuccess(){
      this.changeImage(this.tempUrl)
    },
    //上传请求
    onUploadRequest(data) {
      let fileObj = data.file;
      // FormData 对象
      let form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      uploadFile(form).then(res => {
        if (res.status == 200) {
          console.log(res.data)
        } else {
          this.$message.error(res.message)
        }
      })
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/mixin.scss";
.upload-container {
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  @include clearfix;
  .image-uploader {
    width: 60%;
    float: left;
  }
  .image-preview {
    width: 200px;
    height: 200px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
    .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>
