<template>
  <div class="invoice-preview">

    <!-- 使用Flex布局来居中显示 -->
    <div class="center-container">
      <!-- 下载PDF按钮 -->
      <div style="float:left;">
        <el-button type="primary" @click="download('PDF')" class="download-button">下载PDF</el-button>
        <el-button type="primary" @click="download('OFD')" class="download-button">下载OFD</el-button>
        <el-button type="primary" @click="download('XML')" class="download-button">下载XML</el-button>
      </div>

      <img :src="invoiceImageUrl" alt="加载中" class="invoice-image">

    </div>
  </div>
</template>

<script>
import {getFilePreview,downloadFile} from "@/api/sdInvoicefile/sdinvoicefile";

export default {
  data() {
    return {
      // 替换为你的发票图片base64
      invoiceImageUrl: '',
      id: ''
    };
  },
  mounted() {
    const id = this.$route.params.id;
    console.log('id:', id);
    this.filePreview(id);
  },
  methods: {
    filePreview(id){
      this.id = id;
      this.loading = true;
      getFilePreview(id).then(response => {
        // console.info("id="+response);
        this.invoiceImageUrl = response;
        // this.$forceUpdate();

      });
    },
    // 下载PDF按钮点击事件
    download(ty) {
      const param = {
         "ty": ty,
         "id": this.id
      }
      console.info("param=" + param)
      downloadFile(param).then(response => {
        const content = atob(response.data.fileContent);
        const bytes = new Uint8Array(content.length);
        for (let i = 0; i < content.length; i++) {
          bytes[i] = content.charCodeAt(i);
        }
        const blob = new Blob([bytes], { type: response.data.ty });
        const fileName = this.id;
        if (window.navigator.msSaveOrOpenBlob) {
          // 兼容IE浏览器
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          const link = document.createElement('a');
          const url = URL.createObjectURL(blob);
          link.href = url;
          link.download = fileName + response.data.ty;
          link.click();
          URL.revokeObjectURL(url);

        }
      });

    },
  },
};
</script>

<style scoped>
.invoice-preview {
  width: 100%;
  height: 100vh; /* 设置容器的高度为整个视口高度 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.center-container {
  display: flex;
  flex-direction: column; /* 将子元素垂直排列 */
  justify-content: center;
  align-items: center;
  height: 80vh; /* 或者根据需要设置一个固定高度 */
  flex: 1; /* 占据剩余的垂直空间 */
}

.invoice-image {
  max-width: 90%;
  max-height: 90%;
}

.download-button {
  margin-bottom: 10px;
}
</style>
