<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"
            class="search-input"
        ></el-input>
        <!-- 当 loading 时禁用按钮 -->
        <el-button
            @click="chat"
            type="primary"
            :disabled="loading"
            style="margin-left: 15px"
        >
          {{ "提问" }}
        </el-button>
      </div>


      <!-- 搜索中的提示 -->
      <div v-if="loading" class="loading-spinner">回答中...</div>
      <!-- 展示 chat_res 数据 -->
      <div v-if="chatSummary" class="chat-summary">
        <h4>回答内容</h4>
        <div v-html="parsedChatSummary"></div> <!-- 这里将解析后的内容渲染到页面 -->
      </div>
      <div class="search-results">
        <!-- 只有当 searchResults 不为空时才显示外层的卡片 -->
        <el-card v-if="searchResults.length > 0" class="search-card">
          <h4>搜索内容</h4> <!-- 新增标题 "搜索内容" -->

          <!-- 现有的搜索结果卡片循环 -->
          <div v-for="result in searchResults" :key="result.contentSummary">
            <el-card
                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>
        </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, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { marked } from 'marked';
import {API_BASE_URL} from "@/config";  // 使用命名导入

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

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

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

// 存储chat_res总结
const chatSummary = ref('');

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

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

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

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

// 请求知识库列表
const getKnowledgeBaseList = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/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 chat = async () => {
  if (loading.value) return; // 防止重复调用
  if (!query.value.trim()) {
    ElMessage.warning('请输入提问内容');
    return;
  }

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

  chatSummary.value = '';
  searchResults.value = [];
  selectedResult.value = {};
  originalContent.value = '';

  loading.value = true; // 开始搜索时显示加载提示
  const datasetIds = selectedDatasetIds.value.join(',');
  try {
    const response = await fetch(`${API_BASE_URL}/chat?query=${query.value}&datasetIds=${datasetIds}`);
    const data = await response.json();
    searchResults.value = data.data.results.map((item) => ({
      ...item,
    }));

    // 获取并设置 chat_res
    if (data.data.chat_res) {
      chatSummary.value = data.data.chat_res;
    }

  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false; // 搜索结束后隐藏加载提示
  }
};

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

  // 请求完整内容
  try {
    const response = await fetch(`${API_BASE_URL}/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('请求原文内容失败');
  }
};

// 计算属性：解析 chatSummary（如果是 Markdown 则解析）
const parsedChatSummary = computed(() => {
  if (chatSummary.value) {
    // 分开检查 Markdown 格式的常见符号
    const markdownSymbols = /[#*+\-`>!]/;  // 检测 Markdown 中常见的特殊字符
    const isMarkdown = markdownSymbols.test(chatSummary.value);

    // 如果检测到 Markdown 符号，解析为 Markdown 格式
    if (isMarkdown) {
      return marked(chatSummary.value);  // 使用 marked 库解析 Markdown
    }
  }
  return chatSummary.value;  // 如果不是 Markdown 格式，直接返回文本
});


// 页面初始化加载知识库列表
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;
}

.chat-summary {
  background-color: #f0f8ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.chat-summary h4 {
  font-size: 18px;
  font-weight: bold;
}

.chat-summary p {
  font-size: 14px;
  line-height: 1.5;
}
</style>
