<template>
  <div class="search-test">
    <a-input-search
      v-model:value="searchQuery"
      placeholder="输入查询内容测试检索效果"
      enter-button="检索"
      size="large"
      :loading="kbStore.isSearching"
      @search="handleSearch"
    />

    <div v-if="kbStore.searchResults.length > 0" class="search-results">
      <a-divider>检索结果 ({{ kbStore.searchResults.length }})</a-divider>
      <div
        v-for="(result, index) in kbStore.searchResults"
        :key="index"
        class="search-result-item"
      >
        <div class="search-result-item__header">
          <span class="search-result-item__index">#{{ index + 1 }}</span>
          <a-tag color="blue">{{ result.source }}</a-tag>
          <span class="search-result-item__score">
            相关度: {{ (result.score * 100).toFixed(1) }}%
          </span>
        </div>
        <div class="search-result-item__content">
          {{ result.content }}
        </div>
        <div v-if="Object.keys(result.metadata).length > 0" class="search-result-item__meta">
          <a-tag v-for="(value, key) in result.metadata" :key="String(key)" size="small">
            {{ key }}: {{ value }}
          </a-tag>
        </div>
      </div>
    </div>

    <a-empty
      v-else-if="hasSearched && !kbStore.isSearching"
      description="未找到相关结果"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useKnowledgeStore } from '@/stores/knowledge'

const kbStore = useKnowledgeStore()
const searchQuery = ref('')
const hasSearched = ref(false)

async function handleSearch(): Promise<void> {
  if (!searchQuery.value.trim()) return
  hasSearched.value = true
  await kbStore.search(searchQuery.value)
}
</script>

<style scoped>
.search-test {
  padding: 8px 0;
}

.search-results {
  margin-top: 16px;
}

.search-result-item {
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 12px;
}

.search-result-item__header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.search-result-item__index {
  font-weight: 600;
  color: #1677ff;
}

.search-result-item__score {
  margin-left: auto;
  font-size: 12px;
  color: #999;
}

.search-result-item__content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

.search-result-item__meta {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
</style>
