<template>
  <div class="upload-container">
    <el-upload
      v-if="imageUrl.length <= 0"
      :data="dataObj"
      :multiple="false"
      :show-file-list="false"
      :headers="uploadHeaders"
      :on-success="handleImageSuccess"
      class="image-uploader"
      drag
      :action="uploadHost"
      :style="{ width: uploaderWidth}"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
    </el-upload>
    <div v-show="imageUrl.length>1 && showPreview" class="image-preview">
      <div class="image-preview-wrapper">
        <img :src="imageUrl">
        <div class="image-preview-action">
          <i class="el-icon-delete" @click="rmImage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import store from '@/store'

export default {
  name: 'SingleImageUpload',
  props: {
    value: {
      type: String,
      default: ''
    },
    showPreview: {
      type: Boolean,
      default: true
    },
    uploaderWidth: {
      type: String,
      default: '100%'
    },
    imageType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadHost: process.env.VUE_APP_BASE_API + '/api/files/upload',
      dataObj: { token: '', key: '' }
    }
  },
  computed: {
    imageUrl() {
      return this.value
    },
    uploadHeaders() {
      return {
        'Authorization': store.getters.token
      }
    }
  },
  methods: {
    rmImage() {
      this.emitInput('')
      this.$emit('success', { fileUrl: '', imageType: this.imageType })
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    handleImageSuccess(response) {
      this.emitInput(response.url)
      this.$emit('success', { fileUrl: response.url, imageType: this.imageType })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "src/styles/mixin";
  .upload-container {
    width: 100%;
    position: relative;
    @include clearfix;
    .image-uploader {
      width: 20%;
      float: left;
    }
    .image-preview {
      width: 300px;
      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, .5);
        transition: opacity .3s;
        cursor: pointer;
        text-align: center;
        line-height: 200px;
        .el-icon-delete {
          font-size: 36px;
        }
      }
      &:hover {
        .image-preview-action {
          opacity: 1;
        }
      }
    }
  }

</style>
