<template>
  <div class="upload-com">
    <el-upload
      :limit="1"
      :list-type="listType === 'picture-card' ? 'picture-card' : ''"
      :action="uploadUrl"
      :headers="headers"
      :before-upload="beforeFileUpload"
      :on-remove="handleRemove"
      :before-remove="beforeFileRemove"
      :on-success="handleSuccess"
      :on-preview="previewClick"
      :file-list="fileList"
    >
      <template v-if="listType === 'picture-card'">
        <i class="el-icon-plus"></i>
      </template>
      <template v-else>
        <el-button size="small" type="primary">点击上传</el-button>
      </template>
    </el-upload>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="viewerList"
    />
  </div>
</template>

<script>
import store from "@/store";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  components: { ElImageViewer },
  props: {
    info: {
      type: String,
      default: null
    },
    tip: {
      type: String
    },
    show: {
      type: Boolean
    },
    listType: {
      type: String,
      default: "picture-card"
    }
  },
  watch: {
    getInfo: {
      handler(newVal) {},
      deep: true
    }
  },
  computed: {
    getInfo() {
      if (this.info) {
        const arr = [
          {
            name: this.info,
            url: this.info
          }
        ];
        this.fileList = arr;
      }
      return this.info;
    }
  },
  data() {
    return {
      headers: {
        Authorization: "Bearer " + store.getters.access_token
      },
      uploadUrl: "/admin/sys-file/upload",
      fileTypeLimit: [
        // 图片
        "image/jpeg",
        "image/png",
        "image/gif",
        "image/bmp",
        "image/jpg",
        // word
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        // excel
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        // pdf
        "application/pdf",
        "application/x-pdf",
        // ppt
        "application/vnd.ms-powerpoint", // .ppt
        "application/vnd.openxmlformats-officedocument.presentationml.presentation" // .pptx
      ], // 支持上传的文件类型
      fileList: [],
      imgTypeList: ["jpeg", "jpg", "png", "git", "bmp"], // 能查看的文件类型
      showViewer: false,
      viewerList: []
    };
  },
  methods: {
    beforeFileUpload(file) {
      if (!this.fileTypeLimit.includes(file.type)) {
        this.$message.warning("不支持的文件格式");
        return false;
      }
    },
    handleRemove(file, fileList) {
      this.fileListHandle(fileList);
    },
    beforeFileRemove(file, _fileList) {
      if (file.status === "success") {
        return this.$confirm(`确定移除 ${file.name}？`);
      }
    },
    handleSuccess(response, file, fileList) {
      this.fileListHandle(fileList);
    },
    fileListHandle(fileList) {
      let arr = [];
      arr = fileList.map(item => {
        if (item.response && item.response.code == 0) {
          return {
            fileName: item.name,
            url: item.response.data.url
          };
        } else {
          return {
            fileName: item.name,
            url: item.url
          };
        }
      });
      this.$emit("updateInfo", arr);
    },
    previewClick(file) {
      let url;
      let fileType;
      if (file.response) {
        fileType = file.response.data.url.split(".")[1];
        url = file.response.data.url;
      } else {
        fileType = file.url.split(".")[1];
        url = file.url;
      }
      if (this.imgTypeList.includes(fileType)) {
        this.viewerList = [url];
        this.showViewer = true;
      } else {
        console.log("file", file);
        let url = "";
        let fileName = "";
        if (file.response && file.response.data) {
          url = file.response.data.url;
          fileName = file.response.data.fileName;
        } else {
          url = file.url;
          fileName = file.name;
        }

        const link = document.createElement("a");
        link.href = process.env.VUE_APP_URL + url;
        link.download = fileName;
        link.target = "_blank"; // 为了在某些浏览器中工作，可以设置为 "_blank"
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    closeViewer() {
      this.showViewer = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.file-list {
  margin-top: 12px;

  .file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .file-item-name {
      color: #606266;
    }

    &:hover {
      background-color: #f5f7fa;

      .file-item-name {
        color: #2d8cf0;
      }
    }

    .file-item-right {
      .file-item-view {
        &:hover {
          color: #2d8cf0;
        }
      }

      .el-icon-close {
        &:hover {
          color: #606266;
        }
      }
    }
  }
}
</style>
