using System.Collections.ObjectModel; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEWarframe.Admin.Models; using XFEWarframe.Desktop.Editing; namespace XFEWarframe.Admin.ViewModels; public partial class InventoryPageViewModel : AdminViewModelBase { private JObject inventory = new(); private string? loadedAccountId; private string? archiveVersion; private InventoryPreview? preview; private int pageIndex; public ObservableCollection Accounts { get; } = []; public IReadOnlyList Currencies { get; } = ["RegularCredits", "PremiumCredits", "FusionPoints", "CrewShipFusionPoints", "PrimeTokens"]; [ObservableProperty] public partial AccountRow? SelectedAccount { get; set; } [ObservableProperty] public partial string Currency { get; set; } = "RegularCredits"; [ObservableProperty] public partial double Amount { get; set; } = 1000; [ObservableProperty] public partial string InventoryJson { get; set; } = ""; [ObservableProperty] public partial string Balance { get; set; } = "请选择玩家并读取库存。"; [ObservableProperty] public partial string PageLabel { get; set; } = ""; [ObservableProperty] public partial bool CanPrevious { get; set; } [ObservableProperty] public partial bool CanNext { get; set; } public Microsoft.UI.Xaml.Visibility LoadingVisibility => IsBusy ? Microsoft.UI.Xaml.Visibility.Visible : Microsoft.UI.Xaml.Visibility.Collapsed; public OverviewActionsModel OverviewActions { get; } private bool attached; public InventoryPageViewModel() { PropertyChanged += (_, args) => { if (args.PropertyName == nameof(IsBusy)) OnPropertyChanged(nameof(LoadingVisibility)); }; OverviewActions = new(async target => (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(target.AccountId)}/editor?category=progress"), async (target, body) => { if (target.Server != State.Address || target.AccountId != SelectedAccount?.Id) throw new InvalidOperationException("当前账号或服务器已变化。"); await Service.PostAsync($"accounts/{Uri.EscapeDataString(target.AccountId)}/editor", body); }, Notify); OverviewActions.AppliedAsync = () => RefreshCommand.ExecuteAsync(null); } public void Attach() { if (attached) return; attached = true; State.PropertyChanged += StateChanged; } public void Detach() { attached = false; State.PropertyChanged -= StateChanged; OverviewActions.CancelPending(); } private void StateChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == nameof(AdminState.Address)) SelectedAccount = null; } partial void OnSelectedAccountChanged(AccountRow? value) { State.SelectedAccountId = value?.Id; OverviewActions.Reset(value is null ? null : new(State.Address, value.Id, value.Name)); loadedAccountId = null; archiveVersion = null; InventoryJson = ""; preview = null; pageIndex = 0; PageLabel = ""; CanPrevious = CanNext = false; Balance = value is null ? "先创建玩家账户。" : "点击读取库存,查看所选玩家的数据。"; } protected override async Task LoadAsync(object? parameter) { var wanted = parameter as string ?? State.SelectedAccountId; Accounts.Clear(); foreach (var account in ((JArray)await Service.GetAsync("accounts")).Select(AccountRow.FromJson)) Accounts.Add(account); SelectedAccount = Accounts.FirstOrDefault(x => x.Id == wanted) ?? Accounts.FirstOrDefault(); OverviewActions.Reset(SelectedAccount is { } selected ? new(State.Address, selected.Id, selected.Name) : null); if (SelectedAccount is not null) await ReadInventoryAsync(); } private async Task ReadInventoryAsync() { var id = SelectedAccount?.Id ?? throw new InvalidOperationException("请选择玩家。"); var archive = (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(id)}/archive"); var result = (JObject)archive["inventory"]!; var formatted = await Task.Run(() => InventoryPreview.Create(result, Lifetime), Lifetime); if (id != SelectedAccount?.Id) return; inventory = result; loadedAccountId = id; archiveVersion = archive.Value("version"); preview = formatted; pageIndex = 0; ShowPage(); Balance = $"星币 {inventory.Value("RegularCredits"):N0} · 白金 {inventory.Value("PremiumCredits"):N0} · 内融核心 {inventory.Value("FusionPoints"):N0}"; await OverviewActions.RefreshAsync(); } private void ShowPage() { if (preview is null) return; InventoryJson = preview.Pages[pageIndex]; PageLabel = $"第 {pageIndex + 1} / {preview.Pages.Length} 页 · {preview.Characters:N0} 个字符 · 导出可获取完整 JSON"; CanPrevious = pageIndex > 0; CanNext = pageIndex + 1 < preview.Pages.Length; } [RelayCommand] private void PreviousPage() { if (!IsBusy && CanPrevious) { pageIndex--; ShowPage(); } } [RelayCommand] private void NextPage() { if (!IsBusy && CanNext) { pageIndex++; ShowPage(); } } private string RequireLoaded() => loadedAccountId is not null && loadedAccountId == SelectedAccount?.Id ? loadedAccountId : throw new InvalidOperationException("请先读取所选玩家的库存。"); [RelayCommand] private Task RefreshAsync() => RunAsync(ReadInventoryAsync); [RelayCommand] private void OpenEditor() { if (SelectedAccount is not null) { State.SelectedAccountId = SelectedAccount.Id; Navigation.NavigateTo(InventoryNavigation.Route("Suits")); } } [RelayCommand] private Task AdjustAsync() => RunAsync(async () => { var id = RequireLoaded(); if (!Currencies.Contains(Currency)) throw new InvalidOperationException("请选择货币类型。"); if (!double.IsFinite(Amount) || Amount != Math.Truncate(Amount) || Math.Abs(Amount) > 999999999) throw new InvalidOperationException("数量必须为范围内的整数。"); await Service.PostAsync($"accounts/{Uri.EscapeDataString(id)}/currency", new { currency = Currency, delta = (long)Amount }); await ReadInventoryAsync(); Notify("余额已更新"); }); [RelayCommand] private Task ExportAsync() => RunAsync(() => { RequireLoaded(); return Service.ExportAsync(inventory, "inventory-" + loadedAccountId); }); [RelayCommand] private Task ImportAsync() => RunAsync(async () => { var id = RequireLoaded(); var data = await Service.ReadInventoryFileAsync(); if (data is null) return; var summary = await Task.Run(() => InventoryImportPreview.Describe(data), Lifetime); if (!await Interaction.ConfirmAsync("导入库存 · " + SelectedAccount!.Name, summary)) return; var result = await Service.PostAsync($"accounts/{Uri.EscapeDataString(id)}/import", new { inventory = data, version = archiveVersion }); await ReadInventoryAsync(); Notify("库存已导入;服务器备份:" + result.Value("backup")); }); }