<template>
  <div class="upload-container">
    <el-upload
      :multiple="false"
      :data="dataObj"
      name="files"
      :file-list="annexfileList"
      :action="uploadPath"
      :headers="{ token }"
      :before-upload="annexBeforeUpload"
      :on-success="uploadDone"
      class="btn"
    >
      <el-button v-if="showBtn" class="uploadButton" icon="el-icon-upload2">{{ 'btn.upload' | i18nFilter }}</el-button>
      <span v-if="fileId" slot="tip" class="el-upload__tip" @click="downloadFile">下载文件</span>
    </el-upload>
  </div>
</template>

<script>
import { cloudPath, uploadPath } from '@/api/basic'
import { getToken } from '@/utils/auth'

export default {
  name: 'SingleFileUpload',
  props: {
    fileId: {
      type: String,
      default: () => null
    },
    showBtn: {
      type: Boolean,
      default: () => true
    }
  },
  data() {
    return {
      tempUrl: '',
      dataObj: { typeCode: 'file' },
      uploadPath,
      cloudPath,
      imageUrl: null,
      token: getToken(),
      imgload: false,
      annexfileList: []
    }
  },
  // watch: {
  //   fileId: function(val) {
  //     if (val) {
  //       getUrl({
  //         attachmentId: val,
  //         type: 0
  //       }).then(blob => {
  //         blobToBase64(blob.data).then(res => {
  //           this.imageUrl = res
  //         })
  //       })
  //     }
  //   }
  // },
  methods: {
    rmImage() {
      this.$confirm(this.$t('upload.delPic'), '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imageUrl = null
        this.emitInput(false)
      })
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    uploadDone(res) {
      console.log(res)
      if (res.code === 0) {
        this.$emit('done', res.data[0].id)
      } else {
        this.$message({
          type: 'error',
          message: '上传失败!'
        })
      }
    },
    annexBeforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
      }
      return isRightSize
    },
    downloadFile() {
      window.open(`${location.origin}/api/common/attachment/downloadFile?type=file&attachmentId=${this.fileId}`)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/index.scss";
.upload-container {
  overflow: hidden;
  .btn {
    float: left;
  }
  .el-upload__tip {
    @extend .pointer;
  }
}
.uploadButton{
width: 106px;
height: 32px;
background: #FFFFFF;
border-radius: 4px;
border: 1px solid #D9D9D9;
}
</style>
