<template>
  <div class="result-card">
    <h3 class="result-title" @click.stop="$emit('fragment', item)">
      <span class="title-text">{{ item.title }}</span>
    </h3>
    <div class="result-meta">
      <el-tag v-if="item.doc_type && item.doc_type !== '-'" size="small" class="meta-tag">
        {{ item.doc_type }}
      </el-tag>
      <el-tag v-if="item.department && item.department !== '-'" size="small" class="meta-tag dept-tag">
        {{ item.department }}
      </el-tag>
      <span v-if="item.publish_date" class="meta-info">
        <el-icon><Calendar /></el-icon>
        {{ formatDate(item.publish_date) }}
      </span>
      <span v-if="item.view_count !== undefined" class="meta-info">
        <el-icon><View /></el-icon>
        {{ item.view_count }} 次浏览
      </span>
    </div>
    <p
      class="result-abstract"
      v-html="renderMath(truncateText(item.highlighted_text || item.abstract || '', 300))"
      @click.stop="$emit('fragment', item)"
    ></p>
    <div class="result-tags" v-if="item.tags && item.tags.length">
      <el-tag v-for="tag in item.tags" :key="tag" size="small" class="custom-tag">
        {{ tag }}
      </el-tag>
    </div>
    <div class="result-actions">
      <el-button size="small" class="action-btn" @click.stop="$emit('preview', item)">
        <el-icon><View /></el-icon> 文档预览
      </el-button>
      <el-button size="small" class="action-btn download-btn" @click.stop="$emit('download', item)">
        <el-icon><Download /></el-icon> 下载
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { View, Download, Calendar } from '@element-plus/icons-vue'
import katex from 'katex'

defineProps<{ item: any; keyword: string }>()
defineEmits<{ preview: [item: any]; download: [item: any]; fragment: [item: any] }>()

function formatDate(dateStr: string): string {
  if (!dateStr) return '-'
  return dateStr.split(' ')[0]
}

function renderMath(text: string): string {
  if (!text) return ''
  let result = text.replace(/\$\$([\s\S]*?)\$\$/g, (_, math) => {
    try {
      return katex.renderToString(math, { throwOnError: false, displayMode: true })
    } catch {
      return `<span class="katex-error">${_}</span>`
    }
  })
  result = result.replace(/\$([\s\S]*?)\$/g, (_, math) => {
    try {
      return katex.renderToString(math, { throwOnError: false, displayMode: false })
    } catch {
      return `<span class="katex-error">${_}</span>`
    }
  })
  return result
}

function truncateText(html: string, maxLength: number): string {
  if (html.length <= maxLength) return html

  let count = 0
  let cutIndex = 0
  let inTag = false

  for (let i = 0; i < html.length; i++) {
    const char = html[i]
    if (char === '<') {
      inTag = true
    } else if (char === '>') {
      inTag = false
    } else if (!inTag) {
      count++
      if (count >= maxLength) {
        cutIndex = i + 1
        break
      }
    }
  }

  let result = html.substring(0, cutIndex)

  const openTags: string[] = []
  const tagRegex = /<\/?([a-zA-Z]+)(?:\s[^>]*)?>/g
  let match
  const truncated = result
  while ((match = tagRegex.exec(truncated)) !== null) {
    const tag = match[1].toLowerCase()
    if (match[0].startsWith('</')) {
      if (openTags.length > 0 && openTags[openTags.length - 1] === tag) {
        openTags.pop()
      }
    } else {
      if (!['br', 'hr', 'img', 'input', 'meta', 'link'].includes(tag)) {
        openTags.push(tag)
      }
    }
  }

  while (openTags.length > 0) {
    result += `</${openTags.pop()}>`
  }

  return result + '...'
}
</script>

<style scoped>
.result-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px 24px;
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #f0f0f0;
}
.result-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}
.result-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px;
  font-weight: 600;
  line-height: 1.5;
  cursor: pointer;
  transition: color 0.2s;
}
.result-title:hover {
  color: #f5a623;
}
.title-text {
  flex: 1;
}
.result-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}
.meta-tag {
  border: 1px solid #e8e8e8;
  background: #fafafa;
  color: #909399;
  font-size: 12px;
  padding: 1px 8px;
  border-radius: 2px;
  height: auto;
}
.dept-tag {
  border-color: #d9ecff;
  background: #ecf5ff;
  color: #409eff;
}
.meta-info {
  font-size: 12px;
  color: #b0b0b0;
  display: flex;
  align-items: center;
  gap: 4px;
}
.meta-info :deep(.el-icon) {
  font-size: 14px;
}
.result-abstract {
  font-size: 13px;
  color: #666;
  line-height: 1.8;
  margin: 0 0 12px;
  cursor: pointer;
  transition: color 0.2s;
}
.result-abstract:hover {
  color: #333;
}
.result-abstract :deep(em) {
  color: #f5a623;
  font-style: normal;
  font-weight: 600;
}
.result-tags {
  display: flex;
  gap: 6px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}
.custom-tag {
  border: 1px solid #d9ecff;
  background: #f5f9ff;
  color: #409eff;
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 2px;
  height: auto;
}
.result-actions {
  display: flex;
  gap: 12px;
  padding-top: 4px;
}
.action-btn {
  border-radius: 4px;
  padding: 6px 16px;
  font-size: 13px;
}
.action-btn :deep(.el-icon) {
  margin-right: 4px;
}
.download-btn {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.download-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}
</style>
