<template>
  <div>
    <el-button v-if="disabled" disabled="true" type="primary"
    :style="{'width': width}" class="mt10" > {{placeholder}}</el-button>
    <el-upload action="" v-else
      v-loading.fullscreen.lock="loading"
      :multiple="false"
      :show-file-list="false"
      accept="image/jpeg,image/png"
      class="image-uploader"
      :auto-upload="true"
      :on-exceed="handleExceed"
      :on-change="onFrontImgChange"
      :before-upload="beforeUpload">
      <el-button type="primary" :style="{'width': width}" style="margin-top: 8px;">
        {{placeholder}}
      </el-button>
    </el-upload>
  </div>
</template>

<script>
  import { uploadImg } from "@/components/httpServer/httpServer.js";
  export default {
    name: 'Upload',
    components: {},
    props: {
      placeholder:{
        type: String,
        default: "点击上传基准照片",
      },
      disabled:{
        type: Boolean,
        default: false,
      },
      imgType:{
        type: String,
        default: "",
      },
      width:{
        type: String,
        default: "200px",
      }
    },
    data() {
      return {
        fileMd5:'',
        loading: false,
        onupload: false,
        canUpload: false,
      }
    },
    methods: {
      beforeUpload(file) {
        //限制的上限为20M
        const maxSize = file.size / 1024 ;
        this.canUpload = false;
        if (maxSize > 500) {
          this.$message.error('上传文件大小不能超过 500k!');
          return false;
        }
        if (maxSize <20) {
          this.$message.error('上传文件大小不能小于 20K!');
          return false;
        }
        this.canUpload = true;
        return true;
      },
      handleExceed( event ){
        console.log('handleExceed', event)
      },
      onFrontImgChange:function(file, fileList){
      	const _this = this  //this指向问题
      	var fileReader = new FileReader();
      	var dataFile = file.raw;
      	let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      	fileReader.readAsBinaryString(dataFile)
      	//异步执行函数
      	fileReader.onload = function(e){
          if( _this.canUpload ){
            _this.loading = true
            _this.handleUpload(  file.raw )
          }else{
            console.log("canUpload", _this.canUpload)
          }
      	}
      },
      handleUpload( file ) {
        let that = this
        // 100k
        const formData = new FormData()
        formData.append('avatar', file )
        uploadImg( that.imgType, formData ).then( res=>{
           that.loading = false
           if( res.code== 200){
             that.$emit('onFinish', res.data.url)
           }
        })
      }
    }
  }
</script>
