<template>
  <div class="knowledge-results">
    <!-- 搜索框 -->
    <div class="search-box">
     <!--  <div class="input-wrapper">
        <input
          v-model="searchQuery"
          type="text"
          :placeholder="placeholder"
          @keyup.enter="handleSearch"
          class="search-input"
        />
        <span 
          v-if="searchQuery" 
          class="clear-icon" 
          @click="clearSearch"
        >×</span>
      </div> -->
      <!-- <button @click="handleSearch" :disabled="isSearching" class="search-button">
        {{ isSearching ? '搜索中...' : '搜索' }}
      </button> -->
    </div>

    <!-- 搜索结果列表 -->
    <div 
      v-if="!loading && searchResults.length > 0" 
      class="results-container" 
      ref="resultsContainer" 
      @scroll="handleScroll"
    >
      <div v-for="result in displayResults" :key="result.id" class="result-item">
        <h3 class="result-title">
          <a :href="result.link" target="_blank" rel="noopener noreferrer">{{ result.title }}</a>
        </h3>
        <div class="result-content" v-html="formatContent(result.content)"></div>
        <div v-if="result.translation" class="result-translation">
          <span class="translation-label">中文释义：</span>
          <span class="translation-content">{{ result.translation }}</span>
        </div>
        <div class="result-meta">
          <span class="result-source">来源: {{ result.source || '知识库' }}</span>
          <span class="result-date">{{ formatDate(result.date) }}</span>
        </div>
      </div>

      <!-- 加载更多指示器 -->
      <div v-if="hasMore" class="load-more">
        <div class="loading-spinner"></div>
        <span>加载更多...</span>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>正在搜索...</p>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
     <!--  <div class="empty-icon">🔍</div>
      <p>{{ searchQuery ? '未找到相关内容' : '请输入关键词搜索' }}</p> -->
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, computed, watch } from 'vue';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'KnowledgeResults',
  
  props: {
    searchResults: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    total: {
      type: Number,
      default: 0
    },
    message: {
      type: String,
      default: ''
    },
    // 添加搜索类型属性
    searchType: {
      type: String,
      default: 'remote', // 'remote' 或 'local'
      validator: (value) => ['remote', 'local'].includes(value)
    },
    // 添加是否显示中文释义的配置
    showTranslation: {
      type: Boolean,
      default: true
    }
  },

  emits: ['update:enableSearch', 'search', 'translate'],

  setup(props, { emit }) {
    const searchQuery = ref('');
    const isSearching = ref(false);
    const hasMore = ref(false);
    const displayResults = ref([]);
    const page = ref(1);
    const pageSize = ref(20);

    // 计算属性：根据搜索类型显示不同的占位符
    const placeholder = computed(() => {
      return props.searchType === 'local' ? '搜索本地知识库...' : '搜索远程知识库...';
    });

    // 监听搜索结果变化
    watch(() => props.searchResults, (newResults) => {
      console.log('New search results:', newResults);
      displayResults.value = newResults.map(result => ({
        ...result,
        translation: result.translation || '' // 确保translation字段存在
      }));
    });

    // 监听 message prop 的变化
    watch(() => props.message, (newMessage) => {
      if (newMessage) {
        searchQuery.value = newMessage;
        handleSearch();
      }
    });

    // 处理搜索
    const handleSearch = async () => {
      if (!searchQuery.value.trim() || isSearching.value) return;
      isSearching.value = true;
      page.value = 1; // 重置页码
      
      try {
        emit('search', {
          query: searchQuery.value,
          page: page.value,
          pageSize: pageSize.value,
          type: props.searchType,
          needTranslation: props.showTranslation // 添加是否需要翻译的标志
        });
      } finally {
        isSearching.value = false;
      }
    };

    // 加载更多
    const loadMore = async () => {
      if (isSearching.value || !hasMore.value) return;
      isSearching.value = true;
      page.value += 1;
      
      try {
        emit('search', {
          query: searchQuery.value,
          page: page.value,
          pageSize: pageSize.value,
          type: props.searchType
        });
      } finally {
        isSearching.value = false;
      }
    };

    // 清空搜索
    const clearSearch = () => {
      searchQuery.value = '';
      displayResults.value = [];
      page.value = 1;
      emit('update:enableSearch', false);
    };

    // 格式化日期
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm');
    };

    // 处理滚动加载
    const handleScroll = (e) => {
      const { scrollTop, scrollHeight, clientHeight } = e.target;
      if (scrollHeight - scrollTop - clientHeight < 50 && !isSearching.value && hasMore.value) {
        loadMore();
      }
    };

    // 格式化内容的方法
    const formatContent = (content) => {
      if (!content) return '';
      // 将内容中的关键词高亮显示，同时处理HTML标签
      const escapedQuery = searchQuery.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      return content.replace(new RegExp(escapedQuery, 'gi'), 
        match => `<span class="highlight">${match}</span>`
      );
    };

    return {
      searchQuery,
      isSearching,
      displayResults,
      hasMore,
      handleSearch,
      clearSearch,
      formatDate,
      handleScroll,
      placeholder,
      formatContent,
    };
  }
});
</script>

<style lang="less" scoped>
// 响应式设计的基础变量
:root {
  --base-font-size: 16px;
  --small-font-size: 14px;
  --smaller-font-size: 12px;
  --base-spacing: 16px;
  --border-radius: 6px;
  --input-height: 40px;
  --input-height-mobile: 36px;
  --input-height-small: 32px;
  --button-min-width: 80px;
  --button-min-width-mobile: 64px;
}

.knowledge-results {
  color: var(--primary-text);
  height: 94%;
  display: flex;
  flex-direction: column;
  background: var(--secondary-bg);
  width: 96%;
  overflow: hidden;
  font-size: var(--base-font-size);

  @media (max-width: 768px) {
    font-size: calc(var(--base-font-size) - 2px);
  }

  .search-box {
    padding: var(--base-spacing);
    display: flex;
    gap: 12px;
    align-items: center;

    @media (max-width: 768px) {
      padding: calc(var(--base-spacing) * 0.75);
      gap: 8px;
    }

    @media (max-width: 480px) {
      padding: calc(var(--base-spacing) * 0.5);
      gap: 6px;
    }

    .input-wrapper {
      position: relative;
      flex: 1;
      display: flex;
      align-items: center;
      margin-right: 15px;
      .search-input {
        width: 100%;
        height: 24px;
        font-size: 16px;
        border: 1px solid #d9d9d9;
        padding: 8px 30px 8px 12px;
        border-radius: 4px 0 0 4px;
        outline: none;
        transition: all 0.3s;
        margin-right: 15px;
        @media (max-width: 768px) {
          height: var(--input-height-mobile);
          padding: 0 36px 0 14px;
          font-size: var(--small-font-size);
        }

        @media (max-width: 480px) {
          height: var(--input-height-small);
          padding: 0 32px 0 12px;
          font-size: var(--smaller-font-size);
        }

        &:focus {
          border-color: #1677ff;
          box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1);
        }

        &::placeholder {
          color: rgba(0, 0, 0, 0.25);
          font-size: inherit;
        }
      }

      .clear-icon {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: rgba(0, 0, 0, 0.45);
        font-size: var(--base-font-size);
        transition: all 0.3s;
        border-radius: 50%;
        
        @media (max-width: 768px) {
          right: 10px;
          width: 14px;
          height: 14px;
          font-size: var(--small-font-size);
        }

        @media (max-width: 480px) {
          right: 8px;
          width: 12px;
          height: 12px;
          font-size: var(--smaller-font-size);
        }

        &:hover {
          color: rgba(0, 0, 0, 0.88);
          background: rgba(0, 0, 0, 0.04);
        }
      }
    }

    .search-button {
      height: var(--input-height);
      min-width: var(--button-min-width);
      padding: 0 20px;
      font-size: var(--base-font-size);
      background: #1677ff;
      border: none;
      border-radius: var(--border-radius);
      color: white;
      cursor: pointer;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      justify-content: center;
      white-space: nowrap;
      user-select: none;
      touch-action: manipulation;

      @media (max-width: 768px) {
        height: var(--input-height-mobile);
        min-width: var(--button-min-width-mobile);
        padding: 0 16px;
        font-size: var(--small-font-size);
      }

      @media (max-width: 480px) {
        height: var(--input-height-small);
        padding: 0 12px;
        font-size: var(--smaller-font-size);
      }

      &:hover {
        background: #4096ff;
      }

      &:active {
        background: #0958d9;
      }

      &:disabled {
        background: #d9d9d9;
        cursor: not-allowed;
        pointer-events: none;
      }

      // 添加触摸设备的激活状态样式
      @media (hover: none) {
        &:active {
          background: #0958d9;
        }
      }
    }
  }

  .results-container {
    flex: 1;
    overflow-y: auto;
    padding: var(--base-spacing);

    @media (max-width: 480px) {
      padding: calc(var(--base-spacing) / 2);
    }

    .result-item {
      padding: 20px 0;
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.3s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: rgba(0, 0, 0, 0.02);
      }

      .result-title {
        margin: 0 0 8px;
        font-size: 16px;
        
        a {
          color: #1677ff;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }

      .result-content {
        color: rgba(0, 0, 0, 0.65);
        font-size: 14px;
        margin-bottom: 8px;
        line-height: 1.5;
      }

      .result-translation {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        margin-bottom: 8px;
        padding: 8px;
        background: #f5f5f5;
        border-radius: 4px;

        .translation-label {
          color: rgba(0, 0, 0, 0.85);
          font-weight: 500;
          margin-right: 8px;
        }

        .translation-content {
          color: rgba(0, 0, 0, 0.65);
        }
      }

      .result-meta {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
        display: flex;
        gap: 16px;

        .result-date,
        .result-source {
          display: inline-flex;
          align-items: center;
        }
      }
    }
  }

  .loading-state,
  .empty-state {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--primary-text);
    
    .loading-spinner {
      width: 24px;
      height: 24px;
      border: 2px solid #f0f0f0;
      border-top-color: #1677ff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    p {
      margin-top: 12px;
    }
  }

  .load-more {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;
    color: var(--primary-text);
    gap: 8px;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

// 添加深色模式支持
@media (prefers-color-scheme: dark) {
  .knowledge-results {
    background: #1f1f1f;
    color: rgba(255, 255, 255, 0.85);

    .search-input {
      background: #2f2f2f;
      border-color: #434343;
      color: rgba(255, 255, 255, 0.85);
    }

    .result-item {
      background: #2f2f2f;
      border-color: #434343;

      .result-title {
        color: #1890ff;
      }

      .result-content {
        color: rgba(255, 255, 255, 0.65);
      }

      .result-translation {
        background: #1f1f1f;

        .translation-label {
          color: rgba(255, 255, 255, 0.85);
        }

        .translation-content {
          color: rgba(255, 255, 255, 0.65);
        }
      }

      .result-meta {
        color: rgba(255, 255, 255, 0.45);
      }
    }
  }
}

// 深色模式样式增强
@media (prefers-color-scheme: dark) {
  .knowledge-results {
    background: #1f1f1f;

    .search-box {
      border-color: #303030;

      .search-input {
        background: #2f2f2f;
        border-color: #434343;
        color: rgba(255, 255, 255, 0.85);

        &::placeholder {
          color: rgba(255, 255, 255, 0.25);
        }

        &:focus {
          border-color: #1677ff;
          box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.15);
        }
      }

      .clear-icon {
        color: rgba(255, 255, 255, 0.45);

        &:hover {
          color: rgba(255, 255, 255, 0.85);
          background: rgba(255, 255, 255, 0.08);
        }
      }

      .search-button {
        &:disabled {
          background: #424242;
          color: rgba(255, 255, 255, 0.3);
        }
      }
    }
  }
}

// 添加高对比度模式支持
@media (prefers-contrast: high) {
  .search-input {
    border-width: 2px;
  }

  .search-button {
    border: 2px solid transparent;

    &:focus {
      outline: 2px solid #fff;
      outline-offset: 2px;
    }
  }
}

// 添加减少动画模式支持
@media (prefers-reduced-motion: reduce) {
  .search-input,
  .search-button,
  .clear-icon,
  .result-item {
    transition: none;
  }
}

.highlight {
  color: #1677ff;
  font-weight: 500;
  padding: 0 2px;
  border-radius: 2px;
  background: rgba(24, 144, 255, 0.1);
}
</style> 