<template>
  <div class="preview-doc">
    <div class="preview-doc-back pointer">
      <el-icon @click="router.go(-1)">
        <ArrowLeftBold />
      </el-icon>
      {{ detail?.name }}
    </div>
    <div class="preview-doc-content">
      <div class="preview-doc-content-item">
        <div class="preview-doc-content-item-title">
          源文档
          <el-space>
            <el-button class="primary-text" :icon="Download" @click="downloadByRelPath">下载</el-button>
          </el-space>
        </div>
        <div class="preview-doc-content-item-wrapper" v-loading="loading || pdfLoading">
          <div
            v-if="['docx'].includes(detectFileType(detail?.name))"
            id="preview"
            style="width: 100%"
          ></div>
          <VuePdfEmbed annotation-layer text-layer :source="detail?.relPath" v-else-if="['pdf'].includes(detectFileType(detail?.name))" @progress="test"></VuePdfEmbed>
          <div v-else-if="['doc'].includes(detectFileType(detail?.name))" class="unsupported-format">
            <el-alert type="warning" show-icon :closable="false">
              <p>暂不支持预览 .doc 格式文档</p>
              <p>请<a :href="detail?.relPath" download>下载文件</a>后用Microsoft Word查看</p>
            </el-alert>
          </div>
          <div v-else-if="['ppt'].includes(detectFileType(detail?.name))" id="pptx-wrapper"></div>
          <MdPreview
            v-else-if="['md'].includes(detectFileType(detail?.name))"
            :modelValue="fileContent"
            class="maxkb-md"
            editorId="preview-only"
            style="padding: 20px 30px"
          />
          <div v-else-if="['txt'].includes(detectFileType(detail?.name))" v-html="fileContent"></div>
        </div>
      </div>
      <div class="preview-doc-content-item">
        <div class="preview-doc-content-item-title">
          Markdown
          <el-space>
            <el-button :loading="loading" type="primary" @click="saveContent">保存</el-button>
            <el-button class="primary-text" :icon="Download" @click="downloadMarkdownById">下载</el-button>
          </el-space>
        </div>
        <div class="preview-doc-content-item-wrapper" v-loading="loading">
          <div ref="editorRef" style="width: 100%;height: 100%"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import MdPreview from '@/components/markdown/MdPreview.vue'
import { exportFile } from '@/request/http'
import router from '@/router'
import api from '@/servers/finyx/api'
import { Download } from '@element-plus/icons-vue'
import jsPreviewDocx from '@js-preview/docx'
import jsPreviewPdf from '@js-preview/pdf'
import '@js-preview/docx/lib/index.css'
import { AiEditor } from 'aieditor'
import 'aieditor/dist/style.css'
import { ElMessage } from 'element-plus'
import { first, isEmpty } from 'lodash-es'
import { nextTick, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { init } from 'pptx-preview'
import VuePdfEmbed from 'vue-pdf-embed'
// optional styles
import 'vue-pdf-embed/dist/styles/annotationLayer.css'
import 'vue-pdf-embed/dist/styles/textLayer.css'


const pdfLoading = ref<boolean>(false)
const test = (val: any) => {
  if (!isEmpty(val)) {
    console.log(val)
    pdfLoading.value = val.total > val.loaded;
  }
}

const { query } = useRoute()

const loading = ref<boolean>(false)

const detail = ref<any>({})

const getDocumentItem = async () => {
  try {
    loading.value = true
    detail.value = await api.wendang.getDetail8({ id: query?.id as number })
    const { name, relPath, content } = detail.value
    await nextTick(() => {
      if (content) {
        try {
          aiEditor?.focus().setMarkdownContent(content)
        } catch (e) {
          aiEditor?.focus().setContent(content)
        } finally {
          setTimeout(() => {
            // 找到aiEditorContent 元素 然后滚动条到最上面
            const aiEditorContent = document.querySelector('.aie-content')
            if (aiEditorContent) {
              aiEditorContent.scrollTop = 0
            }

          }, 300)
        }
      }
      if (detectFileType(name) === 'docx') {
        preview.value = jsPreviewDocx.init(<HTMLElement>document.getElementById('preview'))
        preview.value
          .preview(relPath)
          .then(() => {
            console.log('预览完成')
            // 设置延时获取.docx-wrapper 设置style
            setTimeout(() => {
              const docxWrapper = document.querySelector('.docx-wrapper')
              // 计算.preview 的高度
              const previewHeight = document.querySelector('.preview-doc-content-item-wrapper')?.clientHeight || 500
              if (docxWrapper) {
                // docxWrapper.style.alignItems = 'normal'
                // docxWrapper.style.background = 'transparent'
                // docxWrapper.style.overflowX = 'scroll'
                // docxWrapper.style.padding = '0'
                docxWrapper.style.height = previewHeight - 15 + 'px'
              }
            }, 0)
          })
          .catch((e) => {
            console.log('预览失败', e)
          })
      } else if (detectFileType(name) === 'pdf') {
        // preview.value = jsPreviewPdf.init(<HTMLElement>document.getElementById('preview'), {
        //   onError: (e) => {
        //     console.log('发生错误', e)
        //   },
        //   onRendered: () => {
        //     console.log('渲染完成')
        //   }
        // })
        // preview.value.preview(relPath)
      } else if (detectFileType(name) === 'ppt') {
        const width = document.querySelector('.preview')?.clientWidth || 500
        //调用库的init方法生成一个预览器
        let pptxPrviewer = init(<HTMLElement>document.getElementById('pptx-wrapper'), {
          width,
        })
        //获取文件或者读取文件，获取文件的 ArrayBuffer格式数据，传给组件进行预览
        fetch(relPath)
          .then((response) => {
            return response.arrayBuffer()
          })
          .then((res) => {
            //调用预览器的preview方法
            pptxPrviewer.preview(res)
          })
      } else if (detectFileType(name) === 'md' || detectFileType(name) === 'txt') {
        loading.value = true
        fetch(relPath)
          .then((response) => response.text())
          .then((text) => {
            loading.value = false
            if (!content) {
              aiEditor?.focus().setMarkdownContent(text)
            }
            fileContent.value = text
          })
          .catch((e) => {
            loading.value = false
            console.error('获取文件内容失败', e)
          })
      }
    })
  } catch (e) {
    console.error(e)
    ElMessage.error('文档打开失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const saveContent = async () => {
  try {
    const content = aiEditor?.getHtml() || ''
    await api.wendang.update6({ id: query?.id as number, content })
    ElMessage.success('保存成功')
  } catch (e) {
    console.error(e)
    ElMessage.error('保存失败，请稍后重试')
  }
}

const downloadByRelPath = async () => {
  const { relPath } = detail.value
  window.open(relPath, '_blank')
}
const downloadMarkdownById = async () => {
  try {
    const content = aiEditor?.getHtml() || ''
    await api.wendang.update6({ id: query?.id as number, content })
    const params: any = { id: query?.id as number }
    const fileName = detail.value?.name || ''
    await exportFile(fileName, `/finyx/fDocument/downloadMarkdown`, params)
    ElMessage.success('下载成功，请稍后打开查看')
  } catch (e) {
    console.log(e)
    ElMessage.error('下载失败，请稍后重试')
  }
}

// 编辑器
let aiEditor: AiEditor | null = null
const editorRef: any = ref()

/**
 * 根据文件URL判断文件类型
 * @param {string} url - 文件URL
 * @returns {string} - 文件类型（'docx'|'pdf'|'txt'|'md'|'unknown'）
 */
function detectFileType(url) {
  if (!url || typeof url !== 'string') return 'unknown'

  // 移除URL中的查询参数和哈希值
  const cleanUrl = url.split('?')[0].split('#')[0]

  // 获取文件扩展名（小写）
  const ext = cleanUrl.split('.').pop()?.toLowerCase() || ''

  // 判断文件类型
  switch (ext) {
    case 'docx':
      return 'docx'
    case 'doc':
      return 'doc'
    case 'pdf':
      return 'pdf'
    case 'ppt':
    case 'pptx':
      return 'ppt'
    case 'txt':
      return 'txt'
    case 'md':
      return 'md'
    default:
      return 'unknown'
  }
}

const preview = ref<any>()
const fileContent = ref('')
const text = ref('# Hello Editor')

onMounted(() => {
  getDocumentItem()
  aiEditor = new AiEditor({
    element: editorRef.value as Element,
    placeholder: '在左侧使用AI生成文章或直接输入文字',
    toolbarKeys: [],
    content: '',
    draggable: false
  })
})
</script>
<style lang="scss" scoped>
.preview-doc {
  height: 100%;
  display: flex;
  flex-direction: column;
  scrollbar-color: auto;
  //background: #f4f8ff !important;

  &-back {
    height: 20px;
    display: flex;
    align-items: center;

    .el-icon {
      margin-right: 6px;
    }

    margin-bottom: 20px;
  }

  &-content {
    display: flex;
    height: calc(100% - 30px);
    box-sizing: border-box;

    &-item {
      width: 50%;
      height: 100%;
      background: #fff;
      border-radius: 10px;
      &:first-child {
        margin-right: 20px;
        //max-width: 65%
      }

      &-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 500;
        font-size: 16px;
        color: #000000;
        padding: 20px;
        //border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        .primary-text {
          border: 1px solid #3067EF;
        }
      }
      &-wrapper {
        height: calc(100% - 90px);
        overflow-y: scroll;
        padding: 10px;
        &:deep(.docx-wrapper) {
          align-items: normal;
          background: transparent;
          overflow-x: scroll;
          padding: 0;

          /* 滚动条样式 */
          &::-webkit-scrollbar {
            width: 6px;
          }

          &::-webkit-scrollbar-track {
            background: transparent;
            border-radius: 2px;
          }

          &::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 10px;
          }
        }
        &:deep(.vue-office-docx .docx-wrapper>section.docx) {
          box-shadow: none;
          overflow: unset !important;
          min-height: unset !important;
          width: 100% !important;
        }
        &:deep(.aie-content) {
          /* 滚动条样式 */
          &::-webkit-scrollbar {
            width: 6px;
          }

          &::-webkit-scrollbar-track {
            background: transparent;
            border-radius: 2px;
          }

          &::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 10px;
          }
        }
      }
    }

  }
  .unsupported-format {
    padding: 20px;
    text-align: center;

    a {
      color: #409eff;
      text-decoration: underline;
      margin: 0 5px;
    }
  }

}
</style>
