<template>
  <div class="text-viewer">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-wrapper">
      <i class="el-icon-loading" />
      <span>文件加载中...</span>
    </div>

    <!-- 错误状态 -->
    <el-empty v-else-if="error" :description="error" />

    <!-- 内容展示 -->
    <template v-else>
      <!-- Markdown渲染 -->
      <div
        v-if="fileType === 'md'"
        class="markdown-body"
        v-html="compiledMarkdown"
      />

      <!-- 纯文本渲染 -->
      <pre
        v-else
        class="plain-text"
      >{{ content }}</pre>

      <!-- 下载按钮 -->
      <el-button
        class="download-btn"
        type="primary"
        size="mini"
        @click="handleDownload"
      >
        <i class="el-icon-download" /> 下载
      </el-button>
    </template>

    <!-- 隐藏的iframe用于模拟手动访问 -->
    <iframe ref="authIframe" style="display: none"/>

  </div>
</template>

<script>
import marked from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import 'github-markdown-css'
import request from '@/utils/request'

export default {
  props: {
    url: {
      type: String,
      required: true
    },
    webUrl: {
      type: String,
      required: true
    },
    fileType: {
      type: String,
      required: true,
      validator: value => ['txt', 'md'].includes(value)
    }
  },
  data() {
    return {
      content: '',
      loading: false,
      error: ''
    }
  },
  computed: {
    compiledMarkdown() {
      if (this.fileType !== 'md') return ''
      try {
        return marked(this.content, {
          highlight: code => hljs.highlightAuto(code).value,
          breaks: true
        })
      } catch (e) {
        this.error = 'Markdown解析失败'
        return this.content
      }
    }
  },
  watch: {
    url: {
      immediate: true,  // 立即执行一次
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => this.loadContent())
        }
      }
    }
  },
  methods: {
    async loadContent() {
      this.loading = true
      this.error = ''

      console.log("112221====>>> " +this.url);
      // 确保iframe元素存在后再设置src
      if (this.$refs.authIframe) {
        this.$refs.authIframe.src = this.url

        // 监听iframe加载完成事件
        this.$refs.authIframe.onload = () => {
          this.afterAuthIframeLoaded()
        }
      }

    },

    async afterAuthIframeLoaded() {
      try {
        // 使用若依框架封装的request方法
        const response = await request({
          url: this.url,
          method: 'get',
        })

        if (response === null || response === undefined) {
          this.error = '文件加载失败'
          return
        }

        this.content = response
      } catch (e) {
        console.error('文件加载失败:', e)
        this.error = `文件加载失败: ${e.message || '网络错误'}`
      } finally {
        this.loading = false
      }
    },

    handleDownload() {
      try {
        const link = document.createElement('a')
        link.href = this.webUrl
        link.target = '_blank'
        link.rel = 'noopener noreferrer'
        link.click()
      } catch (e) {
        this.$message.error('下载失败: ' + e.message)
      }
    }
  }
}
</script>

<style scoped>
.text-viewer {
  position: relative;
  padding: 15px;
}

.loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.loading-wrapper i {
  margin-right: 8px;
  font-size: 18px;
}

.markdown-body {
  padding: 20px;
}

.plain-text {
  white-space: pre-wrap;
  font-family: Consolas, Monaco, monospace;
  line-height: 1.6;
  margin: 0;
}

.download-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
}

</style>
