<template> 
  <div>
    <el-upload
      :data="dataObj"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList" 
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      action="http://hsz1997.oss-cn-beijing.aliyuncs.com/"
      list-type="picture">
      <el-button size="small">点击上传</el-button>
	
      <div slot="tip" class="el-upload__tip color">  {{ tips }}</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="fileList[0].url" width="100%" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { policy } from '@/api/oss'

export default {
  name: 'singleUpload',
  props: {
    value: {
      type: String
    },
    tips: {
      type: String,
      default: '支付扩展名:.rar .zip .doc .docx .pdf .jpg...'
    },
    max: {
      type: String,
      default: '99'
    }
  },

  data() {
    return {
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: ''
      },
      dialogVisible: false
    }
  },
  computed: {
    imageUrl() {
      return this.value
    },
    imageName() {
      if (this.value != null && this.value !== '') {
        return this.value.substr(this.value.lastIndexOf('/') + 1)
      } else {
        return null
      }
    },
    fileList() {
      return [{
        name: this.imageName,
        url: this.imageUrl
      }]
    },
    showFileList: {
      get: function() {
        return this.value !== null && this.value !== '' && this.value !== undefined
      },
      set: function(newValue) {
      }
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    handleRemove(file, fileList) {
      this.emitInput('')
    },
    handlePreview(file) {
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      const max = this.max
      if (!isLt2M) {
        this.$message.error(`上传附件大小不能超过 ${max} MB!`)
        return
      }
      let _self = this
      return new Promise((resolve, reject) => {
        policy().then(response => {
          console.log(response.data)
          _self.dataObj.policy = response.data.policy
          _self.dataObj.signature = response.data.signature
          _self.dataObj.ossaccessKeyId = response.data.accessKeyId
          _self.dataObj.key = response.data.dir + '/${filename}'
          _self.dataObj.dir = response.data.dir
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true
      this.fileList.pop()
      this.fileList.push({ name: file.name, url: this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name })
      this.emitInput(this.fileList[0].url)
    }
  }
}
</script>
<style scoped>
 .color{
 color:#CCCCCC
 }
</style>


