import { documentsList, findDataInfo } from '../../api/documentManagement'

export default {
  name: 'ApiFile',
  data() {
    return {
      listParams: {
        lang: `${this.$i18n.locale}`,
        childType: 3,
        pageNum:1,
        pageSize:50
      },
      DetailsParams: {
        lang: `${this.$i18n.locale}`,
        childType:3,//1服务条款、2费率、3API文档  childType
      },
      navContent: {},
      documentLoading: true,
      documentContent: '',
      documentError: '',
      navList:[],
      info: '',
      contentShow:false,
    }
  },
  mounted() {
    this.getDocumentsList(this.listParams)
   
  },
  methods: {
    async getDocumentsList(params) {
      try {
        const res = await documentsList(params)
        this.setLoading('documentLoading', true);
        if (res && res.code === 200) {
          this.navList = res.rows
        
          if (this.$route.query.id) {
              this.DetailsParams.id = this.$route.query.id
             
          }else{
              this.DetailsParams.id = res.rows[0].id;                
          }
          if (this.DetailsParams.id) {
              this.fetchProblemDetails(this.DetailsParams)
          }
          
        }
      
     

       
      } catch (error) {
        console.error('获取文档列表失败:', error)
      }
    },
    
    async fetchProblemDetails(params) {
      this.setLoading('documentLoading', true);
      const res = await findDataInfo(params)
      if(res && res.code === 200){
     
          this.info = res.data.content || ""
          this.contentShow = true
      }
      this.setLoading('documentLoading', false);
  },

  backMenu(){
    this.contentShow = false
  },


    // async getDocumentsInfo(params) {
    //   this.documentLoading = true
    //   this.documentError = ''
      
    //   try {
    //     const res = await findDataInfo(params)
    //     console.log('文档详情:', res)
        
    //     if (res && res.code === 200 && res.data) {
    //       this.navContent = res.data
    //       // 将Markdown内容转换为HTML
    //       this.documentContent = this.markdownToHtml(res.data.content || '')
    //     } else {
    //       this.documentError = '获取文档失败: ' + (res?.msg || '未知错误')
    //     }
    //   } catch (error) {
    //     console.error('获取文档详情失败:', error)
    //     this.documentError = '获取文档失败: ' + (error.message || '网络错误')
    //   } finally {
    //     this.documentLoading = false
    //   }
    // },

    /**
     * 改进的Markdown转HTML方法
     * @param {string} markdown - Markdown内容
     * @returns {string} - HTML内容
     */
    markdownToHtml(markdown) {
      if (!markdown) return ''
      
      // 先处理表格（在换行处理之前）
      let html = this.processMarkdownTables(markdown)
      
      html = html
        // 标题处理
        .replace(/^### (.*$)/gim, '<h3>$1</h3>')
        .replace(/^## (.*$)/gim, '<h2>$1</h2>')
        .replace(/^# (.*$)/gim, '<h1>$1</h1>')
        // 粗体和斜体
        .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/gim, '<em>$1</em>')
        // 代码块
        .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
        .replace(/`([^`]*)`/gim, '<code>$1</code>')
        // 链接
        .replace(/\[([^\]]*)\]\(([^)]*)\)/gim, '<a href="$2" target="_blank">$1</a>')

      // 处理段落和换行（避免影响表格）
      const parts = html.split(/(<table[\s\S]*?<\/table>)/g)
      html = parts.map(part => {
        if (part.startsWith('<table')) {
          return part // 保持表格不变
        }
        return part
          .replace(/\n\n/gim, '</p><p>')
          .replace(/\n/gim, '<br>')
      }).join('')

      // 包装段落
      if (html && !html.startsWith('<') && !html.includes('<table')) {
        html = '<p>' + html + '</p>'
      }

      return html
    },

    /**
     * 处理Markdown表格
     * @param {string} text - 包含表格的文本
     * @returns {string} - 转换后的HTML
     */
    processMarkdownTables(text) {
      // 匹配Markdown表格的正则表达式
      const tableRegex = /(\|.*\|[\r\n]+)+/g
      
      return text.replace(tableRegex, (match) => {
        const lines = match.trim().split(/[\r\n]+/)
        if (lines.length < 2) return match
        
        let html = '<table border="1" style="border-collapse: collapse; width: 100%; margin: 15px 0;">\n'
        
        lines.forEach((line, index) => {
          line = line.trim()
          if (!line.startsWith('|') || !line.endsWith('|')) return
          
          // 移除首尾的 |
          const content = line.slice(1, -1)
          const cells = content.split('|').map(cell => cell.trim())
          
          // 跳过分隔线（包含 --- 的行）
          if (cells.some(cell => /^-+$/.test(cell))) return
          
          const isHeader = index === 0
          const tag = isHeader ? 'th' : 'td'
          const style = isHeader ? 
            ' style="background: #f8f9fa; font-weight: 600; padding: 8px 12px; border: 1px solid #ddd; text-align: left;"' :
            ' style="padding: 8px 12px; border: 1px solid #ddd; text-align: left;"'
          
          html += '  <tr>\n'
          cells.forEach(cell => {
            html += `    <${tag}${style}>${cell}</${tag}>\n`
          })
          html += '  </tr>\n'
        })
        
        html += '</table>\n'
        return html
      })
    },
    
    clickJump(item) {
           
      this.DetailsParams.id = item.id
      this.fetchProblemDetails(this.DetailsParams)
    
  },
  }
}