<template>
  <a-card
    :bodyStyle="{ height: '100%', padding: '0px 0px', margin: '0px 0px' }"
    style="overflow-y: hidden; height: 100%; padding: 0px"
    :bordered="true"
  >
    <template #title><span v-html="fileTitle"></span></template>
    <template #extra>
      <a href="#" @click="handleShowDrawer">选择文件</a>
      <a href="#" style="margin-left: 20px" @click="toggleCollapse">{{ toggleCollapseLeft ? '展开>' : '<收起' }}</a>
    </template>
    <iFrame v-if="fileTp == 'pdf'" :src="fileUrl" style="width: 100%; height: 100%"></iFrame>
    <div v-else style="height: 100%; overflow: auto" v-html="docContent" class="file-content"> </div>
  </a-card>
  <a-drawer
    title=""
    placement="left"
    width="100%"
    :closable="false"
    :visible="showDrawer"
    :get-container="false"
    :wrap-style="{ position: 'absolute', border: '1px solid rgb(255,255,255,0)' }"
    @close="closeDrawer"
  >
    <DocFileList ref="regDocFileList" @selectFileDoc="setDocFile" @closeDrawer="closeDrawer" />
  </a-drawer>
</template>

<script lang="ts" setup>
  import iFrame from '/@/components/iFrame/index.vue';
  import { ref } from 'vue';
  import DocFileList from './DocFileList.vue';
  import { queryDocFileById } from '../../index.api';
  import mammoth from 'mammoth';
  import * as XLSX from 'xlsx';

  const toggleCollapseLeft = ref(false);
  const loading = ref(false);
  const fileTp = ref('');
  const fileTitle = ref('文件名称');
  const showDrawer = ref(false);
  const regDocFileList = ref();
  const fileUrl = ref('');
  const emit = defineEmits(['register', 'success', 'goItem', 'toggleCollapse']);

  function toggleCollapse() {
    emit('toggleCollapse');
  }
  const curDocFile = ref({});

  const docContent = ref<string>('');

  const fetchDoc = async (docUrl) => {
    try {
      const response = await fetch(docUrl);
      const arrayBuffer = await response.arrayBuffer();
      const result = await mammoth.convertToHtml({ arrayBuffer });
      docContent.value = result.value;
      loading.value = false;
    } catch (error) {
      console.error('无法加载 DOC 文件:', error);
    } finally {
      loading.value = false;
    }
  };

  const fetchText = async (docUrl) => {
    try {
      const response = await fetch(docUrl);
      const arrayBuffer = await response.arrayBuffer();
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const decoder = new TextDecoder('utf-8'); // 根据需要选择编码
      const text = decoder.decode(arrayBuffer);
      docContent.value = text;
      loading.value = false;
    } catch (error) {
      console.error('无法加载 Txt 文件:', error);
    } finally {
      loading.value = false;
    }
  };

  const fetchExcel = async (docUrl) => {

    try {
      fetch(docUrl)
        .then((response) => {
          if (!response.ok) {
            throw new Error('网络响应不是 OK');
          }
          return response.arrayBuffer();
        })
        .then((data) => {
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const htmlString = XLSX.utils.sheet_to_html(worksheet);
          docContent.value = htmlString;
          loading.value = false;
        })
        .catch((error) => {
          console.error('读取 Excel 文件时出错:', error);
        });

      loading.value = false;
    } catch (error) {
      console.error('无法加载 Excel 文件:', error);
    } finally {
      loading.value = false;
    }
  };

  async function fetchXml(fileUrl) {
    try {
      const response = await fetch(fileUrl);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const xmlText = await response.text();
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
      docContent.value = xmlText.toString();

      docContent.value = createXmlTree(xmlDoc.documentElement);
      loading.value = false;
    } catch (error) {
      console.error('Error fetching or parsing XML:', error);
    } finally {
      loading.value = false;
    }
  }

  function createXmlTree(node) {
    let html = `<div class="xml-node"><strong>${node.nodeName}</strong>`;

    if (node.attributes && node.attributes.length > 0) {
      html += ' [';
      for (let i = 0; i < node.attributes.length; i++) {
        const attr = node.attributes[i];
        html += `${attr.name}="${attr.value}"`;
        if (i < node.attributes.length - 1) {
          html += ', ';
        }
      }
      html += ']';
    }
    if (node.childNodes.length > 0) {
      html += '<div class="xml-node">';
      node.childNodes.forEach((childNode) => {
        if (childNode.nodeType === Node.ELEMENT_NODE) {
          // 仅处理元素节点
          html += createXmlTree(childNode);
        } else if (childNode.nodeType === Node.TEXT_NODE && childNode.nodeValue.trim()) {
          html += `<div>文本: ${childNode.nodeValue.trim()}</div>`;
        }
      });
      html += '</div>';
    }

    html += '</div>';
    return html;
  }

  async function handleShowDrawer() {
    showDrawer.value = true;
    await regDocFileList.value.iniData();
  }

  function closeDrawer() {
    showDrawer.value = false;
  }

  async function showCurFille(fileData) {
    curDocFile.value = fileData;
    let globOnlineViewUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_URL;
    fileTp.value = fileData.fileTp;
    fileUrl.value = globOnlineViewUrl + fileData.filePath;
    fileTitle.value = '文件名：' + fileData.fileName;
    loading.value = true;
    try {
      if (fileTp.value == 'docx') {
        fileUrl.value = globOnlineViewUrl +"/sys/common/static/"+ fileData.filePath;
        await fetchDoc(fileUrl.value);
      } else if (fileTp.value == 'pdf') {
        fileUrl.value = globOnlineViewUrl + fileData.filePath;
      } else if (fileTp.value == 'txt') {
        await fetchText(fileUrl.value);
      } else if (fileTp.value == 'xml') {
        await fetchXml(fileUrl.value);
      } else if (fileTp.value == 'xlsx') {
        fetchExcel(fileUrl.value);
      } else if (fileTp.value == 'zip') {
      } else {
        await fetchText(fileUrl.value);
      }
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
      closeDrawer();
    }
  }

  function getFileId() {
    return curDocFile.value['fileId'] || curDocFile.value['id'];
  }

  function setDocFile(fileData) {

    if (fileData && fileData.filePath) {
      showCurFille(fileData);
      curDocFile.value = fileData;
    }
  }

  async function setDocFileById(fileId) {
    if (fileId) {
      curDocFile.value = await queryDocFileById({ id: fileId });
      showCurFille(curDocFile.value);
    }
  }

  defineExpose({
    getFileId,
    setDocFile,
    setDocFileById,
  });
</script>


<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }

  ::v-deep .content table {
    border: 1px solid;
    width: 100%;
  }
  ::v-deep .content tr {
    border: 1px solid;
  }
  ::v-deep .content td {
    border: 1px solid;
  }

  .ant-card-body {
    padding: 2px !important;
  }


  :deep(.file-content) {
    padding: 20px;
    font-family: "Microsoft YaHei", SimSun, sans-serif;
    line-height: 1.6;
    color: #333;

    /* 表格样式 */
    table {
      border-collapse: collapse;
      width: 100%;
      margin: 15px 0;
      border: 1px solid #ddd;
      
      th, td {
        border: 1px solid #ddd;
        padding: 8px 12px;
      }
      
      th {
        background-color: #f2f2f2;
        font-weight: bold;
      }
    }

    /* 标题样式 */
    h1, h2, h3, h4, h5, h6 {
      margin: 20px 0 10px;
      color: #222;
      font-weight: bold;
    }
    
    h1 { font-size: 24px; }
    h2 { font-size: 22px; }
    h3 { font-size: 20px; }
    h4 { font-size: 18px; }
    h5 { font-size: 16px; }
    h6 { font-size: 14px; }

    /* 段落样式 */
    p {
      margin: 0 0 15px;
      text-align: justify;
    }

    /* 列表样式 */
    ul, ol {
      margin: 15px 0;
      padding-left: 30px;
    }
    
    li {
      margin-bottom: 5px;
    }

    /* 图片样式 */
    img {
      max-width: 100%;
      height: auto;
      margin: 10px 0;
    }

    /* 代码块样式 */
    pre {
      background-color: #f5f5f5;
      padding: 15px;
      border-radius: 4px;
      overflow-x: auto;
      margin: 15px 0;
    }

    /* 引用样式 */
    blockquote {
      border-left: 4px solid #ddd;
      padding-left: 15px;
      color: #666;
      margin: 15px 0;
    }
  }

  .ant-card-body {
    padding: 2px !important;
  }
</style>

