<template>
  <div>
    <div v-if="value" class="upload-file">
      <img
        class="el-upload-list__item-thumbnail"
        :src="value"
        alt=""
      >
      <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-delete"
          @click="removeImage"
        >
          <i class="el-icon-delete" />
        </span>
      </span>
    </div>
    <el-upload
      v-else
      drag
      action=""
      :http-request="uploadFile"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传 jpg/png 文件，且不超过 2Mb</div>
    </el-upload>
  </div>
</template>

<script>
import { imageWithWatermark } from '@/api/components/file'
import moment from 'moment'

export default {
  name: 'UploadSingle',
  props: {
    // eslint-disable-next-line vue/require-default-prop
    value: {
      type: [String, null],
      default: () => ''
    },
    watermarkText: {
      type: [String, null],
      default: () => ''
    },
    dateTime: {
      type: [String, null],
      default: () => ''
    }
  },
  computed: {
    visible() {
      return this.value && this.value.length > 0
    }
  },
  methods: {
    removeImage() {
      this.$emit('update:value', '')
    },
    uploadFile(http) {
      if (this.dateTime == null || this.dateTime === '' || this.dateTime === 'null') {
        this.$message.info('请选择时间！')
        return
      }
      const reader = new FileReader()
      reader.readAsDataURL(http.file)
      reader.onload = e => {
        const result = e.target.result.replace(/^data:image\/\w+;base64,/, '')
        // cb ? cb(e.target.result) : null
        const params = {
          fileData: result,
          fileName: http.file.name,
          text: this.watermarkText + '|' + moment(this.dateTime).format('YYYY-MM-DD HH:mm:ss')
        }
        imageWithWatermark(params)
          .then(res => {
            const { data } = res
            this.$emit('update:value', data.url)
          })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.upload-file{
    width: 360px;
    position: relative;
    img{
      width: 100%;
      display: block;
    }
    .el-upload-list__item-actions{
      line-height: 180px;
      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;
      .el-upload-list__item-delete{
        position: static;
        font-size: inherit;
        color: inherit;
      }
      span{
        display: inline-block;
        cursor: pointer;
      }
      span + span {
        margin-left: 15px;
      }
    }
    .el-upload-list__item-actions:hover{
      opacity: 1;
    }
  }
</style>
