<template>
  <div class="x-upload">
    <div class="upload-container">
      <label class="upload-icon" for="upload-file">
        <Plus></Plus>
      </label>
      <input
        class="upload-input"
        id="upload-file"
        type="file"
        accept="image/*"
        @change="tirggerFile($event)"
      />
      <div v-if="imgSrc" class="upload-img">
        <img :src="imgSrc" />
        <div class="mask">
          <CloseLittle size="20"  @click="deleteImgSrc"></CloseLittle>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Plus, CloseLittle } from '@nutui/icons-vue';
import { showDialog } from "@nutui/nutui";


export default {
  name: "XImgUpload",
  components: {
    Plus,
    CloseLittle
  },
  data() {
    return {
      imgFile: [],
      imgSrc: "",
    };
  },
  methods: {
    tirggerFile(evnet) {
      let isLt8M = evnet.target.files[0].size / 1024 / 1024 < 8;
      if(!isLt8M) {
        showDialog({
          title: '温馨提示',
          content: '图片大小不能大于8M',
          noCancelBtn: true
        })
        return false;
      }
      this.imgFile = evnet.target.files;
      let url = "";
      //创建reader对象
      let reader = new FileReader();
      //传入文件 （参数必须是blob对象）
      reader.readAsDataURL(this.imgFile[0]);
      //加载完成
      reader.onloadend = (event) => {
        // url = reader
        this.imgSrc = reader.result;
      };
      this.$emit('onImgChange', this.imgFile)
    },
    deleteImgSrc() {
      (this.imgFile = []), (this.imgSrc = "");
      this.$emit('onImgChange', this.imgFile)
    },
  },
}
</script>


<style scoped>
.x-upload {
}
.upload-container {
  width: 100px;
  height: 100px;
  position: relative;
  overflow: hidden;
  border: 1px dashed;
  border-radius: 5px;
  color: #999;
  cursor: pointer;
  z-index: 1;
}
.upload-container:hover, .upload-container:active {
  color: #3576ff;
}
.upload-icon {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.upload-input {
  display: none !important;
}

.upload-img {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}
.upload-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s ease-out;
  cursor: pointer;
  z-index: 999;
}
.mask:hover {
  opacity: 1;
}


</style>
