using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BaiduSearchApp
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
private int _currentPage = 1;
private int _pageSize = 10; // 每页显示10条结果
private int _totalItems = 0;
private int _totalPages = 1;
private string _currentQuery = string.Empty;
private BaiduSearchApi _searchApi;
private List _allSearchResults = new List(); // 存储所有搜索结果
public MainWindow()
{
InitializeComponent();
// 初始化占位符可见性
txtApiKeyPlaceholder.Visibility = Visibility.Visible;
txtSearchQueryPlaceholder.Visibility = Visibility.Visible;
// 初始化 WebView2
InitializeWebView();
}
private void TxtApiKey_TextChanged(object sender, TextChangedEventArgs e)
{
txtApiKeyPlaceholder.Visibility = string.IsNullOrEmpty(txtApiKey.Text) ? Visibility.Visible : Visibility.Collapsed;
}
private void TxtSearchQuery_TextChanged(object sender, TextChangedEventArgs e)
{
txtSearchQueryPlaceholder.Visibility = string.IsNullOrEmpty(txtSearchQuery.Text) ? Visibility.Visible : Visibility.Collapsed;
}
private async void BtnSearch_Click(object sender, RoutedEventArgs e)
{
await PerformSearchAsync();
}
private async void TxtSearchQuery_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
await PerformSearchAsync();
}
}
private async Task PerformSearchAsync()
{
string apiKey = txtApiKey.Text.Trim();
string query = txtSearchQuery.Text.Trim();
if (string.IsNullOrEmpty(apiKey))
{
ShowErrorMessage("请先输入百度千帆API Key");
return;
}
if (string.IsNullOrEmpty(query))
{
ShowErrorMessage("请输入搜索内容");
return;
}
try
{
txtStatus.Text = "正在搜索中...";
btnSearch.IsEnabled = false;
btnPrevPage.IsEnabled = false;
btnNextPage.IsEnabled = false;
lvSearchResults.Items.Clear();
_searchApi = new BaiduSearchApi(apiKey);
_currentQuery = query;
_currentPage = 1; // 重置为第一页
// 一次获取最多50条结果
SearchResponse response = await _searchApi.SearchAsync(query, 50);
if (response.References != null && response.References.Count > 0)
{
// 保存所有搜索结果
_allSearchResults = response.References;
_totalItems = _allSearchResults.Count;
// 计算总页数
_totalPages = (int)Math.Ceiling((double)_totalItems / _pageSize);
txtStatus.Text = $"找到 {_totalItems} 条结果";
// 显示当前页结果
ShowCurrentPageResults();
// 更新分页信息
UpdatePaginationInfo();
}
else
{
txtStatus.Text = "未找到相关结果";
_allSearchResults.Clear();
_totalItems = 0;
_totalPages = 1;
_currentPage = 1;
UpdatePaginationInfo();
}
}
catch (HttpRequestException ex)
{
ShowErrorMessage($"网络错误: {ex.Message}");
}
catch (Exception ex)
{
ShowErrorMessage($"搜索失败: {ex.Message}");
}
finally
{
btnSearch.IsEnabled = true;
}
}
private void ShowErrorMessage(string message)
{
txtStatus.Text = message;
MessageBox.Show(message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
#region 分页相关方法
///
/// 显示当前页的搜索结果
///
private void ShowCurrentPageResults()
{
lvSearchResults.Items.Clear();
// 计算当前页的起始和结束索引
int startIndex = (_currentPage - 1) * _pageSize;
int endIndex = Math.Min(startIndex + _pageSize, _totalItems);
// 添加当前页的结果
for (int i = startIndex; i < endIndex; i++)
{
lvSearchResults.Items.Add(_allSearchResults[i]);
}
}
private void UpdatePaginationInfo()
{
// 更新分页信息
txtPageInfo.Text = $"第 {_currentPage} 页,共 {_totalPages} 页";
// 启用/禁用分页按钮
btnPrevPage.IsEnabled = _currentPage > 1;
btnNextPage.IsEnabled = _currentPage < _totalPages;
}
private void BtnPrevPage_Click(object sender, RoutedEventArgs e)
{
if (_currentPage > 1)
{
_currentPage--;
ShowCurrentPageResults();
UpdatePaginationInfo();
}
}
private void BtnNextPage_Click(object sender, RoutedEventArgs e)
{
if (_currentPage < _totalPages)
{
_currentPage++;
ShowCurrentPageResults();
UpdatePaginationInfo();
}
}
#endregion
#region WebView2 相关方法
private async void InitializeWebView()
{
// 初始化 WebView2
await webView.EnsureCoreWebView2Async();
// 设置 WebView2 事件
webView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
webView.CoreWebView2.HistoryChanged += CoreWebView2_HistoryChanged;
}
private void CoreWebView2_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
{
// 更新地址栏
txtBrowserUrl.Text = webView.Source.ToString();
}
private void CoreWebView2_HistoryChanged(object sender, object e)
{
// 更新前进后退按钮状态
btnBack.IsEnabled = webView.CanGoBack;
btnForward.IsEnabled = webView.CanGoForward;
}
private void LvSearchResults_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// 双击搜索结果项打开链接
if (lvSearchResults.SelectedItem is Reference selectedReference)
{
OpenUrlInBrowser(selectedReference.Url);
}
}
private void OpenUrlInBrowser(string url)
{
if (!string.IsNullOrEmpty(url) && webView.CoreWebView2 != null)
{
webView.CoreWebView2.Navigate(url);
}
}
private void BtnBack_Click(object sender, RoutedEventArgs e)
{
if (webView.CanGoBack)
{
webView.GoBack();
}
}
private void BtnForward_Click(object sender, RoutedEventArgs e)
{
if (webView.CanGoForward)
{
webView.GoForward();
}
}
private void BtnRefresh_Click(object sender, RoutedEventArgs e)
{
webView.Reload();
}
private void BtnGo_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(txtBrowserUrl.Text) && webView.CoreWebView2 != null)
{
webView.CoreWebView2.Navigate(txtBrowserUrl.Text);
}
}
private void BtnCloseBrowser_Click(object sender, RoutedEventArgs e)
{
if (webView.CoreWebView2 != null)
{
webView.CoreWebView2.NavigateToString("浏览器已关闭
双击搜索结果项打开链接
");
}
}
#endregion
}
}