<!-- 答案内容预览 -->
<template>
  <vue-markdown :source="content"
                v-highlight
                class="markdown-body">
  </vue-markdown>
</template>

<script>
import 'vis-network/dist/dist/vis-network.css';
// eslint-disable-next-line no-unused-vars
import { Network } from 'vis-network/dist/vis-network.esm.js';

import hljs from 'highlight.js' // 代码块高亮
// import 'highlight.js/styles/github.css' // 代码块高亮样式
import './github-markdown.css' // 整体 markdown 样式
import VueMarkdown from 'vue-markdown'
import filePreview from './filePreview'
export default {
  data () {
    return {
      result: undefined

    };
  },
  props: ['content'],
  components: { VueMarkdown },

  computed: {},

  directives: {
    highlight: {
      // 指令的定义
      inserted: function (el) {
        let blocks = el.querySelectorAll('pre code');
        blocks.forEach((block, index) => {
          /** 代码高亮 */
          hljs.highlightBlock(block);
          /** 手动添加一个hljs类名，防止不支持的语言背景变空白 */
          block.classList.add('hljs');
        })
      }
    }
  },
  mounted () {

  },
  watch: {

  },
  methods: {
    isSuccess () {
      this.$nextTick(() => {
        const anchorTags = Object.values(this.$el.getElementsByTagName('a'));
        this.preview(anchorTags)
      })
    },
    preview (anchorTags) {
      let that = this
      // 遍历并输出链接的 href 属性

      anchorTags.forEach((aTag) => {
        let tagUrl = aTag.getAttribute('href') || ''

        let isFile = ['pdf', 'jpg', 'gif', 'jpeg', 'png', 'docx', 'doc', 'xlsx', 'xls', 'mp4', 'webm', 'ogg', 'ogv', 'txt'].indexOf(tagUrl.split('.').pop().toLowerCase()) !== -1
        let isFile2 = ['html', 'md', 'json', 'jsonl', 'csv', 'pdf', 'png', 'jpg', 'jpeg', 'bmp', 'eml', 'msg', 'epub', 'xlsx', 'xlsd', 'ipynb', 'odt', 'py', 'rst', 'rtf', 'srt', 'toml', 'tsv', 'docx', 'doc', 'xml', 'ppt', 'pptx', 'txt', 'htm'].indexOf(tagUrl.split('.').pop().toLowerCase()) !== -1
        if (isFile2 || aTag.className === 'show_detail') { // 判断知识库以及基于文件问答 的文件类型，并添加dom以及样式 ||  添加特殊a标签展示详情内容
          this.setDescribeStyle(aTag)
        }
        aTag.addEventListener('click', function (event) {
          if (isFile) { // 判断可预览文件类型
            // 阻止默认点击事件
            event.preventDefault();
            that.$dialog.show('文件预览', filePreview, {
              area: ['100%', '100%']
            }, { url: tagUrl }).then(res => {

            }).catch(e => { });
          }
        });
      });
    },
    setDescribeStyle (aTag) {
      // let describeDom = aTag.nextElementSibling
      // 在当前元素前插入新的 HTML 内容
      aTag.insertAdjacentHTML('afterend', `
      <button style="margin-top:10px" type="button" class="el-button el-button--primary el-button--mini is-round">
        <span style="margin-right:5px">详情</span>
        <i class="el-icon-arrow-down"></i>
      </button>
      `);

      var buttonDom = aTag.nextElementSibling;// 下拉按钮
      let describeDom = aTag.parentNode.querySelector('.describe-view') || aTag.parentNode.parentNode.querySelector('.describe-view')// 详情
      this.initNetwork(describeDom, describeDom.getAttribute('data'))
      let height = describeDom.scrollHeight
      describeDom.setAttribute('style', 'height:0px;')
      buttonDom.addEventListener('click', function (event) {
        if (height > 0 && (describeDom.style.height !== '0px' && describeDom.style.height !== '')) {
          describeDom.setAttribute('style', 'height:0px;')
        } else {
          describeDom.setAttribute('style', `height:${height}px;`)
        }
      })
    },
    initNetwork (target, data) {
      // 判断有没有data属性
      if (target.hasAttribute('data') && target.getAttribute('data') !== null) {
        const container = document.createElement('div');
        container.style.width = '100%'
        container.style.border = '1px solid lightgray'
        container.style.height = '400px'
        container.style.position = 'relative';
        container.style.borderRadius = '10px'
        container.style.marginBottom = '10px'
        container.style.zIndex = '10000'
        data = JSON.parse(data.replace(/'/g, '"')).network
        data.edges = data.edges.map((item) => {
          item.length = 300
          return item
        })
        const options = {
          autoResize: true, // 网络将自动检测其容器的大小调整，并相应地重绘自身
          nodes: {
            shape: 'circle',
            widthConstraint: 100, // 设置数字，将节点的最小和最大宽度设为该值,当值设为很小的时候，label会换行，节点会保持一个最小值，里边的内容会换行
            color: {
              background: '#0092FF'

            },
            font: {
              color: '#7a7a7a' // 修改节点内文字颜色为黑色
            },
            size: 30
          },
          edges: {
            arrows: {
              to: {
                enabled: true,
                scaleFactor: 0.4 // 箭头大小的缩放因子
              }
            },
            font: {
              size: 12
            }
          },

          physics: {
            enabled: true,
            barnesHut: {
              gravitationalConstant: -2000
            }

          }
        };
        // eslint-disable-next-line no-unused-vars
        const network = new Network(container, data, options);
        target.appendChild(container);
        container.setAttribute('isfull', '0')
        let fullDom = document.createElement('div')
        fullDom.classList.add('el-icon-full-screen', 'full')

        container.appendChild(fullDom)
        fullDom.addEventListener('click', () => {
          if (container.getAttribute('isfull') !== '0') {
            container.style.height = '400px';
            container.style.position = 'relative';
            container.style.background = 'none'
            container.setAttribute('isfull', '0')
            container.style.border = '1px solid lightgray'
            fullDom.classList.remove('el-icon-close')
            fullDom.classList.add('el-icon-full-screen')
            document.querySelector('.full').style.color = '#000'
            document.querySelector('.down').style.color = '#000'
          } else {
            document.querySelector('.full').style.color = '#fff'
            document.querySelector('.down').style.color = '#fff'

            fullDom.classList.remove('el-icon-full-screen')
            fullDom.classList.add('el-icon-close')
            container.style.height = '100%';
            container.style.position = 'fixed';
            container.style.top = 0;
            container.style.left = 0;
            container.style.border = 'none'
            container.style.background = '#00000096'
            container.setAttribute('isfull', '1')
          }
        })

        let downDom = document.createElement('div')
        downDom.classList.add('el-icon-download', 'down')
        downDom.addEventListener('click', () => {
          this.downloadCanvas(container.querySelector('canvas'))
        })
        container.appendChild(downDom)
      }
    },
    downloadCanvas (canvas) {
      // 获取 Canvas 的内容作为DataURL
      var dataURL = canvas.toDataURL('image/png');

      // 创建一个下载链接
      var downloadLink = document.createElement('a');
      downloadLink.href = dataURL;
      downloadLink.download = 'Image.png'; // 设置下载文件的名称

      // 将下载链接添加到页面
      document.body.appendChild(downloadLink);

      // 模拟点击下载链接
      downloadLink.click();

      // 移除下载链接
      document.body.removeChild(downloadLink);
    }

  }
}

</script>
<style scoped>
.markdown-body {
  background: none !important;
  font-size: 14px !important;
}
.markdown-body pre {
  background-color: #3b3d3f;
}
</style>
<style>
.describe-view {
  overflow: hidden !important;
  transition: all 0.5s;
  color: #000;
  font-size: 14px;
  background-color: #fff;
  border-radius: 10px;
  padding: 0 20px 0 20px;
  position: relative;
}
</style>
<style>
.vis-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.full {
  width: 20px;
  height: 20px;
  /* background: #0092FF; */
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 20px;
  /* color: #fff; */
  border-radius: 5px;
  /* transition: all 0.5s; */
}
.down {
  width: 20px;
  height: 20px;
  /* background: #0092FF; */
  position: absolute;
  right: 40px;
  top: 10px;
  font-size: 20px;
  /* color: #fff; */
  border-radius: 5px;
}
</style>
