<template>
  <div class="upload-file">
    <el-upload
      :action="uploadImgUrl"
      :headers="headers"
      multiple
      list-type="picture-card"
      :fileType="fileType"
      :file-list="fileList"
      :limit="limit"
      :before-upload="handleBeforeUpload"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :class="{hide: isHide}"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件，且不超过{{limit}}个
    </div>

    <!-- 图片预览 -->
    <el-image
      v-show="false"
      id="img"
      ref="previewImg"
      :src="dialogImageUrl"
      :preview-src-list="[dialogImageUrl]"
      :z-index="9999999"
    >
    </el-image>
  </div>

</template>

<script>
  import { getToken } from "@/utils/auth";
  export default {
    name: "multiple-image-upload",
    props: {
      // 值
      value: [String, Object, Array],
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5,
      },
      //回显数组
      /*fileList: {
        type: Array,
         default: () => [],
      },*/
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
          type: Array,
          default: () => ["jpg","jpeg","png"],
      },
      limit: {
          type: Number,
          default: 5
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true,
      },
    },
    data(){
        return{
          uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          previewImg: null,
          dialogImageUrl: null,
          fileList: [],
          isHide: false
        }
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
    },
    methods: {
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        // 校检文件类型
        if (this.fileType) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          const isTypeOk = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
              if (fileExtension && fileExtension.indexOf(type) > -1) return true;
              return false;
            });
            if (!isTypeOk) {
              this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
              return false;
            }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        return true;
      },
      // 文件个数超出
      handleExceed() {
        this.$message.error(`只允许上传单`+ this.limit +`文件`);
      },
      handleUploadSuccess(res,file,fileList) {
        if (res.code == 200) {
          let files = this.getFile(fileList);
          this.$message.success("上传成功");
          this.$emit("input", files.join(","));
          this.hideUpload(fileList);
        }
      },
      handleUploadError() {
        this.$message.error("上传失败, 请重试");
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.$refs.previewImg.showViewer = true;
      },
      handleRemove(file, fileList) {
        let files = this.getFile(fileList);
        this.$emit("input", files.join(","));
        this.hideUpload(fileList);
      },
      getFile(fileList){
        if (fileList.every(item => item.status == "success")) {
          //由于fileList是所有的文件包含之前已上传过的，这里需要做区分（带response的即为新上传的）
          return fileList.map(item => {
              if(item.response){
              return item.response.url;
            }else{
              return item.url;
            }
          })
        }else{
          return [];
        }
      },
      hideUpload(fileList){
        if(fileList.length > 4){
          this.isHide = true;
        }else{
          this.isHide = false;
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .hide ::v-deep .el-upload--picture-card {
    display: none;
  }
</style>
