<template>
  <a-card
    :bodyStyle="{ height: '90%', padding: '10px 0px', margin: '0px 10px' }"
    style="overflow-y: auto; height: 100%; padding: 0px"
    :bordered="false"
  >
    <template #title><span v-html="fileTitle"></span></template>
    <!-- <template #extra><a href="#" @click="handleShowDrawer">选择文件</a></template> -->
    <i-frame v-if="fileTp == 'pdf'||fileTp=='url'" :src="fileUrl" style="width: 100%; height: 100%" />
    <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 './esStandLibQuery.api';
  import mammoth from 'mammoth';
  import * as XLSX from 'xlsx';

  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']);

  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);
          alert('加载 Excel 文件时出错: ' + error.message);
        });

      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;
    const fpath = fileData.fpath;
    if(isHttpOrHttps(fpath)) {
      fileTp.value = "url"
      fileUrl.value = fpath
      fileTitle.value = '网址：' + fpath;
    }  else {
      fileTp.value = await getFileTp(fpath);
      fileUrl.value = globOnlineViewUrl + fileData.fpath;
      fileTitle.value = '文件名：' + fileData.fpathHight;
    }

    
    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') {
      } 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.fpath) {
      showCurFille(fileData);
      curDocFile.value = fileData;
    }
  }

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


  async function getFileTp(strUrl) {  
      const p = strUrl.lastIndexOf('.'); // 将 lastIndex 改为 lastIndexOf  
      if (p === -1) return ''; // 如果没有找到文件扩展名，则返回空字符串  
      const fileTp = strUrl.substring(p + 1); // 获取最后一个点之后的子字符串  
      return fileTp;  
  }  

  function isHttpOrHttps(url) {  
      return url.startsWith('http://') || url.startsWith('https://');  
  }

  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;
  }
</style>
