using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI.Xaml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Admin.Models;
using XFEWarframe.Desktop.Editing;
namespace XFEWarframe.Admin.ViewModels;
public partial class EditorPageViewModel : AdminViewModelBase
{
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; }
public ObservableCollection<AccountRow> Accounts { get; } = [];
public ObservableCollection<EditorCategory> Categories { get; } = [];
public ObservableCollection<EditorItem> Items { get; } = [];
public ObservableCollection<EditorAction> Actions { get; } = [];
public ObservableCollection<EditorAction> BatchActions { get; } = [];
[ObservableProperty] public partial AccountRow? 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<EditorField> 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 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)) NotifyDetailNavigation(); };
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(AccountRow? value) { State.SelectedAccountId = value?.Id; OnPropertyChanged(nameof(CatalogToggleVisibility)); 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; } }
partial void OnSelectedActionChanged(EditorAction? value)
{
Fields = value?.Fields.OfType<JObject>().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;
QuestCreation = null; Items.Clear(); Actions.Clear(); BatchActions.Clear(); SelectedAction = BatchAction = null; Fields = []; PageLabel = ""; SelectionLabel = "点击读取,载入所选分类";
}
public void Attach() => changes.Start();
public void Detach() => changes.Stop();
private void MarkChanged()
{
HasExternalChanges = true; CanSave = false;
ChangeNotice = "存档已在游戏或其他窗口更新。当前输入已保留;请记录修改后点击读取 / 刷新,再保存。";
}
public async Task CheckChangesAsync()
{
if (!changes.Active || IsBusy || IsCatalogMode || version is null || loadedAccount is null) return;
var observed = version; var generation = selectionGeneration; var pageGeneration = changes.Generation;
try
{
var status = (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(loadedAccount)}/editor-revision");
if (!changes.Active || IsBusy || observed != version || generation != selectionGeneration || pageGeneration != changes.Generation) return;
if (status.Value<string>("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 = "连接中断,当前输入已保留;连接恢复后会继续检查存档更新。";
}
}
protected override async Task LoadAsync(object? parameter)
{
Query = ""; IsCatalogMode = false; Reset();
var category = InventoryNavigation.Category(parameter);
var wanted = category is null ? parameter as string ?? State.SelectedAccountId : State.SelectedAccountId;
if (category is not null) Category = new EditorCategory(category, InventoryNavigation.Label(category));
var accounts = ((JArray)await Service.GetAsync("accounts")).Select(AccountRow.FromJson).ToArray();
Accounts.Clear(); foreach (var a in accounts) Accounts.Add(a);
SelectedAccount = Accounts.FirstOrDefault(x => x.Id == wanted) ?? Accounts.FirstOrDefault();
if (SelectedAccount is not null) await ReadAsync();
}
private async Task ReadAsync(string? item = null, bool automatic = false)
{
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 = (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(account)}/editor" + query);
var prepared = await Task.Run(() => new
{
Categories = data["categories"]!.Where(x => x.Value<string>("key") != "progress").Select(x => new EditorCategory(x.Value<string>("key")!, x.Value<string>("label")!)).ToArray(),
Items = (data["items"] as JArray ?? []).Select(x => new EditorItem(x.Value<string>("key")!, x.Value<string>("name")!, x.Value<string>("detail") ?? "", x["presentation"]?.Value<string>("tags") ?? "", x.Value<bool?>("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<string>("version"); loadedAccount = account; loadedCategory = category; loadedItem = data.Value<string>("selectedKey");
Categories.Clear(); foreach (var c in prepared.Categories) Categories.Add(c); Category = Categories.First(x => x.Key == category);
Items.Clear(); foreach (var row in prepared.Items) Items.Add(row); SelectedItem = Items.FirstOrDefault(x => x.Key == loadedItem);
total = data.Value<int>("total"); PageLabel = $"共 {total:N0} 项 · 第 {offset / 40 + 1} / {Math.Max(1, (total + 39) / 40)} 页";
CanPrevious = offset > 0; CanNext = offset + 40 < total;
ListVisibility = data.Value<bool?>("listVisible") == false || category is "settings" or "progress" or "templates" ? Visibility.Collapsed : Visibility.Visible;
EquipmentSummary = data.Value<string>("summary") ?? "";
SelectionLabel = data.Value<string>("selectedName") ?? Category.Label;
Actions.Clear(); foreach (var a in prepared.Actions) Actions.Add(a);
if (category == "settings") 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();
if (SelectedAction is null) Description = data.Value<string>("summary") ?? "当前选择没有可执行的编辑操作。";
}
finally { loadingSelection = false; }
}
private static EditorAction[] ParseActions(JArray? actions) => (actions ?? []).Select(x => new EditorAction(x.Value<string>("key")!, x.Value<string>("label")!, x.Value<string>("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 -= 40; await ReadAsync(); } });
[RelayCommand] private Task NextAsync() => RunAsync(async () => { if (offset + 40 < total) { offset += 40; 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 = (JObject)await Submit(SelectedAction.Key, values);
foreach (var cleanup in (result["cleanup"] as JArray ?? []).Values<string>())
{
var field = Fields.First(x => x.Key == cleanup);
if (await Interaction.ConfirmAsync("应用到已有记录", $"已开启“{field.Label}”。是否同时清理已有的限制记录?"))
{
version = result.Value<string>("version"); result = (JObject)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("批量操作已完成");
});
private Task<JToken> Submit(string action, JObject values)
{
if (version is null || loadedAccount is null || loadedAccount != SelectedAccount?.Id || loadedCategory != Category?.Key) throw new InvalidOperationException("请先读取所选玩家的分类。");
return Service.PostAsync($"accounts/{Uri.EscapeDataString(loadedAccount)}/editor", new { version, category = loadedCategory, item = loadedItem, action, values });
}
}
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI.Xaml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Admin.Models;
using XFEWarframe.Desktop.Editing;
namespace XFEWarframe.Admin.ViewModels;
public partial class EditorPageViewModel : AdminViewModelBase
{
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; }
public ObservableCollection<AccountRow> Accounts { get; } = [];
public ObservableCollection<EditorCategory> Categories { get; } = [];
public ObservableCollection<EditorItem> Items { get; } = [];
public ObservableCollection<EditorAction> Actions { get; } = [];
public ObservableCollection<EditorAction> BatchActions { get; } = [];
[ObservableProperty] public partial AccountRow? 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<EditorField> 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 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)) NotifyDetailNavigation(); };
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(AccountRow? value) { State.SelectedAccountId = value?.Id; OnPropertyChanged(nameof(CatalogToggleVisibility)); 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; } }
partial void OnSelectedActionChanged(EditorAction? value)
{
Fields = value?.Fields.OfType<JObject>().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;
QuestCreation = null; Items.Clear(); Actions.Clear(); BatchActions.Clear(); SelectedAction = BatchAction = null; Fields = []; PageLabel = ""; SelectionLabel = "点击读取,载入所选分类";
}
public void Attach() => changes.Start();
public void Detach() => changes.Stop();
private void MarkChanged()
{
HasExternalChanges = true; CanSave = false;
ChangeNotice = "存档已在游戏或其他窗口更新。当前输入已保留;请记录修改后点击读取 / 刷新,再保存。";
}
public async Task CheckChangesAsync()
{
if (!changes.Active || IsBusy || IsCatalogMode || version is null || loadedAccount is null) return;
var observed = version; var generation = selectionGeneration; var pageGeneration = changes.Generation;
try
{
var status = (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(loadedAccount)}/editor-revision");
if (!changes.Active || IsBusy || observed != version || generation != selectionGeneration || pageGeneration != changes.Generation) return;
if (status.Value<string>("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 = "连接中断,当前输入已保留;连接恢复后会继续检查存档更新。";
}
}
protected override async Task LoadAsync(object? parameter)
{
Query = ""; IsCatalogMode = false; Reset();
var category = InventoryNavigation.Category(parameter);
var wanted = category is null ? parameter as string ?? State.SelectedAccountId : State.SelectedAccountId;
if (category is not null) Category = new EditorCategory(category, InventoryNavigation.Label(category));
var accounts = ((JArray)await Service.GetAsync("accounts")).Select(AccountRow.FromJson).ToArray();
Accounts.Clear(); foreach (var a in accounts) Accounts.Add(a);
SelectedAccount = Accounts.FirstOrDefault(x => x.Id == wanted) ?? Accounts.FirstOrDefault();
if (SelectedAccount is not null) await ReadAsync();
}
private async Task ReadAsync(string? item = null, bool automatic = false)
{
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 = (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(account)}/editor" + query);
var prepared = await Task.Run(() => new
{
Categories = data["categories"]!.Where(x => x.Value<string>("key") != "progress").Select(x => new EditorCategory(x.Value<string>("key")!, x.Value<string>("label")!)).ToArray(),
Items = (data["items"] as JArray ?? []).Select(x => new EditorItem(x.Value<string>("key")!, x.Value<string>("name")!, x.Value<string>("detail") ?? "", x["presentation"]?.Value<string>("tags") ?? "", x.Value<bool?>("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<string>("version"); loadedAccount = account; loadedCategory = category; loadedItem = data.Value<string>("selectedKey");
Categories.Clear(); foreach (var c in prepared.Categories) Categories.Add(c); Category = Categories.First(x => x.Key == category);
Items.Clear(); foreach (var row in prepared.Items) Items.Add(row); SelectedItem = Items.FirstOrDefault(x => x.Key == loadedItem);
total = data.Value<int>("total"); PageLabel = $"共 {total:N0} 项 · 第 {offset / 40 + 1} / {Math.Max(1, (total + 39) / 40)} 页";
CanPrevious = offset > 0; CanNext = offset + 40 < total;
ListVisibility = data.Value<bool?>("listVisible") == false || category is "settings" or "progress" or "templates" ? Visibility.Collapsed : Visibility.Visible;
EquipmentSummary = data.Value<string>("summary") ?? "";
SelectionLabel = data.Value<string>("selectedName") ?? Category.Label;
Actions.Clear(); foreach (var a in prepared.Actions) Actions.Add(a);
if (category == "settings") 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();
if (SelectedAction is null) Description = data.Value<string>("summary") ?? "当前选择没有可执行的编辑操作。";
}
finally { loadingSelection = false; }
}
private static EditorAction[] ParseActions(JArray? actions) => (actions ?? []).Select(x => new EditorAction(x.Value<string>("key")!, x.Value<string>("label")!, x.Value<string>("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 -= 40; await ReadAsync(); } });
[RelayCommand] private Task NextAsync() => RunAsync(async () => { if (offset + 40 < total) { offset += 40; 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 = (JObject)await Submit(SelectedAction.Key, values);
foreach (var cleanup in (result["cleanup"] as JArray ?? []).Values<string>())
{
var field = Fields.First(x => x.Key == cleanup);
if (await Interaction.ConfirmAsync("应用到已有记录", $"已开启“{field.Label}”。是否同时清理已有的限制记录?"))
{
version = result.Value<string>("version"); result = (JObject)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("批量操作已完成");
});
private Task<JToken> Submit(string action, JObject values)
{
if (version is null || loadedAccount is null || loadedAccount != SelectedAccount?.Id || loadedCategory != Category?.Key) throw new InvalidOperationException("请先读取所选玩家的分类。");
return Service.PostAsync($"accounts/{Uri.EscapeDataString(loadedAccount)}/editor", new { version, category = loadedCategory, item = loadedItem, action, values });
}
}