<template>
  <div>
    <el-upload ref="upload" :action="imgAction" :headers="headers" :file-list="fileList"
               :before-upload="imgBeforeUpload" list-type="picture-card" :on-preview="handlePreview"
               :on-change="handleChange"
               :limit="limit" :auto-upload="true" :on-remove="handelDelete" :on-error="handleError"
               :on-success="handleSuccess" :on-exceed="handleExceed">
      <i slot="default" class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">最多可上传{{limit}}个文件，{{fileTip == null ? defaultTip : fileTip}}</div>
    </el-upload>
    <el-image-viewer v-if="imageVisible" :on-close="closeViewer" :url-list="[dialogImageUrl]" z-index="5000"/>
  </div>
</template>

<script>
  import {getToken} from '@/utils/auth'
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

  export default {
    name: "MaterialUpload",
    components: {ElImageViewer},
    props: {
      limit: Number,
      fileTip:String,
      imageType:String
    },
    data() {
      return {
        fileList: [],
        filePath: '',
        defaultTip:'文件使用压缩包格式',
        imageVisible: false,
        dialogImageUrl: '',
        imgAction: process.env.VUE_APP_BASE_API + "/upload",
        progressPercent: 0,
        minSize: 1 * 1024,
        maxSize: 1 * 1024 * 1024,
        minSizeTip: '1KB',
        maxSizeTip: '1MB',
      }
    },
    computed: {
      headers() {
        return {'Authorization': 'Bearer ' + getToken()}
      }
    },
    methods: {
      imgBeforeUpload(file) {
        if (!this.imageType || this.imageType == '')
          this.imageType = 'jpeg|png|jpg|gif|bmp';
        let isAccept = new RegExp('image/(' + this.imageType + ')').test(file.type.toLowerCase())
        if (!isAccept) {
            this.$message.error('文件请选用' + this.imageType.replaceAll("|", "、")+'格式')
            return false;
        }
        let isRightSize = file.size <= this.maxSize
        if (!isRightSize) {
          this.$message.error('文件大小不能超过' + this.maxSizeTip)
          return false;
        }
        isRightSize = file.size >= this.minSize
        if (!isRightSize) {
          this.$message.error('文件大小不能小于' + this.minSizeTip)
          return false;
        }
        return isRightSize && isAccept
      },
      handlePreview(file) {
        this.imageVisible = true;
        this.dialogImageUrl = file.url;
      },
      closeViewer() {
        this.imageVisible = false;
      },
      handelDelete(file, fileList) { //imgBeforeUpload校验失败会触发此方法
        if (file && file.status === "success") {
          this.filePath = '';
          for (let file in fileList) {
            this.filePath += ',' + fileList[file].filePath;
          }
          if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
            this.filePath = this.filePath.substr(1, this.filePath.length);
          this.$emit("setImgPath", this.filePath)
        }
      },
      handleSuccess(response, file) {
        file.percentage = 100;
        file.filePath = response.filePath;
        this.filePath += ',' + response.filePath;
        if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
          this.filePath = this.filePath.substr(1, this.filePath.length);
        this.$emit("setImgPath", this.filePath)
      },
      handleError() {
        this.$message.error('文件上传失败，请重新上传或联系管理员');
      },
      handleExceed() {
        this.$message.error('最多只能上传' + this.limit + '个文件');
      },
      handleChange() {
        // if (file.status == 'ready') {
        //     this.progressPercent = 70;
        //     const interval = setInterval(()=>{
        //       if (this.progressPercent >= 99) {
        //           clearInterval(interval);
        //           return;
        //       }
        //       this.progressPercent +=1;
        //       file.percentage = this.progressPercent;
        // }, 20)
        // }
        // if (file.status == 'success') {
        //     this.progressPercent = 100;
        //     file.percentage = this.progressPercent;
        // }
      },
      reset() {
        this.fileList = [];
        this.filePath = '';
      },
      setFileList(fileList) {
        this.fileList = fileList;
        for (let file in fileList) {
          this.filePath += ',' + fileList[file].filePath;
        }
        if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
          this.filePath = this.filePath.substr(1, this.filePath.length);
        this.$emit("setImgPath", this.filePath)
      },
      // uploadImg(f) {
      //     this.videoFlag = true
      //     let formData = new FormData();
      //     formData.append('file', f.file)
      //     request({
      //         url: '/upload',
      //         headers: {'Content-Type': 'multipart/form-data'},
      //         method: 'post',
      //         data: formData,
      //         onUploadProgress: progressEvent => {
      //             // progressEvent.loaded:已上传文件大小
      //             // progressEvent.total:被上传文件的总大小
      //             this.progressPercent = (progressEvent.loaded / progressEvent.total * 100)
      //         }
      //     }).then(res => {
      //         this.filePath = res.filePath
      //         console.log(res.filePath);
      //         this.videoFlag = false
      //         this.progressPercent = 0
      //     }).then(error => {
      //         console.log('error');
      //
      //         console.log(error)
      //     })
      // }
    },
    created() {
      // this.getDicts("imageSize").then(response => {
      //     let sizeConfig = response.data;
      //     for (let index in sizeConfig) {
      //         let config = sizeConfig[index];
      //         if (config.dictLabel == '最大') {
      //              this.maxSize = eval(config.dictValue);
      //              if (config.dictValue.split("*").length == 3)
      //                  this.maxSizeTip = config.dictValue.split("*")[0] + "MB"
      //             else
      //                  this.maxSizeTip = config.dictValue.split("*")[0] + "KB"
      //          } else {
      //              this.minSize = eval(config.dictValue);
      //             if (config.dictValue.split("*").length == 3)
      //                 this.minSizeTip = config.dictValue.split("*")[0] + "MB"
      //             else
      //                 this.minSizeTip = config.dictValue.split("*")[0] + "KB"
      //          }
      //     }
      // });
      // this.getDicts("imageType").then(response => {
      //     this.imageType = response.data[0].dictValue;
      // });
    }
  }
</script>

<style scoped>

</style>
