<template>
  <div class="container">
    <!-- 左侧知识库列表 -->
    <div class="knowledge-base">
      <h3>选择知识库</h3>
      <div
          v-for="item in knowledgeBaseList"
          :key="item.dataset_id"
          :class="['knowledge-item', { 'active': selectedDatasetIds.includes(item.dataset_id) }]"
          @click="toggleDatasetSelection(item.dataset_id)"
      >
        {{ item.name }}
      </div>
    </div>

    <!-- 右侧搜索框和搜索结果 -->
    <div class="search-area">
      <div class="search-container">
        <el-input
            v-model="query"
            placeholder="请输入搜索内容"
            suffix-icon="el-icon-search"
            @keyup.enter="search"
            class="search-input"
        ></el-input>
        <el-button @click="search" type="primary" style="margin-left: 15px">搜索</el-button>
      </div>
      <!-- 搜索中的提示 -->
      <div v-if="loading" class="loading-spinner">搜索中...</div>
      <div class="search-results">
        <el-card
            v-for="result in searchResults"
            :key="result.contentSummary"
            class="result-card"
            @click="handleDetails(result)"
        >
          <h3>{{ result.contentSummary }}</h3>
          <p>{{ result.content.substring(0, 100) }}...</p>
          <div class="meta">
            <span>相似度: {{ result.score.toFixed(2) }}</span>
            <span>知识库: {{ result.datasetName }}</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>

  <!-- 弹窗：展示完整内容 -->
  <el-dialog v-model="dialogVisible" width="80%">
    <div>
      <h3>{{ selectedResult.contentSummary }}</h3>
      <p>{{ selectedResult.content }}</p>
      <hr />
      <div>
        <h4>原文内容:</h4>
        <p>{{ originalContent }}</p>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

// 存储选择的知识库数据
const knowledgeBaseList = ref([]);
const selectedDatasetIds = ref([]);

// 搜索框输入内容
const query = ref('');

// 存储搜索结果
const searchResults = ref([]);

// 弹窗显示状态
const dialogVisible = ref(false);

// 存储选中的搜索结果
const selectedResult = ref({});

// 存储原文内容
const originalContent = ref('');

// 搜索加载状态
const loading = ref(false);

// 请求知识库列表
const getKnowledgeBaseList = async () => {
  try {
    const response = await fetch('http://127.0.0.1:8001/api/dataset/list');
    const data = await response.json();
    knowledgeBaseList.value = data.data;
  } catch (error) {
    ElMessage.error('获取知识库列表失败');
  }
};

// 选择或取消选择知识库
const toggleDatasetSelection = (datasetId) => {
  const index = selectedDatasetIds.value.indexOf(datasetId);
  if (index === -1) {
    selectedDatasetIds.value.push(datasetId);
  } else {
    selectedDatasetIds.value.splice(index, 1);
  }
};

// 执行搜索操作
const search = async () => {
  if (!query.value.trim()) {
    ElMessage.warning('请输入搜索内容');
    return;
  }

  if (selectedDatasetIds.value.length === 0) {
    ElMessage.warning('请先选择知识库');
    return;
  }

  loading.value = true; // 开始搜索时显示加载提示
  const datasetIds = selectedDatasetIds.value.join(',');
  try {
    const response = await fetch(`http://127.0.0.1:8001/api/query?query=${query.value}&datasetIds=${datasetIds}`);
    const data = await response.json();
    searchResults.value = data.data.results.map((item) => ({
      ...item,
      // 这里只是简化了展示，可以将 datasetName 从返回结果中提取
    }));
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false; // 搜索结束后隐藏加载提示
  }
};

// 展示选中的搜索结果的完整内容
const handleDetails = async (result) => {
  selectedResult.value = result;
  dialogVisible.value = true; // 打开弹窗

  // 请求完整内容
  try {
    const response = await fetch(`http://127.0.0.1:8001/api/content/get?docId=${result.docId}`);
    const data = await response.json();
    if (data.status_code === 200) {
      originalContent.value = data.data.text; // 显示原文内容
    } else {
      ElMessage.error('获取原文内容失败');
    }
  } catch (error) {
    ElMessage.error('请求原文内容失败');
  }
};

// 页面初始化加载知识库列表
onMounted(() => {
  getKnowledgeBaseList();
});
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  height: 100vh; /* 设置容器高度为视口高度 */
}

.knowledge-base {
  width: 20%;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  height: 100%; /* 确保高度为100% */
  overflow-y: auto; /* 启用垂直滚动 */
}

.knowledge-item {
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  margin: 5px 0;
  transition: background-color 0.3s ease;
}

.knowledge-item:hover {
  background-color: #e6f7ff;
}

.knowledge-item.active {
  background-color: #b3d8ff;
}

.search-area {
  width: 75%;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: 100%; /* 确保高度为100% */
  overflow-y: auto; /* 启用垂直滚动 */
}

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 60%; /* 控制搜索框的宽度 */
}

.result-card {
  margin-top: 10px;
  cursor: pointer;
}

.result-card:hover {
  background-color: #f5f5f5;
}

.meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #888;
}

.loading-spinner {
  text-align: center;
  font-size: 16px;
  color: #888;
  margin-top: 20px;
}

</style>
