<template>
  <a-drawer
    :title="fileTitle"
    placement="left"
    :width="drawerWidth"
    :closable="true"
    :visible="showDrawer"
    @close="closeDrawer"
    :mask="false"
  >

  <template #extra>
    <a-space wrap>
      <a-button type="link" v-show="isFullScreen" block @click="setDrawerFull">
        <FullscreenOutlined />
      </a-button>
      <a-button type="link" v-show="!isFullScreen" block @click="setDrawerFull">
        <FullscreenExitOutlined />
      </a-button>
      <a-button type="link" block @click="closeDrawer">
        <CloseOutlined />
      </a-button>
    </a-space>
  </template>

    <i-frame v-if="fileTp == 'pdf'" :src="fileUrl" style="width: 100%;">
    
    </i-frame>
    
  
  </a-drawer>
</template>

<script lang="ts" setup>
  import iFrame from '/@/components/iFrame/index.vue';
  import { ref,h } from 'vue';
  import { FullscreenOutlined,FullscreenExitOutlined,CloseOutlined} from '@ant-design/icons-vue';
  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 drawerWidth = ref("50%");
  const isFullScreen = ref(false);
  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') {
      } 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;
    }
  }


  const files = ref({
    1:{fileTp:"pdf",filePath:"/baosong/银行业保险业信息科技非现场监管报表（2024版）.pdf",fileName:"银行业保险业信息科技非现场监管报表（2024版）"},
    2:{fileTp:"pdf",filePath:"/baosong/银行业保险业信息科技非现场监管报表填报指南（2024版）.pdf",fileName:"银行业保险业信息科技非现场监管报表填报指南（2024版）.pdf"}
  })

  function setDocFile(tp) {
    showCurFille(files.value[tp]);
    showDrawer.value = true;
  }

  function setDrawerFull() {
    isFullScreen.value = !isFullScreen.value;
    drawerWidth.value = isFullScreen.value?"100%":"50%"
    
  }


  defineExpose({
    setDocFile,
  });
</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>
