v2rayN/v2rayN/ServiceLib/ViewModels/ProfilesSelectViewModel.cs
2025-09-06 18:57:14 +08:00

139 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using ServiceLib.Base;
namespace ServiceLib.ViewModels;
public class ProfilesSelectViewModel(Func<EViewAction, object?, Task<bool>>? updateView) : ProfilesBaseViewModel(updateView)
{
#region private prop
private string _subIndexId = string.Empty;
#endregion private prop
#region Init
protected override async Task Initialize()
{
_subIndexId = _config.SubIndexId ?? string.Empty;
await base.Initialize();
}
#endregion Init
#region Actions
public bool CanOk()
{
return SelectedProfile != null && !SelectedProfile.IndexId.IsNullOrEmpty();
}
public bool SelectFinish()
{
if (!CanOk())
{
return false;
}
_updateView?.Invoke(EViewAction.CloseWindow, null);
return true;
}
#endregion Actions
#region Servers && Groups
public async Task<ProfileItem?> GetProfileItem()
{
if (string.IsNullOrEmpty(SelectedProfile?.IndexId))
{
return null;
}
var indexId = SelectedProfile.IndexId;
var item = await AppManager.Instance.GetProfileItem(indexId);
if (item is null)
{
NoticeManager.Instance.Enqueue(ResUI.PleaseSelectServer);
return null;
}
return item;
}
public Task SortServer(string colName)
{
if (colName.IsNullOrEmpty())
{
return Task.CompletedTask;
}
var prop = typeof(ProfileItemModel).GetProperty(colName);
if (prop == null)
{
return Task.CompletedTask;
}
_dicHeaderSort.TryAdd(colName, true);
var asc = _dicHeaderSort[colName];
var comparer = Comparer<object?>.Create((a, b) =>
{
if (ReferenceEquals(a, b))
{
return 0;
}
if (a is null)
{
return -1;
}
if (b is null)
{
return 1;
}
if (a.GetType() == b.GetType() && a is IComparable ca)
{
return ca.CompareTo(b);
}
return string.Compare(a.ToString(), b.ToString(), StringComparison.OrdinalIgnoreCase);
});
object? KeySelector(ProfileItemModel x)
{
return prop.GetValue(x);
}
IEnumerable<ProfileItemModel> sorted = asc
? ProfileItems.OrderBy(KeySelector, comparer)
: ProfileItems.OrderByDescending(KeySelector, comparer);
var list = sorted.ToList();
ProfileItems.Clear();
ProfileItems.AddRange(list);
_dicHeaderSort[colName] = !asc;
return Task.CompletedTask;
}
#endregion Servers && Groups
#region overrides
protected override string GetCurrentSubIndexId()
{
return _subIndexId;
}
protected override void SetCurrentSubIndexId(string? id)
{
_subIndexId = id ?? string.Empty;
}
protected override bool ShouldSetDefaultServer => false;
#endregion overrides
}