<template>
  <div class="upload-container">
    <el-upload
      class="image-uploader"
      action="/admin/upload"
      :headers="{ 'x-token': token }"
	  :multiple="false"
      :show-file-list="false"
	  drag
      :on-success="handleImageSuccess"
      :before-upload="beforeImageUpload"
    >
		<i class="el-icon-upload"  />
		<div class="el-upload__text" >
		  <span v-if="placeholder"> <em>{{placeholder}}</em> </span>
		  <span v-else> 拖动或<em>点击上传</em> </span>
		</div>
		
		<div class="image-preview" v-show="imageUrl.length>1">
		  <div  class="image-preview-wrapper">
			<img :src="imageUrl">
<!-- 			<div class="image-preview-action">
			  <i class="el-icon-delete" @click="rmImage" />
			</div> -->
		  </div>
		</div>
    </el-upload>
  </div>
</template>
<script>
const path = process.env.VUE_APP_BASE_API;
import { mapGetters } from "vuex";
import ImageCompress from "@/utils/image.js";
export default {
  name: "upload-image",
  model: {
    prop: "imageUrl",
    event: "change",
  },
  props: {
    imageUrl: {
      type: String,
      default: "",
    },
	placeholder:{
		type: String,
		default: "",
	},
    fileSize: {
      type: Number,
      default: 2048, // 2M 超出后执行压缩
    },
    maxWH: {
      type: Number,
      default: 1920, // 图片长宽上限
    },
  },
  data() {
    return {
      path: path,
    };
  },
  computed: {
    ...mapGetters("user", ["userInfo", "token"]),
  },
  methods: {
    beforeImageUpload(file) {
      let isRightSize = file.size / 1024 < this.fileSize;
      if (!isRightSize) {
        let compress = new ImageCompress(file, this.fileSize, this.maxWH);
        return compress.compress();
      }
      return isRightSize;
    },
	rmImage( ){
		this.$emit("rmImage");
	},
    handleImageSuccess(res) {
      const {  data } = res;
      if (data) {
        this.$emit("change", data.url);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-container {
  width: 100%;
  height: 100%;
  position: relative;
  .image-uploader {
    height: 100%;
  }
  .image-preview {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0px;
    top: 0px;
    border: 1px dashed #d9d9d9;
    .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>
