<template>
  <div>
    <el-upload
      ref="upload"
      :action="imgAction"
      :headers="headers"
      :file-list="fileList"
      :before-upload="imgBeforeUpload"
      :on-change="handleChange"
      :limit="limit"
      :auto-upload="true"
      :on-remove="handelDelete"
      :on-error="handleError"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">
        最多可上传{{ limit }}个文件{{ limitRemark }}
      </div>
    </el-upload>
  </div>
</template>

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

  export default {
    name: "NonimageUpload",
    components: {ElImageViewer},
    model: {
      prop: "value",
    },
    mixins: [emitter],
    props: {
      //配合v-model 加载初始值
      value: {
        type: Array,
        default: () => [],
      },
      limit: Number,
      limitRemark: String,
      fileName: String,
      serverAddr: String,
      imageType: String
    },
    data() {
      return {
        fileList: [],
        filePath: "",
        imageVisible: false,
        dialogImageUrl: "",
        imgAction: process.env.VUE_APP_BASE_API + "/upload",
        progressPercent: 0,
        minSize: 0 * 1024,
        maxSize: 5 * 1024 * 1024 * 1024,
        minSizeTip: "1KB",
        maxSizeTip: "50MB",
      };
    },
    computed: {
      headers() {
        return {Authorization: "Bearer " + getToken()};
      },
    },
    created() {
      this.setFileList(this.value);
    },
    // //监听父组件值是否在变化
    // watch: {
    //   //有些页面初始初始src没有赋值
    //   value(newValue, oldValue) {
    //     this.setFileList(newValue);
    //   },
    // },
    methods: {
      imgBeforeUpload(file) {
        if (!this.imageType || this.imageType == '') {
          this.imageType = 'pdf|doc|docx|txt';
        }
        let fileExt = file.name.replace(/.+\./, "");
        let isAccept = (this.imageType.indexOf(fileExt) != -1);
        if (!isAccept) {
          this.$message.error('文件请选用' + this.imageType.replaceAll("|", "、") + '格式')
          return false;
        }
        if (file.size == 0) {
          this.$message.error("不能上传空文件");
          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;
      // },
      handlePreview(file) {
        // if (window.navigator.msSaveOrOpenBlob) {
        //   navigator.msSaveBlob(file.raw, file.name);
        // } else {
        //   var link = document.createElement("a");
        //   link.download = file.name;
        //   var binaryData = [];
        //   binaryData.push(file.raw);
        //   link.href = window.URL.createObjectURL(
        //     new Blob(binaryData, { type: "application/zip" })
        //   );
        //   // link.href = window.URL.createObjectURL(file.raw);
        //   link.click();
        //   window.URL.revokeObjectURL(link.href);
        // }
      },
      closeViewer() {
        this.imageVisible = false;
      },
      handelDelete(file, fileList) {
        //imgBeforeUpload校验失败会触发此方法
        if (file && file.status === "success") {
          // this.fileList2PathStrList(fileList, this.value);
          this.$emit("input", this.file2Path(fileList));
          // this.$emit("blur", this.file2Path(fileList));
          // this.$emit("change", this.file2Path(fileList), this.fileList);
          this.dispatch('ElFormItem', 'el.form.change', this.file2Path(fileList));

          //filePath start
          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);
          //filePath end
        }
      },
      handleSuccess(response, file) {
        file.percentage = 100;
        file.filePath = response.filePath;

        this.value.push(file.filePath);
        // this.$emit("input", this.file2Path(this.fileList));//TODO why not work???
        this.dispatch('ElFormItem', 'el.form.change', this.file2Path(this.value));

        //filePath start
        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);
        //filePath end
      },
      handleError() {
        this.$message.error("文件上传失败，请重新上传或联系管理员");
      },
      handleExceed() {
        this.$message.error("最多只能上传" + this.limit + "个文件");
      },
      handleChange() {
      },

      //通过父组件传过来的value更新子组件
      setFileList(stringList) {
        let detailFile = [];
        if (stringList && stringList.length > 0) {
          for (let index in stringList) {
            detailFile.push({
              name: this.fileName + (Number.parseInt(index) + 1),
              url: this.serverAddr + stringList[index],
              filePath: stringList[index],
            });
          }
        }
        this.fileList = detailFile;

        //filePath start
        for (let file in this.fileList) {
          this.filePath += "," + this.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);
        //filePath end
      },
      fileList2PathStrList(fList, strList) {
        strList.length = 0;
        if (fList && fList.length > 0) {
          for (let index in fList) {
            strList.push(fList[index].filePath);
          }
        }
      },
      file2Path(fList) {
        let strList = [];
        if (fList && fList.length > 0) {
          for (let index in fList) {
            strList.push(fList[index].filePath);
          }
        }
        return strList;
      },
      reset() {
        this.fileList = [];
        this.filePath = '';
      },
      setToolFileList(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)
      },
      setInstallDocFileList(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)
      }
    },
  };
</script>

<style scoped>
</style>
