<template>
  <a-modal
    v-model:open="modalOpen"
    :title="modalTitle"
    width="880px"
    @ok="emit('openDetail', currentDocId || '')"
  >
    <template #footer>
      <a-button @click="modalOpen = false">关闭</a-button>
      <a-button v-if="showImport" @click="emit('import', currentDocId || '')">加入资料篮</a-button>
      <a-button v-if="showOpenDetail" type="primary" @click="emit('openDetail', currentDocId || '')">打开详情</a-button>
    </template>

    <a-spin :spinning="loading">
      <template v-if="document">
        <div class="quick-preview">
          <div class="quick-preview__header">
            <h3>{{ document.title }}</h3>
          </div>

          <a-row :gutter="16">
            <a-col :span="9">
              <a-card size="small" title="元数据">
                <a-descriptions :column="1" size="small">
                  <a-descriptions-item label="文号">{{ document.doc_number || '-' }}</a-descriptions-item>
                  <a-descriptions-item label="发文机关">{{ document.issuing_org || '-' }}</a-descriptions-item>
                  <a-descriptions-item label="文种">{{ document.doc_type || '-' }}</a-descriptions-item>
                  <a-descriptions-item label="发文日期">{{ document.publish_date || '-' }}</a-descriptions-item>
                  <a-descriptions-item label="知识分类">
                    <a-tag v-if="document.knowledge_category" color="green">{{ document.knowledge_category }}</a-tag>
                    <span v-else>-</span>
                  </a-descriptions-item>
                  <a-descriptions-item label="主题词">
                    <a-space wrap>
                      <a-tag v-for="tag in document.subject_words" :key="tag" class="subject-word-tag">{{ tag }}</a-tag>
                      <span v-if="!document.subject_words?.length">-</span>
                    </a-space>
                  </a-descriptions-item>
                </a-descriptions>
              </a-card>

              <a-card v-if="document.summary" size="small" title="摘要" class="quick-preview__summary-card">
                <div class="quick-preview__summary">{{ document.summary }}</div>
              </a-card>
            </a-col>

            <a-col :span="15">
              <a-card size="small" title="命中内容">
                <!-- 使用 matched_chunks 展示结构化信息 -->
                <div v-if="matchedChunksData.length" class="quick-preview__chunks">
                  <div
                    v-for="(chunk, index) in matchedChunksData.slice(0, 3)"
                    :key="index"
                    class="chunk-block"
                  >
                    <div class="chunk-location">
                      <span v-if="chunk.page_number" class="chunk-tag">
                        <FileTextOutlined /> 第 {{ chunk.page_number }} 页
                      </span>
                      <span v-else-if="chunk.page_numbers?.length" class="chunk-tag">
                        <FileTextOutlined /> 第 {{ chunk.page_numbers.join('-') }} 页
                      </span>
                      <span v-if="chunk.chunk_index != null" class="chunk-tag">
                        第 {{ chunk.chunk_index + 1 }} 段
                      </span>
                      <span v-if="chunk.element_type" class="chunk-tag chunk-tag--type">
                        {{ elementTypeLabel(chunk.element_type) }}
                      </span>
                    </div>
                    <div
                      v-if="chunk.heading_hierarchy?.length"
                      class="chunk-heading"
                    >
                      <span v-for="(h, i) in chunk.heading_hierarchy" :key="i">
                        {{ h }}<span v-if="i < chunk.heading_hierarchy.length - 1" class="heading-sep"> / </span>
                      </span>
                    </div>
                    <div class="chunk-text" v-html="'...' + sanitizeHtml(chunk.text) + '...'" />
                  </div>
                </div>

                <!-- fallback: 只有 highlights 没有 matched_chunks -->
                <div v-else-if="resolvedHighlights.length" class="quick-preview__highlights">
                  <div
                    v-for="(highlight, index) in resolvedHighlights.slice(0, 3)"
                    :key="index"
                    class="highlight-block"
                    v-html="'...' + sanitizeHtml(highlight) + '...'"
                  />
                </div>

                <a-empty v-if="!resolvedHighlights.length && !matchedChunksData.length" description="暂无命中内容" />
              </a-card>
            </a-col>
          </a-row>
        </div>
      </template>

      <a-empty v-else-if="!loading" description="未找到文档预览信息" />
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { FileTextOutlined } from '@ant-design/icons-vue'
import { getDocumentDetail } from '@/api/document'
import { sanitizeHtml } from '@/utils/sanitize'
import type { DocumentDetail } from '@/types/document'
import type { MatchedChunk } from '@/types/search'

const props = defineProps<{
  open: boolean
  docId?: string
  highlights?: string[]
  matchedChunks?: MatchedChunk[]
  fallbackText?: string
  showImport?: boolean
  showOpenDetail?: boolean
  title?: string
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'openDetail', docId: string): void
  (e: 'import', docId: string): void
}>()

const loading = ref(false)
const document = ref<DocumentDetail | null>(null)

const currentDocId = computed(() => props.docId)
const highlights = computed(() => props.highlights || [])
const matchedChunksData = computed(() => props.matchedChunks || [])
const resolvedHighlights = computed(() => {
  if (highlights.value.length) return highlights.value
  if (props.fallbackText?.trim()) return [props.fallbackText.trim()]
  if (document.value?.summary?.trim()) return [document.value.summary.trim()]
  return []
})
const showImport = computed(() => props.showImport !== false)
const showOpenDetail = computed(() => props.showOpenDetail !== false)
const modalTitle = computed(() => props.title || '文档快速预览')

const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value),
})

function elementTypeLabel(type: string): string {
  const map: Record<string, string> = {
    paragraph: '段落',
    table: '表格',
    list: '列表',
    title: '标题',
    header: '页眉',
    footer: '页脚',
    figure: '图片',
    caption: '图注',
  }
  return map[type] || type
}

async function loadPreview() {
  if (!currentDocId.value) {
    document.value = null
    return
  }

  loading.value = true
  try {
    document.value = await getDocumentDetail(currentDocId.value)
  } catch {
    document.value = null
  } finally {
    loading.value = false
  }
}

watch(
  () => [props.open, currentDocId.value],
  ([open, docId]) => {
    if (open && docId) {
      loadPreview()
    }
  },
  { immediate: true },
)
</script>

<style scoped lang="less">
.quick-preview {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quick-preview__header {
  h3 {
    margin: 0;
  }
}

.subject-word-tag {
  color: #1890ff;
  background: #e6f7ff;
  border-color: #91d5ff;
}

// ── Matched chunks ──────────────────────────────────────────────
.quick-preview__chunks {
  .chunk-block {
    margin-bottom: 12px;
    padding: 10px 12px;
    background: #fafafa;
    border-radius: 8px;
    border-left: 3px solid #bae7ff;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .chunk-location {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 6px;
  }

  .chunk-tag {
    display: inline-flex;
    align-items: center;
    gap: 3px;
    font-size: 12px;
    color: #1890ff;
    background: #e6f7ff;
    border: 1px solid #91d5ff;
    border-radius: 4px;
    padding: 0 6px;
    line-height: 20px;

    &--type {
      color: #722ed1;
      background: #f9f0ff;
      border-color: #d3adf7;
    }
  }

  .chunk-heading {
    font-size: 12px;
    color: #8c8c8c;
    margin-bottom: 4px;

    .heading-sep {
      color: #d9d9d9;
    }
  }

  .chunk-text {
    font-size: 13px;
    color: #595959;
    line-height: 1.7;

    :deep(em) {
      color: #f5222d;
      font-style: normal;
      background: #fff1f0;
      padding: 0 2px;
      border-radius: 2px;
    }
  }
}

// ── Fallback highlights ─────────────────────────────────────────
.quick-preview__highlights {
  margin-bottom: 12px;
}

.highlight-block {
  margin-bottom: 8px;
  padding: 8px 10px;
  background: #fafafa;
  border-radius: 8px;
  line-height: 1.6;

  :deep(em) {
    color: #f5222d;
    font-style: normal;
    background: #fff1f0;
    padding: 0 2px;
    border-radius: 2px;
  }
}

.quick-preview__summary-card {
  margin-top: 12px;
}

.quick-preview__summary {
  white-space: pre-wrap;
  line-height: 1.7;
  color: #595959;
  font-size: 13px;
}
</style>
