using CommunityToolkit.Mvvm.ComponentModel; using System.Collections.ObjectModel; using XFEExtension.NetCore.WinUIHelper.Interface.Services; using XFEExtension.NetCore.WinUIHelper.Utilities; using XFENewsApplication.Core.Models; using XFENewsApplication.Core.Utilities.Helpers; namespace XFENewsApplication.ViewModels; public partial class HotSearchViewPageViewModel : ViewModelBase { [ObservableProperty] int selectedIndex = -1; public ObservableCollection HotSearchSource { get; } = []; public CancellationTokenSource? TokenSource { get; set; } public INavigationParameterService NavigationParameterService { get; set; } = ServiceManager.GetService>(); public IListViewService ListViewService { get; set; } = ServiceManager.GetService(); public IMessageService? MessageService { get; set; } = ServiceManager.GetGlobalService(); public INavigationViewService? NavigationViewService { get; set; } = ServiceManager.GetGlobalService(); public HotSearchViewPageViewModel() { NavigationParameterService.ParameterChange += NavigationParameterService_ParameterChange; } private void ListView_DoubleTapped(object sender, Microsoft.UI.Xaml.Input.DoubleTappedRoutedEventArgs e) { if (SelectedIndex < 0 || SelectedIndex >= HotSearchSource.Count) return; var keyword = Uri.EscapeDataString(HotSearchSource[SelectedIndex].Title); switch (NavigationParameterService.Parameter) { case "Weibo": Helper.OpenInBrowser($"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D{keyword}"); break; case "Bilibili": Helper.OpenInBrowser($"https://search.bilibili.com/all?keyword={keyword}"); break; default: break; } } private async void NavigationParameterService_ParameterChange(object? sender, string? e) { ListViewService.ListView.DoubleTapped -= ListView_DoubleTapped; ListViewService.ListView.DoubleTapped += ListView_DoubleTapped; TokenSource?.Cancel(); var tokenSource = new CancellationTokenSource(); TokenSource = tokenSource; try { var result = await GetSource(e, tokenSource.Token); tokenSource.Token.ThrowIfCancellationRequested(); if (!ReferenceEquals(TokenSource, tokenSource)) return; if (result.Success) LoadHotSearch(result.NewsSourceList); else MessageService?.ShowMessage(result.Message ?? "请检查网络连接", "无法获取", InfoBarSeverity.Warning); } catch (OperationCanceledException) when (tokenSource.IsCancellationRequested) { } catch (Exception ex) { if (!tokenSource.IsCancellationRequested) MessageService?.ShowMessage(ex.Message, "无法获取热搜", InfoBarSeverity.Warning); } finally { if (ReferenceEquals(TokenSource, tokenSource)) TokenSource = null; tokenSource.Dispose(); } } private static async Task GetSource(string? source, CancellationToken cancellationToken) => source switch { "Weibo" => await ClimbHelper.ClimbWeiboHotSearch(cancellationToken), "Bilibili" => await ClimbHelper.ClimbBilibiliHotSearch(cancellationToken), _ => new() }; public void LoadHotSearch(IEnumerable newsSources) { HotSearchSource.Clear(); foreach (var source in newsSources) HotSearchSource.Add(source); } }