
<template>
  <div>
    <div v-if="fileId" class="pdf-css">
      <el-image
        @click="check(fileId)"
        :src="
          accept === '.pdf'
            ? require('@/assets/PDF.png')
            : (accept.indexOf('.jpg') !== -1 ||
                accept.indexOf('.png') !== -1 ||
                accept.indexOf('.jpeg') !== -1) &&
              accept.indexOf('.pdf') == -1 &&
              accept.indexOf('.xlsx') == -1
            ? require('@/assets/image.png')
            : require('@/assets/doc.png')
        "
        alt
        :preview-src-list="srcList"
      ></el-image>
      <i
        v-if="!readonly"
        class="el-icon-error fork"
        @click="deltabpdf(fileId)"
      ></i>
    </div>
    <el-upload
      v-loading="loading"
      v-else
      action=""
      :on-change="handleChange"
      :show-file-list="false"
      :file-list="fileList"
      :accept="accept"
      :auto-upload="false"
      ref="upload"
      class="upload-css"
    >
      <el-button type="primary" :disabled="canUp">点击上传</el-button>
      <div slot="tip" class="el-upload__tip"><slot name="dec"></slot></div>
    </el-upload>

    <el-dialog
      title="预览"
      :visible.sync="dialogFile"
      width="70%"
      append-to-body
    >
      <iframe
        :src="pdfSrc"
        frameborder="0"
        style="width: 100%; height: 100%"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { uploadData, uploadCheck } from "@/api/user";

export default {
  name: "ylUpload",
  props: {
    // 对话框('dialog')还是跳页面('window')打开文件
    openFileType: {
      type: String,
      default: "dialog"
    },
    // 上传路径名称,用于文件夹分类，方便查找
    urlName: {
      type: String,
      default: "spd"
    },
    // 文档类别，.pdf, .jpg等
    accept: {
      type: String,
      default: ".pdf"
    },
    // 最大M数，上传的大小
    maxSize: {
      type: Number,
      default: 10
    },
    // 传递的id值
    fileId: {
      type: [Number, String],
      default: ""
    },
    // 文件是否只读
    readonly: {
      type: Boolean,
      default: false
    },
    index:{
      type: Number,
      default: 0,
    }
  },
  data() {
    return {
      loading: false,
      // pdf
      dialogFile: false,
      pdfSrc: "",
      srcList: [""],
      type: ""
    };
  },
  methods: {
    // 上传文件
    handleChange(file) {
      this.loading = true;
      const max = this.maxSize * 1024 * 1024;
      if (file.size > max) {
        this.$message({
          message: "上传文件大小不能超过" + this.maxSize + "M!",
          type: "warning"
        });
        this.loading = false;
        return false;
      } else if (file.name.indexOf(",") !== -1) {
        this.$message.warning("文件名称不能存在英文逗号");
        this.loading = false;
        return false;
      } else if (this.accept && this.accept.indexOf("/") === -1) {
        const suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
        const acceptArr = this.accept
          .replace(/\./g, "")
          .toLowerCase()
          .split(",");
        if (!acceptArr.includes(suffix)) {
          this.$message.warning(`仅支持上传${acceptArr.join("、")}格式文件`);
          this.loading = false;
          return false;
        }
      }
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = async (e) => {
        console.log(e);
        const fileCode = e.target.result;
        const data = {
          fileName: file.name,
          itemcode: this.urlName,
          fileContent: fileCode
        };
        const res = await uploadData(data, this);
        if (res.success == true) {
          this.$emit("getUpload", res.data.id,this.index);
          this.loading = false;
        } else {
          this.loading = false;
        }
      };
    },
    // 表单点击预览
    check(id) {
      this.pdfSrc = "";
      this.srcList = false;
      this.type = "";
      let file = {
        id: id
      };

      uploadCheck(file).then((res) => {
        if (res.success == true) {
          const a = res.data.fileContent;
          this.type = res.data.fileSufx;
          // 打开pdf
          if (res.data.fileSufx === "pdf") {
            console.log(222)
            const b = this.dataURLtoBlob(res.data.fileContent.slice(28));
            console.log(b,"bb")
            if (this.openFileType === "dialog") {
              this.dialogFile = true;
              this.pdfSrc = b;
            } else if (this.openFileType === "window") {
              window.open(b);
            }
          } else if (
            this.type == "jpg" ||
            this.type == "png" ||
            this.type.toLowerCase() == "jpeg"
          ) {
            //打开图片
            this.srcList = [a];
          }
        }
      });
    },

    // 预览文件
    dataURLtoBlob(e) {
      console.log(111)
      let bstr = atob(e);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      } //确定解析格式
      let blob = new Blob([u8arr], { type: "application/pdf;chartset=UTF-8" });
      let url = window.URL.createObjectURL(blob);
      return url;
    },

    deltabpdf(id) {
      this.$emit("getUpload", "",this.index);
    }
  }
};
</script>

<style scoped lang="scss">
.pdf-css {
  position: relative;
  width: 42px;
  height: 42px;
  padding-top: 4px;
  padding-left: 10px;

  img {
    width: 35px;
    height: 35px;
  }
  .fork {
    cursor: pointer;
    position: absolute;
    top: 4px;
    right: -11px;
    color: #cecece;
  }
}
.upload-css {
  padding: 5px;
}
::v-deep .el-loading-mask {
  right: auto;
  left: 26px;
}
::v-deep .el-dialog {
  height: 90%;
  margin-top: 30px !important;
}

::v-deep .el-dialog__body {
  height: 90%;
  padding: 25px 25px 0px;
}
</style>