<script setup lang="ts">
import { ref } from 'vue'
import { search } from '@/api/troubleshoot'
import { renderMarkdown } from '@/utils/markdown'
import http from '@/utils/http'
import type { MatchedCase } from '@/types/troubleshoot'
import { ElMessage } from 'element-plus'

const keyword = ref('')
const searching = ref(false)
const searched = ref(false)
const results = ref<MatchedCase[]>([])
const matchedCount = ref(0)
const searchTime = ref(0)

// 记录详情弹窗
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailContent = ref('')
const detailTitle = ref('')
const detailRecordId = ref('')

async function doSearch() {
  const q = keyword.value.trim()
  if (!q) return
  searching.value = true
  try {
    const res = await search({ query: q })
    if (res.success) {
      results.value = res.matched_cases
      matchedCount.value = res.matched_count
      searchTime.value = res.search_time
      searched.value = true
    } else {
      ElMessage.error('搜索失败')
    }
  } catch {
    ElMessage.error('搜索异常，请稍后重试')
  } finally {
    searching.value = false
  }
}

const emit = defineEmits<{ exit: [] }>()

function clearSearch() {
  keyword.value = ''
  results.value = []
  searched.value = false
  matchedCount.value = 0
  emit('exit')
}

async function showRecordDetail(c: MatchedCase) {
  if (!c.record_id) return
  detailRecordId.value = c.record_id
  detailTitle.value = c.title
  detailContent.value = ''
  detailLoading.value = true
  detailVisible.value = true
  try {
    const res = await http.get(`/api/troubleshoot/record/${c.record_id}`)
    if (res.data?.success && res.data.record) {
      detailContent.value = res.data.record.full_text || ''
      detailTitle.value = res.data.record.title || c.title
    } else {
      detailContent.value = '记录加载失败'
    }
  } catch {
    detailContent.value = '记录加载失败'
  } finally {
    detailLoading.value = false
  }
}

function downloadRecord() {
  if (!detailRecordId.value) return
  window.open(`/api/troubleshoot/record/${detailRecordId.value}/download`, '_blank')
}

// 相似度百分比
function scorePercent(score: number): string {
  return (score * 100).toFixed(0) + '%'
}
</script>

<template>
  <div class="search-results-panel">
    <!-- 搜索框 -->
    <div class="search-bar">
      <el-input
        v-model="keyword"
        placeholder="搜索历史问题案例..."
        clearable
        size="large"
        :prefix-icon="'Search'"
        @keyup.enter="doSearch"
        @clear="clearSearch"
      >
        <template #append>
          <el-button :loading="searching" @click="doSearch">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searched" class="result-area">
      <div class="result-header">
        <span class="result-count">共匹配 {{ matchedCount }} 个相关案例</span>
        <span class="result-time" v-if="searchTime">耗时 {{ searchTime }}s</span>
        <el-button link type="primary" size="small" @click="clearSearch">返回产品浏览</el-button>
      </div>

      <!-- 空结果 -->
      <div v-if="results.length === 0" class="empty-state">
        <div class="empty-icon">🔍</div>
        <h3>未找到相关案例</h3>
        <p>换个关键词试试，或从左侧产品列表浏览</p>
      </div>

      <!-- 结果列表 -->
      <div v-else class="result-list">
        <div
          v-for="(c, i) in results"
          :key="c.record_id"
          class="result-item"
          @click="showRecordDetail(c)"
        >
          <div class="result-top">
            <span class="result-index">{{ i + 1 }}</span>
            <span class="result-title">{{ c.title }}</span>
            <span class="result-score">{{ scorePercent(c.score) }}</span>
          </div>
          <div class="result-meta">
            <span v-if="c.project" class="result-project">🏷 {{ c.project }}</span>
            <span v-if="c.phenomenon" class="result-phenomenon">{{ c.phenomenon }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 未搜索时的引导 -->
    <div v-else class="idle-state">
      <div class="idle-icon">💡</div>
      <h3>全局搜索</h3>
      <p>输入问题关键词，全文搜索历史案例</p>
      <p class="idle-hint">例如：门口屏 MQTT 绑定失败、无纸化平板离线</p>
    </div>

    <!-- 记录详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      :title="detailTitle"
      width="700px"
      destroy-on-close
    >
      <div v-loading="detailLoading" class="record-detail-content">
        <div
          v-if="detailContent"
          class="record-detail-md"
          v-html="renderMarkdown(detailContent)"
        />
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadRecord">
          📥 下载文档
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-results-panel {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  min-height: 400px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.search-bar {
  margin-bottom: 20px;
}

.result-area {
  .result-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding-bottom: 12px;
    margin-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .result-count {
      font-size: 14px;
      font-weight: 500;
      color: #1d2129;
    }
    .result-time {
      font-size: 12px;
      color: #86909c;
    }
    .el-button {
      margin-left: auto;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
  color: #86909c;
  .empty-icon { font-size: 56px; margin-bottom: 16px; opacity: 0.5; }
  h3 { font-size: 16px; font-weight: 500; color: #4e5969; margin: 0 0 8px; }
  p { font-size: 14px; margin: 0; }
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-item {
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 10px;
  padding: 14px 18px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #f7f9fc;
    border-color: #e0e7ff;
    box-shadow: 0 2px 8px rgba(22, 125, 255, 0.08);
  }
}

.result-top {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;

  .result-index {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 6px;
    background: #e8f3ff;
    color: #165dff;
    font-size: 12px;
    font-weight: 600;
    flex-shrink: 0;
  }
  .result-title {
    flex: 1;
    font-size: 15px;
    font-weight: 500;
    color: #1d2129;
    line-height: 1.5;
  }
  .result-score {
    flex-shrink: 0;
    font-size: 12px;
    font-weight: 600;
    color: #165dff;
    background: #e8f3ff;
    padding: 2px 8px;
    border-radius: 12px;
  }
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
  color: #86909c;

  .result-project {
    flex-shrink: 0;
    color: #4e5969;
  }
  .result-phenomenon {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.idle-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 280px;
  color: #86909c;

  .idle-icon { font-size: 56px; margin-bottom: 16px; opacity: 0.6; }
  h3 { font-size: 16px; font-weight: 500; color: #4e5969; margin: 0 0 8px; }
  p { font-size: 14px; margin: 0 0 4px; }
  .idle-hint { color: #c9cdd4; font-size: 13px; }
}

.record-detail-content {
  min-height: 200px;
  max-height: 60vh;
  overflow-y: auto;
}
.record-detail-md { line-height: 1.8; }
</style>