<template>
  <section class="shs-upload-img">
    <el-upload :action="actionUrl"
               :accept="accept"
               :data="data"
               :headers="headers"
               :on-exceed="handleExceed"
               :multiple="multiple"
               :on-progress="handleProgress"
               :on-success="handleSuccess"
               :on-error="handleError"
               :before-upload="handleBeforeUpload"
               :show-file-list="false"
               :disabled="isPreview&&!!coverUrl"
               >
      <template v-if="type==='button'">
        <el-button :size="buttonSize" type="primary">{{buttonText}}</el-button>
      </template>
      <template v-else-if="type==='list'">
        <div class="add-img-box" :style="`width:${width}px;height:${height}px;`">
          <i class="el-icon-plus"></i>
        </div>
      </template>
      <template v-else>
        <div class="add-img-box" :style="`width:${width}px;height:${height}px;`">

          <template v-if="coverUrl && coverUrl!==''">

            <el-image v-if="urlType==='image'&&isPreview&&!!coverUrl"
                 :src="coverUrl+'?x-oss-process=image/auto-orient,0/resize,m_fill,limit_0,h_'+height+',w_'+width"
                 :style="`width:${width}px;height:${height}px;`" :preview-src-list="[coverUrl]">
            </el-image>
            <img v-else-if="urlType==='image'"
                 :src="coverUrl+'?x-oss-process=image/auto-orient,0/resize,m_fill,limit_0,h_'+height+',w_'+width"
                 :style="`width:${width}px;height:${height}px;`" />
                 

            <img v-if="urlType==='video'" :style="`width:${width}px;height:${height}px;`"
                 :src="coverUrl+'?spm=a2c4g.11186623.2.1.yjOb8V&x-oss-process=video/snapshot,t_7000,f_jpg,m_fast'"
            />

            <img v-if="urlType==='audio'"
                 src="https://chinavisionary-test.oss-cn-beijing.aliyuncs.com/4468ce9bde6f42e2b601dcdc3eff7a16[-]1593686321892[-]WechatIMG155.png"
                 :style="`width:${width}px;height:${height}px;`" />

            <span v-if="!readonly" class="delete-img" @click.stop="deleteItem()"><i class="el-icon-delete"></i></span>
          </template>

          <template v-else>
            <span v-if="emptyText">{{emptyText}}</span>
            <i v-else class="el-icon-plus"></i>
          </template>

          <template v-if="uploadFileList.length===1">
            <div class="img-progress" v-if="uploadFileList[0].progress!==100 && !uploadFileList[0].key">
              <el-progress type="circle" :percentage="uploadFileList[0].progress" :width="progressWidth"></el-progress>
            </div>
          </template>

          <template v-if="uploadFileList.length===2">
            <div class="img-progress" v-if="uploadFileList[1].progress!==100 && !uploadFileList[1].key">
              <el-progress type="circle" :percentage="uploadFileList[1].progress" :width="progressWidth"></el-progress>
            </div>
          </template>
         
        </div>
      </template>
    </el-upload>
  </section>
</template>

<script>
 
  export default {
    name: 'UploadAlbum',

    props: {
      // 文件list
      uploadFileList: {
        type: Array,
        default: function () {
          return []
        }
      },
      // 文件夹key
      folderKey: {
        type: String,
        default: ''
      },

      type: {
        type: String,
        default: 'img'
      },

      // 按钮size
      buttonSize: {
        type: String,
        default: 'small'
      },

      // 按钮文本
      buttonText: {
        type: String,
        default: '本地上传'
      },

      width: {
        type: Number,
        default: 100
      },

      height: {
        type: Number,
        default: 100
      },

      coverUrl: {
        type: String,
        default: ''
      },

      fileKey: {
        type: String,
        default: ''
      },

      acceptType: {
        type: String,
        default: 'image'
      },

      action: {
        type: String,
        default: ''
      },

      multiple: {
        type: Boolean,
        default: false
      },

      emptyText: {
        type: String,
        default: ''
      },
      // 是否设置上传文件大小
      isSetImgSize: {
        type: Boolean,
        default: false
      },
      // 上传图片的宽度
      imgWidth: {
        type: Number,
        default: 100
      },
      // 上传图片的高度
      imgHeight: {
        type: Number,
        default: 100
      },

      // 只读
      readonly: {
        type: Boolean,
        default: false
      },
      // 有图片时是否可以放大预览
      isPreview: {
        type: Boolean,
        default: false
      },
      // 接口额外参数
      extend: {
        type: Object,
        default: () => {}
      },
      // 视频允许格式
      videoFileType: {
        type: String,
        default: '.mp4, .m3u8,.flv,.f4v,.webm,.mov,.m4v,.3gp,.avi,.wmv,'
      },
      // 上传单个文件不得超过2G
      maxFileSize: {
        type: Number,
        default: 2000
      }
    },

    data() {
      return {
        limit: 5, // 最大允许上传个数
        headers: {
          token: localStorage.getItem('token') // 获取token
        },
        data: Object.assign({
          albumKey: this.folderKey
        }, this.extend),
        imageUrl: '',
        fileList: [],

        fileType:{
          image: '.jpg,.jpeg,.png,.gif,.bmp,',
          video: this.videoFileType,
          audio: '.mp3,.wma,.wav,.amr,.m4a,'
        },
      }
    },

    created() {
      // 如果是封面上传对象 添加时候修改
    },

    computed: {
      // 进度条宽度
      progressWidth() {
        let percent = 100;
        if (parseInt(this.width) > parseInt(this.height)) {
          percent = parseInt(this.height) * 0.7
        } else {
          percent = parseInt(this.width) * 0.7
        }
        return percent
      },

      accept() {
        let types = '';
        if (this.acceptType.indexOf('image') > -1) {
          types = this.fileType.image
        }
        if (this.acceptType.indexOf('video') > -1) {
          types += this.fileType.video
        }
        if (this.acceptType.indexOf('audio') > -1) {
          types +=  this.fileType.audio
        }
        return types
      },

      urlType() {
        if(!this.coverUrl){
          return
        }

        let type = '';
        let urlList = this.coverUrl.split('.');
        let urlType = urlList.pop();
        urlType=urlType.toLowerCase();
        if (this.fileType.image.indexOf(urlType)>-1) {
          type = 'image'
        }else if (this.fileType.video.indexOf(urlType)>-1) {
          type = 'video'
        }else if (this.fileType.audio.indexOf(urlType)>-1) {
          type = 'audio'
        }
        return type
      },

      actionUrl() {
        let url = this.action || window.ajaxBase.uploadFileUrl;
        return url
      },
    },

    components: {},

    methods: {
      handleProgress(event, file, fileList) {
        let tempArr = this.uploadFileList
        this.uploadFileList.forEach((element, index) => {
          if (element.uid === file.uid) {
            // 更新这个uid下的进度
            const progress = Math.floor(event.percent);

            const loaded = event.loaded
            const timeStamp = event.timeStamp
            let mark = false

            let speed = element.speed
            let diffTime = 0
            if (element.timeStamp > 0) {
              diffTime = timeStamp - element.timeStamp
              if (diffTime >= 1000) {
                mark = true
                speed = Math.floor(1000 * (loaded - element.loaded) / (timeStamp - element.timeStamp))
              }
            } else {
              mark = true
            }
            // 防止上传完接口还没有返回成功值，所以此处给定progress的最大值为99，成功的钩子中再置为100
            element.progress = progress === 100 ? 99 : progress
            element.speed = speed
            if (mark) {
              element.loaded = loaded
              element.timeStamp = timeStamp
            }
            this.$set(tempArr, index, element);
            this.$emit('changeFileList', tempArr);
          }
        });
      },

      /***
       * 添加数据
       */
      objAddItem(tempArr, file) {
        const tempObj = {
          uid: file.uid, // uid用于辨别文件
          originalName: file.name, // 列表显示的文件名
          progress: 0, // 进度条
          speed: 0, // 上传速度
          timeStamp: 0, // 时间戳
          loaded: 0 // 已上传
        };
        tempArr.push(tempObj);
        this.$emit('changeFileList', tempArr);
      },

      /**
       * 文件超出个数限制时的钩子
       */
      handleExceed(files, fileList) {
        if (files.length > this.limit) {
          this.$message.error(`最多允许上传${this.limit}个文件`);
          return false;
        }
      },

      handleBeforeUpload(file) {
        if(this.isSetImgSize){
          let that = this;
          let reader = new FileReader();
          reader.onload = function (event) {
            let txt = event.target.result;
            let img = document.createElement("img");
            img.src = txt;
            img.onload =  () => {
              // 文件宽度
              if(img.width!==that.imgWidth  || img.height!==that.imgHeight){
                that.$message.warning(`上传宽度需为${that.imgWidth}*${that.imgHeight}`);
                return
              }

              // 文件大小限制
              const result = file.size / 1024 / 1024 < that.maxFileSize;
              if (!result) {
                that.$message.warning(`上传文件大小不得超过${that.maxFileSize}M！`);
                return result;
              }
              // 验证都通过后，给自定义的列表中添加需要的数据
              that.objAddItem(that.uploadFileList, file);
            }
          };
          reader.readAsDataURL(file);
        }else{
          // 文件大小限制
          const result = file.size / 1024 / 1024 < this.maxFileSize;
          if (!result) {
            this.$message.warning(`上传文件大小不得超过${this.maxFileSize}M！`);
            return result;
          }
          // 验证都通过后，给自定义的列表中添加需要的数据
          this.objAddItem(this.uploadFileList, file);
        }
      },

      handleSuccess(response, file, fileList) {
				let tempArr = this.uploadFileList;
				this.uploadFileList.forEach((element, index) => {
					if(element.uid === file.uid) {
						if(response.success) {
							const {
								key,
								url,
								sourceUrl,
								name
							} = response.data.rows[0]
							element.progress = 100
							element.key = key
							element.url = url
							element.sourceUrl = sourceUrl
							element.name = name
							this.$set(tempArr, index, element);

							if( this.type !== 'list') {
								this.$emit('update:fileKey', element.key);
								this.$emit('update:coverUrl', element.url);
								if(tempArr.length>1){
									// 判断是一张图片时候删除
									tempArr.splice(1, 1);
								}					
							}

							this.$emit('onUploadSuccess', file, tempArr);
						} else {
							tempArr.splice(index, 1); // 上传失败删除该记录
							this.$message.error(`"${element.originalName}"上传失败,${response.message}`);
							this.$emit('onUploadFailed', file, tempArr);
						}
					}
				});
			},

      handleError(errorObj, file, fileList) {
        if (errorObj.message.indexOf('666') > 0) {
          this.$router.replace({
            name: 'login'
          });
          this.$message.warning('登录超时，请重新登录')
        }
        let tempArr = this.fileList;
        this.fileList.forEach((element, index) => {
          if (element.uid === file.uid) {
            tempArr.splice(index, 1); // 上传失败删除该记录
            this.$message.error(`文件上传失败:${element.originalName}`);
            this.$emit('onUploadFailed', file, fileList);
          }
        });
      },


      /**
       * 删除上传选项
       * @param index
       */
      async deleteItem() {
        this.$emit('update:fileKey', '');
        this.$emit('update:coverUrl', '');
      }
    },

    

  }
</script>
<style lang="scss">
  .shs-upload-img {
    .add-img-box {
      overflow: hidden;
      border-radius: 3px;
      border: 1px dashed #d9d9d9;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      position: relative;

      i {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
      }

      .img-progress {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        background: rgba(0, 0, 0, .2);
        display: inline-flex;
        justify-content: center;
        align-items: center;
        align-content: center;

        .el-progress__text {
          color: #409EFF;
        }
      }

      .delete-img{
        position: absolute;
        right: 0;
        bottom: 0;
        line-height: 14px;
        font-size: 10px;
        color: red;
        padding: 3px 5px;
        border-radius: 2px;
        overflow: hidden;
        margin-left: 5px;
        cursor: pointer;
      }
    }
  }
</style>


