<template>
  <div class="search-results"><!--   @keyup.enter="handleSearch" -->
    <!-- <div class="search-box">
      <div class="input-wrapper">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Enter your search query"
        
        />
        <span 
          v-if="searchQuery" 
          class="clear-icon" 
          @click="clearSearch"
        >×</span>
      </div>
      <button @click="handleSearch" :disabled="isSearching">
        搜索一下
      </button>
    </div> -->

    <!-- <div class="results-header">
      <h2>Related Search Results</h2>
      <div class="result-stats">
        Found {{ total }} results
      </div>
    </div> -->

    <div class="results-container" ref="resultsContainer" @scroll="handleScroll">
      <!-- 搜索结果列表 -->
      <div v-if="displayResults.length > 0" class="results-list">
        <div v-for="(item, index) in displayResults" :key="index" class="result-item">
          <h3 class="result-title">
            <a :href="item.link"  target="_blank" rel="noopener noreferrer">{{ item.title }}</a>
          </h3>
          <p class="result-url">{{ item.link }}</p>
          <p class="result-snippet">{{ item.snippet }}</p>
          <div class="result-meta">
            <span class="result-date">{{ formatDate(item.date) }}</span>
            <span class="result-source">{{ item.source }}</span>
          </div>
        </div>

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

      <!-- 无结果显示 -->
      <div v-else class="no-results">
      <!--   <FileSearchOutlined class="no-results-icon" />
        <p>No related results found</p> -->
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, watch } from 'vue';
import { FileSearchOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import axios from 'axios';

export default defineComponent({
  name: 'SearchResults',
  components: {
    FileSearchOutlined
  },
  props: {
    searchResults: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    total: {
      type: Number,
      default: 0
    },
    message: {
      type: String,
      default: ''
    },
    enableWebSearch: {
      type: Boolean,
      default: true,
    },
  },
  emits: ['update:total', 'update:enableWebSearch'],
  setup(props, { emit }) {
    const displayResults = ref([]);
    const hasMore = ref(false);
    const searchQuery = ref('');
    const isSearching = ref(false);
    const localTotal = ref(props.total);
    const isSearchEnabled = ref(props.enableWebSearch);

    // 监听props中的total变化
    watch(() => props.total, (newTotal) => {
      localTotal.value = newTotal;
    });

    // 监听 searchResults 变化
    watch(() => props.searchResults, (newResults) => {
      displayResults.value = newResults;
      hasMore.value = displayResults.value.length < props.total;
    }, { immediate: true });

    // 监听 message prop 的变化
    watch(() => props.message, (newMessage) => {
      if (newMessage && props.enableWebSearch) {
        searchQuery.value = newMessage;
       // handleSearch(); // 自动触发搜索
      }
    });

    // 添加监听器
    watch(
      () => props.enableWebSearch,
      (newVal) => {
        isSearchEnabled.value = newVal;
        if (!newVal) {
          // 当搜索被关闭时,清空搜索结果
          clearSearch();
        }
      }
    );

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

    // 更新搜索处理函数
    const handleSearch = async () => {
      if (!searchQuery.value.trim() || isSearching.value || !props.enableWebSearch) return;
      
      isSearching.value = true;
      try {
        const response = await axios.post(
          `${import.meta.env.VITE_BASE_AI_API}/api/web-search-results/`,
          {
            query: searchQuery.value,
            num_results: 20,
            page: 1,
            page_size: 20,
            engine: "bing",
          }
        );

        // 添加调试日志
        console.log('API Response:', response.data);
        
        if (response.data && response.data.code === 200) {
          displayResults.value = response.data.data.result || [];
          // 添加调试日志
          console.log('Total Results:', response.data.data.total);
          localTotal.value = response.data.data.total || 0;
          emit('update:total', response.data.data.total || 0);
        }
      } catch (error) {
        console.error('Web search failed:', error);
        displayResults.value = [];
        localTotal.value = 0;
        emit('update:total', 0);
      } finally {
        isSearching.value = false;
      }
    };

    // 清空搜索函数
    const clearSearch = () => {
      searchQuery.value = '';
      displayResults.value = [];
      localTotal.value = 0;
      emit('update:total', 0);
    };

    const toggleSearch = () => {
      isSearchEnabled.value = !isSearchEnabled.value;
      emit('update:enableWebSearch', isSearchEnabled.value);
    };

    return {
      displayResults,
      loading: props.loading,
      total: localTotal,
      hasMore,
      formatDate,
      searchQuery,
      isSearching,
      handleSearch,
      clearSearch,
      isSearchEnabled,
      toggleSearch,
    };
  }
});
</script>

<style lang="less" scoped>
.search-results {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--secondary-bg);
  width: 100%;
  overflow: hidden;

  .search-box {
    padding: 16px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    gap: 0;

    .input-wrapper {
      position: relative;
      flex: 1;
      display: flex;
      align-items: center;

      input {
        width: 100%;
        padding: 8px 30px 8px 12px;
        height: 24px;
        font-size: 16px;
        border: 2px solid #4e6ef2;
        border-right: none;
        border-radius: 4px 0 0 4px;

        &:focus {
          outline: none;
        }
      }

      .clear-icon {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #999;
        font-size: 16px;
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;

        &:hover {
          color: #666;
          background-color: rgba(0, 0, 0, 0.05);
        }
      }
    }

    button {
      padding: 0 20px;
      height: 44px;
      background: #4e6ef2;
      border: none;
      border-radius: 0 4px 4px 0;
      color: white;
      cursor: pointer;
      font-size: 16px;
      min-width: 108px;

      &:disabled {
        background: #7a96fa;
        cursor: not-allowed;
      }

      &:hover:not(:disabled) {
        background: #4662d9;
      }
    }
  }

  .results-header {
    padding: 16px 24px;
    border-bottom: 1px solid var(--border-color);
    
    h2 {
      margin: 0;
      font-size: 18px;
      color: var(--primary-text);
    }

    .result-stats {
      margin-top: 4px;
      font-size: 14px;
      color: var(--primary-text);
    }
  }

  .results-container {
    flex: 1;
    overflow-y: auto;
    padding: 0 24px;
    scroll-behavior: smooth;
  }

  .results-list {
    .result-item {
      padding: 20px 0;
      border-bottom: 1px solid #f0f0f0;

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

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

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

      .result-url {
        color: #0ca678;
        font-size: 13px;
        margin-bottom: 8px;
      }

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

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

        .result-date {
          margin-right: 16px;
        }
      }
    }
  }

  .no-results {
    text-align: center;
    padding: 48px 0;
    color: var(--primary-text);

    .no-results-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }

    p {
      font-size: 14px;
    }
  }

  .loading-more {
    text-align: center;
    padding: 20px 0;
    color: var(--primary-text);
    font-size: 14px;
  }

  .loading-spinner {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #1677ff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  // 添加滚动条样式
  .results-container::-webkit-scrollbar {
    width: 6px;
  }

  .results-container::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }

  .results-container::-webkit-scrollbar-track {
    background-color: transparent;
  }
}
</style> 