using System.Collections.ObjectModel; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.UI.Xaml; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEExtension.NetCore.WinUIHelper.Utilities; using XFEWarframe.Player.Interface.Services; using XFEWarframe.Player.Models; using XFEWarframe.Desktop.Editing; namespace XFEWarframe.Player.ViewModels; public sealed record EditorAccount(string Id, string Name); public partial class EditorPageViewModel : PlayerViewModelBase { private string? version, loadedAccount, loadedCategory, loadedItem; private int offset, total; private bool loadingSelection; private readonly EditorChangeMonitor changes; private int selectionGeneration; private string loadedQuery = ""; [ObservableProperty] [NotifyPropertyChangedFor(nameof(HasChangeNotice))] public partial string ChangeNotice { get; set; } = ""; public bool HasChangeNotice => ChangeNotice.Length > 0; public bool HasExternalChanges { get; private set; } [ObservableProperty] public partial Visibility ImportVisibility { get; set; } = Visibility.Collapsed; [ObservableProperty] public partial Visibility ExportVisibility { get; set; } = Visibility.Collapsed; public ObservableCollection Accounts { get; } = []; public ObservableCollection Categories { get; } = []; public ObservableCollection Items { get; } = []; public ObservableCollection Actions { get; } = []; public ObservableCollection BatchActions { get; } = []; [ObservableProperty] public partial EditorAccount? SelectedAccount { get; set; } [ObservableProperty] public partial EditorCategory? Category { get; set; } [ObservableProperty] public partial EditorItem? SelectedItem { get; set; } [ObservableProperty] public partial EditorAction? SelectedAction { get; set; } [ObservableProperty] public partial EditorAction? BatchAction { get; set; } [ObservableProperty] public partial string Query { get; set; } = ""; [ObservableProperty] public partial string PageLabel { get; set; } = ""; [ObservableProperty] public partial string SelectionLabel { get; set; } = "选择玩家并读取数据"; [ObservableProperty] public partial string EquipmentSummary { get; set; } = ""; [ObservableProperty] public partial string Description { get; set; } = ""; [ObservableProperty] public partial string Preview { get; set; } = ""; [ObservableProperty] public partial IReadOnlyList Fields { get; set; } = []; [ObservableProperty] public partial bool CanSave { get; set; } [ObservableProperty] public partial bool CanPrevious { get; set; } [ObservableProperty] public partial bool CanNext { get; set; } [ObservableProperty] public partial Visibility ListVisibility { get; set; } = Visibility.Visible; public Visibility ActionListVisibility => ListVisibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed; partial void OnListVisibilityChanged(Visibility value) => OnPropertyChanged(nameof(ActionListVisibility)); public Visibility LoadingVisibility => IsBusy ? Visibility.Visible : Visibility.Collapsed; public Visibility ActionVisibility => Actions.Count > 0 ? Visibility.Visible : Visibility.Collapsed; public Visibility BatchVisibility => BatchActions.Count > 0 ? Visibility.Visible : Visibility.Collapsed; public Visibility PreviewVisibility => Preview.Length > 0 ? Visibility.Visible : Visibility.Collapsed; public EditorPageViewModel() { InitializeCatalog(); Actions.CollectionChanged += (_, _) => NotifyDetailNavigation(); PropertyChanged += (_, e) => { if (e.PropertyName is nameof(SelectedItem) or nameof(Category) or nameof(IsCatalogMode)) { NotifyDetailNavigation(); NotifyPermissionNotice(); } }; changes = new EditorChangeMonitor(CheckChangesAsync); PropertyChanged += (_, e) => { if (e.PropertyName == nameof(IsBusy)) OnPropertyChanged(nameof(LoadingVisibility)); }; } partial void OnPreviewChanged(string value) => OnPropertyChanged(nameof(PreviewVisibility)); partial void OnSelectedAccountChanged(EditorAccount? value) { if (!loadingSelection) Reset(); } partial void OnCategoryChanged(EditorCategory? value) { CategoryPresentationChanged(); if (!loadingSelection) Reset(); } partial void OnSelectedItemChanged(EditorItem? value) { if (!loadingSelection) { selectionGeneration++; CanSave = false; Fields = []; Actions.Clear(); SelectedAction = null; OnPropertyChanged(nameof(ActionVisibility)); if (!Account.EditingEnabled && value is not null) { SelectionLabel = value.Name; Description = value.Detail; } } } partial void OnSelectedActionChanged(EditorAction? value) { Fields = value?.Fields.OfType().Select(x => new EditorField(x)).ToArray() ?? []; Description = value?.Description ?? ""; Preview = value?.Preview ?? ""; CanSave = version is not null && value is not null && !HasExternalChanges; } private void Reset() { selectionGeneration++; HasExternalChanges = false; ChangeNotice = ""; version = loadedItem = null; offset = total = 0; CanSave = CanPrevious = CanNext = false; ImportVisibility = ExportVisibility = Visibility.Collapsed; QuestCreation = null; Items.Clear(); Actions.Clear(); BatchActions.Clear(); SelectedAction = BatchAction = null; Fields = []; PageLabel = ""; OnPropertyChanged(nameof(ActionVisibility)); OnPropertyChanged(nameof(BatchVisibility)); SelectionLabel = "点击读取,载入所选分类"; } private IPlayerAccountService AccountService => ServiceManager.GetGlobalService()!; public PlayerAccountState Account => AccountService.State; public void Attach() { Detach(); Account.PropertyChanged += AccountChanged; changes.Start(); } public void Detach() { Account.PropertyChanged -= AccountChanged; changes.Stop(); } private void MarkChanged() { HasExternalChanges = true; CanSave = false; ChangeNotice = "存档已在游戏或其他窗口更新。当前输入已保留;请记录修改后点击读取 / 刷新,再保存。"; } public async Task CheckChangesAsync() { if (!changes.Active || IsBusy || IsCatalogMode || !Account.IsLoggedIn) return; if (permissionRefreshPending) { await RefreshPermissionsAsync(); return; } var observed = version; var generation = selectionGeneration; var pageGeneration = changes.Generation; try { var status = await AccountService.EditorRevisionAsync(); if (!changes.Active || IsBusy || observed != version || generation != selectionGeneration || pageGeneration != changes.Generation) return; if (status.Enabled != Account.EditingEnabled || status.Permissions != Account.EditingRevision) { await AccountService.RefreshAsync(); if (changes.Active && pageGeneration == changes.Generation) await RefreshPermissionsAsync(); return; } if (version is null) return; if (status.Version == version) { if (!HasExternalChanges) ChangeNotice = ""; return; } if (Fields.Any(x => x.Changed) || Query != loadedQuery || SelectedItem?.Key != loadedItem) { MarkChanged(); return; } await ReadAsync(loadedItem, automatic: true); } catch (OperationCanceledException) { } catch { if (changes.Active && pageGeneration == changes.Generation && observed == version) ChangeNotice = "连接中断,当前输入已保留;连接恢复后会继续检查存档更新。"; } } private void AccountChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { NotifyDetailNavigation(); NotifyPermissionNotice(); if (e.PropertyName is nameof(PlayerAccountState.ItemGrantEnabled) or nameof(PlayerAccountState.IsLoggedIn)) { OnPropertyChanged(nameof(CatalogToggleVisibility)); if (!Account.ItemGrantEnabled || !Account.IsLoggedIn) IsCatalogMode = false; } if (e.PropertyName is nameof(PlayerAccountState.EditingEnabled) or nameof(PlayerAccountState.EditingRevision) or nameof(PlayerAccountState.IsLoggedIn) or nameof(PlayerAccountState.AccountId)) InvalidatePermissions(); } protected override async Task LoadAsync(object? parameter) { Query = ""; IsCatalogMode = false; Reset(); await AccountService.InitializeAsync(); permissionRefreshPending = false; permissionSelectedItem = null; if (!Account.IsLoggedIn) return; SelectedAccount = new EditorAccount(Account.AccountId, Account.DisplayName); var key = InventoryNavigation.Category(parameter); if (key is not null) Category = new EditorCategory(key, InventoryNavigation.Label(key)); await ReadAsync(); } private async Task ReadAsync(string? item = null, bool automatic = false) { if (!Account.EditingEnabled) { await ReadOnlyAsync(item); return; } var generation = selectionGeneration; var pageGeneration = changes.Generation; var originalQuery = Query; var preferredAction = SelectedAction?.Key; var observedVersion = version; var account = SelectedAccount?.Id ?? throw new InvalidOperationException("请选择玩家。"); var category = Category?.Key ?? "Suits"; var query = $"?category={Uri.EscapeDataString(category)}&skip={offset}&q={Uri.EscapeDataString(Query)}" + (item is null ? "" : "&item=" + Uri.EscapeDataString(item)); var data = await AccountService.ReadEditorAsync(category, Query, item, offset); var prepared = await Task.Run(() => new { Categories = data["categories"]!.Where(x => x.Value("key") != "progress").Select(x => new EditorCategory(x.Value("key")!, x.Value("label")!)).ToArray(), Items = (data["items"] as JArray ?? []).Select(x => new EditorItem(x.Value("key")!, x.Value("name")!, x.Value("detail") ?? "", x["presentation"]?.Value("tags") ?? "", x.Value("canEdit") ?? true)).ToArray(), Actions = ParseActions(data["actions"] as JArray), Batch = ParseActions(data["batchActions"] as JArray) }, Lifetime); if (generation != selectionGeneration || pageGeneration != changes.Generation || originalQuery != Query || account != SelectedAccount?.Id) throw new OperationCanceledException("编辑目标已变化。"); if (automatic && (IsBusy || observedVersion != version)) return; if (automatic && Fields.Any(x => x.Changed)) { MarkChanged(); return; } loadingSelection = true; try { HasExternalChanges = false; ChangeNotice = ""; loadedQuery = originalQuery; version = data.Value("version"); loadedAccount = account; loadedCategory = category; loadedItem = data.Value("selectedKey"); ImportVisibility = data.Value("canImport") ? Visibility.Visible : Visibility.Collapsed; ExportVisibility = data.Value("canExport") ? Visibility.Visible : Visibility.Collapsed; Categories.Clear(); foreach (var c in prepared.Categories) Categories.Add(c); Category = Categories.FirstOrDefault(x => x.Key == category) ?? Categories.FirstOrDefault(); Items.Clear(); foreach (var row in prepared.Items) Items.Add(row); SelectedItem = Items.FirstOrDefault(x => x.Key == loadedItem); total = data.Value("total"); PageLabel = $"共 {total:N0} 项 · 第 {offset / 40 + 1} / {Math.Max(1, (total + 39) / 40)} 页"; CanPrevious = offset > 0; CanNext = offset + 40 < total; ListVisibility = data.Value("listVisible") == false || category is "settings" or "progress" or "templates" ? Visibility.Collapsed : Visibility.Visible; EquipmentSummary = data.Value("summary") ?? ""; SelectionLabel = data.Value("selectedName") ?? Category?.Label ?? "存档编辑"; Actions.Clear(); foreach (var a in prepared.Actions) Actions.Add(a); if (category == "settings" && data["fields"] is JArray { Count: > 0 }) Actions.Add(new EditorAction("settings", "保存修改的账号规则", "仅提交已修改的选项。部分规则可追溯应用到已有记录。", (JArray)data["fields"]!, "")); QuestCreation = ParseActions(data["creationActions"] as JArray).FirstOrDefault(); BatchActions.Clear(); foreach (var a in prepared.Batch) BatchActions.Add(a); BatchAction = BatchActions.FirstOrDefault(); SelectedAction = Actions.FirstOrDefault(x => x.Key == preferredAction) ?? Actions.FirstOrDefault(); OnPropertyChanged(nameof(ActionVisibility)); OnPropertyChanged(nameof(BatchVisibility)); if (SelectedAction is null) Description = data.Value("summary") ?? "当前选择没有可执行的编辑操作。"; } finally { loadingSelection = false; } } private static EditorAction[] ParseActions(JArray? actions) => (actions ?? []).Select(x => new EditorAction(x.Value("key")!, x.Value("label")!, x.Value("description") ?? "", (JArray)x["fields"]!, x["preview"]?.ToString(Formatting.Indented) ?? "")).ToArray(); [RelayCommand] private Task RefreshAsync() => RunAsync(async () => { offset = 0; await ReadAsync(); }); [RelayCommand] private void CancelEdit() => OnSelectedActionChanged(SelectedAction); [RelayCommand] private Task PrepareEditorAsync() => RunAsync(() => { if (ListVisibility == Visibility.Visible && SelectedItem is null && Actions.Count == 0) throw new InvalidOperationException("请选择物品。"); return ReadAsync(SelectedItem?.Key); }); [RelayCommand] private Task OpenItemAsync() => RunAsync(() => ReadAsync(SelectedItem?.Key ?? throw new InvalidOperationException("请选择物品。"))); [RelayCommand] private Task PreviousAsync() => RunAsync(async () => { if (offset > 0) { offset = Math.Max(0, offset - PageSize); await ReadAsync(); } }); [RelayCommand] private Task NextAsync() => RunAsync(async () => { if (offset + PageSize < total) { offset += PageSize; await ReadAsync(); } }); [RelayCommand] private Task SaveAsync() => RunAsync(async () => { if (!CanSave || SelectedAction is null) return; var values = new JObject(Fields.Where(x => SelectedAction.Key != "settings" || x.Changed).Select(x => new JProperty(x.Key, x.Serialize()))); if (SelectedAction.Key == "settings" && values.Count == 0) { Notify("没有需要保存的修改"); return; } if ((SelectedAction.Key is "remove" or "shards.remove" or "umbra.remove" or "invigoration.remove" || SelectedAction.Key.StartsWith("template.", StringComparison.Ordinal) || SelectedAction.Key.StartsWith("guild.", StringComparison.Ordinal) || SelectedAction.Key.StartsWith("unlock.", StringComparison.Ordinal)) && !await Interaction.ConfirmAsync(SelectedAction.Label, $"玩家:{SelectedAccount!.Name}\n目标:{SelectionLabel}\n{Description}")) return; var result = await Submit(SelectedAction.Key, values); foreach (var cleanup in (result["cleanup"] as JArray ?? []).Values()) { var field = Fields.First(x => x.Key == cleanup); if (await Interaction.ConfirmAsync("应用到已有记录", $"已开启“{field.Label}”。是否同时清理已有的限制记录?")) { version = result.Value("version"); result = await Submit("cleanup", new JObject { ["key"] = cleanup }); } } await ReadAsync(loadedItem); Notify("存档已保存"); }); [RelayCommand] private Task ApplyBatchAsync() => RunAsync(async () => { if (BatchAction is null || version is null) return; if (!await Interaction.ConfirmAsync(BatchAction.Label, $"玩家:{SelectedAccount!.Name}\n分类:{Category!.Label}\n{BatchAction.Description}")) return; await Submit(BatchAction.Key, new JObject()); await ReadAsync(); Notify("批量操作已完成"); }); [RelayCommand] private Task ExportArchiveAsync() => RunAsync(async () => { if (ExportVisibility != Visibility.Visible) return; var path = await Interaction.SaveJsonAsync("inventory-" + Account.AccountId); if (path is null) return; var archive = await AccountService.ExportArchiveAsync(); await Task.Run(async () => await File.WriteAllTextAsync(path, archive["inventory"]!.ToString(Formatting.Indented), Lifetime), Lifetime); Notify("完整存档已导出"); }); [RelayCommand] private Task ImportArchiveAsync() => RunAsync(async () => { if (ImportVisibility != Visibility.Visible || version is null) return; var capturedVersion = version; var capturedAccount = Account.AccountId; var path = await Interaction.OpenJsonAsync(); if (path is null) return; var data = await Task.Run(async () => { if (new FileInfo(path).Length > 16 * 1024 * 1024) throw new InvalidOperationException("文件不能超过 16 MB。"); var inventory = JObject.Parse(await File.ReadAllTextAsync(path, Lifetime)); return (Inventory: inventory, Preview: InventoryImportPreview.Describe(inventory)); }, Lifetime); if (!await Interaction.ConfirmAsync("导入存档 · " + Account.DisplayName, data.Preview)) return; if (capturedAccount != Account.AccountId || capturedVersion != version) throw new InvalidOperationException("账号或权限已变化,请重新读取。"); var result = await AccountService.ImportArchiveAsync(capturedVersion, data.Inventory); await AccountService.RefreshAsync(); await ReadAsync(); Notify("存档已导入;服务器备份:" + result.Value("backup")); }); private Task Submit(string action, JObject values) { if (version is null || loadedAccount is null || loadedAccount != SelectedAccount?.Id || loadedCategory != Category?.Key) throw new InvalidOperationException("请先读取所选玩家的分类。"); return AccountService.SaveEditorAsync(new JObject { ["version"] = version, ["category"] = loadedCategory, ["item"] = loadedItem, ["action"] = action, ["values"] = values }); } }