<template>
  <div>
    <el-upload action=""
      :multiple="false"
      :show-file-list="false"
      accept="image/jpeg,image/png"
      class="image-uploader"
      :on-exceed="handleExceed"
      :on-change="onFrontImgChange"
      :before-upload="beforeUpload">
      <el-button type="primary" style="width: 200px;" class="mt20">
        {{placeholder}}
      </el-button>
    </el-upload>
  </div>
</template>

<script>
  import SparkMD5 from 'spark-md5'
  import { uploadImg } from "@/components/httpServer/httpServer.js";
  import { compressImg } from "../util.js";
  export default {
    name: 'Upload',
    components: {},
    props: {
      placeholder:{
        type: String,
        default: "点击上传基准照片",
      },
      mins:{
        type: Number,
        default: 20,
      },
      maxs:{
        type: Number,
        default: 200,
      },
    },
    data() {
      return {
        fileMd5:'',
        onupload: false,
      }
    },
    methods: {
      beforeUpload(file) {
        let fileSize = file.size / 1024
        let {maxs,mins} = this;
        if (fileSize > maxs ) {
          this.$message.error(`上传文件大小不能超过 ${maxs}KB!`);
          return false
        }
        if (fileSize < mins ) {
          this.$message.error(`上传文件大小不能小于 ${mins}KB!`);
          return false
        }
        file.is_pass = 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;
      	//console.log(file)
      	let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      	var spark = new SparkMD5();
      	fileReader.readAsBinaryString(dataFile)

      	//异步执行函数
      	fileReader.onload = function(e){
          spark.appendBinary(e.target.result);
          var md5 = spark.end()
          _this.fileMd5 = md5;
          if( !_this.onupload){
            console.log('start', _this.fileMd5)
            _this.onupload = true
            _this.handleUpload( md5, file.raw )
          }else{
            console.log("skip", _this.fileMd5 )
          }
      	}
      },
      handleUpload( rand, file ) {
        if( !file.is_pass ) return;
        let that = this
        const formData = new FormData()
        formData.append('avatar', file )
        this.$message.successMsg('文件开始上传!', 1);
        uploadImg( that.fileMd5, formData ).then( res=>{
         that.onupload = false
         if( res.code== 200){
           that.$emit('onFinish', res.data.url)
         }
        })
      }
    }
  }
</script>
