<script setup lang="ts">
import mammoth from 'mammoth'; 
import { reactive,ref } from "vue";
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {queryFileFlowRepTemplateApi,exportTemplateApi} from '@/api/reporting/RepTemplate/RepTemplate';
const route = useRoute();
// 也可以直接是在线地址
//获取当前文件的信息
const pageQuery = ref(route || null); 
const fileData = pageQuery.value?.query?.fileData;
//是否渲染完成
let htmlContent = ref("");
const downLoadErrorMsg = {
  "1001":"预览失败,文件路径不存在",
  "1002":"预览失败,未找到文件信息",
  "1003":"预览失败,请联系管理员",
}
const fetchDocFile = async ()=>{  
  try {  
    // 假设你有一个API可以返回DOC文件流  
    const response = await queryFileFlowRepTemplateApi(fileData);
    const { data, headers } = response;
      if(headers['status'] == 500){// 说明此时下载文件有错误，需要获取WARN和ERROR的值
        const code = headers['error']?headers['error'].substring(headers['error'].length-4):'1003';
        console.log(code)
        switch(code){
          case "1001":
          case "1002":
            ElMessage.error(downLoadErrorMsg[code]);
            break;
          default:
            ElMessage.error(downLoadErrorMsg['1003']);
            break;
        }
      return;
    }
    const arrayBuffer = await new File([data], 'document.docx', { type: data.type }).arrayBuffer();
    if (!(arrayBuffer instanceof ArrayBuffer)) {
      throw new Error('Invalid arrayBuffer type');
    }
    dealWithFile(arrayBuffer);
  } catch (error) {  
    console.error('Error fetching or converting DOC file:', error);  
  }  
} 
// fetchDocFile();

//处理文件信息显示
const dealWithFile = async (arrayBuffer)=>{
  console.log(arrayBuffer);
  // 配置 styleMap 以支持表格解析
  // const styleMap = `
  //         p[style-name='Heading 1'] => h1:fresh
  //         p[style-name='Heading 2'] => h2:fresh
  //         p[style-name='Heading 3'] => h3:fresh
  //         table => table
  //         tr => tr
  //         td => td
  //         p[style-name='Normal'] => p
  //         p[style-name='List Paragraph'] => ul > li:fresh
  //         header => div.header
  //         footer => div.footer
  //       `;
  const styleMap = `
    p:style-name => p
    p:Heading1 => h1
    p:Heading2 => h2
    p:Heading3 => h3
    p:Heading4 => h4
    p:Heading5 => h5
    p:Heading6 => h6
    p:Normal => p
    p:Title => h1.title
    p:Subtitle => h2.subtitle
    p:Quote => blockquote
    p:Code => pre
    p:ListParagraph => li
    r:Emphasis => em
    r:Strong => strong
    r:Underline => u
    r:Strikethrough => del
    r:Hyperlink => a
    p:style-name => p style="text-align: center;"
    r:style-name => span style="color: red;"
    p:style-name => p.class-name
    r:style-name => span.class-name
    p:style-name => p#id
    r:style-name => span#id
    p:style-name => p.class-name#id
    r:style-name => span.class-name#id
    table => table
    tr => tr
    td => td
    p[style-name='Normal'] => h6
    p[style-name='List Paragraph'] => ul > li:fresh
    header => div.header
    footer => div.footer
  `;
    let result;
    try {
      result = await mammoth.convertToHtml({
        arrayBuffer,
        styleMap,
        includeDefaultStyleMap: true,
        extractImages: {
          // 自定义图片处理函数
          getAltText: (image) => {
            return image.contentId; // 可以根据需要返回图片的 alt 文本
          },
          getImageUrl: (image) => {
            // 将图片转换为 base64 编码的 URL
            const contentType = image.contentType;
            const base64Data = Buffer.from(image.data).toString('base64');
            return `data:${contentType};base64,${base64Data}`;
          }
        },
        convertImage:mammothImages,
        transformDocument: (document) => {
          // 自定义处理文档，例如提取页眉和页脚
          const headers = document.children.filter(child => child.type === 'header');
          const footers = document.children.filter(child => child.type === 'footer');

          // 将页眉和页脚插入到文档的适当位置
          headers.forEach(header => {
            document.children.push({
              type: 'custom',
              name: 'div',
              attributes: { class: 'header' },
              children: header.children
            });
          });

          footers.forEach(footer => {
            document.children.push({
              type: 'custom',
              name: 'div',
              attributes: { class: 'footer' },
              children: footer.children
            });
          });

          return document;
        },
      });
    } catch (convertError) {
      console.error('Error converting DOC file to HTML:', convertError);
      throw convertError;
    }
    console.log(result,"result信息"); 
    // 添加边框线的CSS样式
    const cssStyles = `
      <style>
        table {
          border-collapse: collapse;
          width: 100%;
        }
        th, td {
          border: 1px solid black;
          padding: 8px;
        }
      </style>
    `;
    // 将生成的HTML内容赋值给htmlContent  
    htmlContent.value = `${cssStyles}${result.value}`; // result.value 包含转换后的HTML  
    // 如果需要显示消息，可以使用 result.messages  
}

// 自定义图片处理函数
const mammothImages = (image) => {
  return mammoth.images.imgElement(image);
}

// 插入分页标记
const insertPageBreaks = (html) => {
  // 假设每500个字符插入一个分页标记
  const pageSize = 500;
  let pagedHtml = '';
  for (let i = 0; i < html.length; i += pageSize) {
    pagedHtml += html.slice(i, i + pageSize) + '<div class="page-break"></div>';
  }
  return pagedHtml;
}

const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const arrayBuffer = await file.arrayBuffer();
  dealWithFile(arrayBuffer);
};

//下载文件
const downloadFile = () => {
  exportTemplateApi({pId:fileData});
};

</script>
 

<template>
  <div class="wrap">
    <div class="fixedToolBar">
      <!-- 其中包含的功能有分页，页数跳转，文件下载 -->
      <i @click="downloadFile" class="fa fa-download cursor-pointer download" hover-color="var(--el-color-primary)"></i>
    </div>
    <input type="file" @change="handleFileChange" accept=".docx" style="margin-top:60px;" />
    <div v-html="htmlContent" class="htmlContent"></div>
  </div>
</template>

<style scoped>
  .fixedToolBar{
    position: fixed;
    top: 0;
    left: 0;
    width:100%;
    height:50px;
    line-height:50px;
    background-color: #635f5f;
    color:#fff;
  }
  .download{
    position: absolute;
    font-size:1.3rem;
    top:13px;
    right:15px;
  }

  .htmlContent {
    height: 100vh;
    overflow: auto;
    background-color: #fff;
    padding:50px;
  }
</style>


