XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
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 sealed record RivenWeapon(string Key, string Label, double Disposition);

public partial class RivenPageViewModel : AdminViewModelBase
{
    private string? version, accountId, editingId, editingType, loadedFamily;
    private bool selecting;
    private RivenStatOption[] tags = [];
    private JObject? baseFingerprint;
    private JArray challengeData = [];
    public ObservableCollection<EditorCategory> Challenges { get; } = [];
    public ObservableCollection<EditorCategory> Complications { get; } = [];
    private int offset, total;
    public ObservableCollection<AccountRow> Accounts { get; } = [];
    public ObservableCollection<EditorCategory> Families { get; } = [];
    public ObservableCollection<RivenWeapon> Weapons { get; } = [];
    public ObservableCollection<EditorItem> Owned { get; } = [];
    public ObservableCollection<RivenStatRow> Rows { get; } = [];
    public IReadOnlyList<string> Polarities { get; } = ["AP_ANY", "AP_UNIVERSAL", "AP_ATTACK", "AP_DEFENSE", "AP_TACTIC", "AP_POWER", "AP_WARD", "AP_PRECEPT", "AP_UMBRA"];
    [ObservableProperty] public partial AccountRow? SelectedAccount { get; set; }
    [ObservableProperty] public partial EditorCategory? Family { get; set; }
    [ObservableProperty] public partial RivenWeapon? Weapon { get; set; }
    [ObservableProperty] public partial EditorItem? SelectedOwned { get; set; }
    [ObservableProperty] public partial double Disposition { get; set; } = 1;
    [ObservableProperty] public partial double Level { get; set; } = 8;
    [ObservableProperty] public partial double Mastery { get; set; }
    [ObservableProperty] public partial double Rerolls { get; set; }
    [ObservableProperty] public partial string Polarity { get; set; } = "AP_ANY";
    [ObservableProperty] public partial string Fingerprint { get; set; } = "";
    [ObservableProperty] public partial string Name { get; set; } = "新建紫卡";
    [ObservableProperty] public partial string EditingLabel { get; set; } = "尚未选择玩家";
    [ObservableProperty] public partial string PageLabel { get; set; } = "";
    [ObservableProperty] public partial bool CanUpdate { get; set; }
    [ObservableProperty] public partial bool Veiled { get; set; }
    [ObservableProperty] public partial bool Sentinel { get; set; }
    [ObservableProperty] public partial EditorCategory? SelectedChallenge { get; set; }
    [ObservableProperty] public partial EditorCategory? SelectedComplication { get; set; }
    [ObservableProperty] public partial double Required { get; set; } = 1;
    [ObservableProperty] public partial double Progress { get; set; }
    public Visibility VeiledVisibility => Veiled ? Visibility.Visible : Visibility.Collapsed;
    public Visibility RevealedVisibility => Veiled ? Visibility.Collapsed : Visibility.Visible;
    partial void OnVeiledChanged(bool value) { OnPropertyChanged(nameof(VeiledVisibility)); OnPropertyChanged(nameof(RevealedVisibility)); }
    partial void OnSelectedChallengeChanged(EditorCategory? value)
    {
        Complications.Clear();
        if (challengeData.FirstOrDefault(x => x.Value<string>("key") == value?.Key) is not JObject data) return;
        foreach (var row in data["complications"]!) Complications.Add(new(row.Value<string>("key")!, row.Value<string>("label")!));
        SelectedComplication = Complications.FirstOrDefault(); Required = data.Value<double>("required"); Progress = 0;
    }
    public string CreateButtonText => true ? UiText.Translate("创建紫卡") : "";
    public string UpdateButtonText => CanUpdate ? UiText.Translate("保存修改") : "";
    partial void OnCanUpdateChanged(bool value) => OnPropertyChanged(nameof(UpdateButtonText));
    public Visibility LoadingVisibility => IsBusy ? Visibility.Visible : Visibility.Collapsed;
    public RivenPageViewModel()
    {
        PropertyChanged += (_, e) => { if (e.PropertyName == nameof(IsBusy)) OnPropertyChanged(nameof(LoadingVisibility)); };
        _ = new RivenPreview(this, Rows, () => !IsBusy && !selecting && !Veiled && Family?.Key == loadedFamily && Weapon is not null && Rows.Count > 0,
            CalculationRequest, body => Calculate(body), ApplyCalculation);
    }
    partial void OnSelectedAccountChanged(AccountRow? value) { State.SelectedAccountId = value?.Id; if (!selecting) { version = null; Owned.Clear(); New(); } }
    partial void OnFamilyChanged(EditorCategory? value)
    {
        if (selecting || value?.Key == loadedFamily) return;
        CanUpdate = false;
        if (value is not null) { loadedFamily = null; Rows.Clear(); }
    }
    partial void OnWeaponChanged(RivenWeapon? value) { if (value is not null) Disposition = value.Disposition; }
    protected override async Task LoadAsync(object? parameter)
    {
        var wanted = parameter as string ?? State.SelectedAccountId;
        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();
        await ReadCatalogAsync(); if (SelectedAccount is not null) await ReadOwnedAsync();
    }
    private async Task ReadCatalogAsync(string? family = null)
    {
        var data = (JObject)await Service.GetAsync("riven/catalog" + ((family ?? Family?.Key) is string type ? "?type=" + Uri.EscapeDataString(type) : ""));
        selecting = true;
        try
        {
            var wanted = family ?? Family?.Key;
            Families.Clear(); foreach (var row in data["families"]!) Families.Add(new(row.Value<string>("key")!, row.Value<string>("label")!));
            Family = Families.FirstOrDefault(x => x.Key == wanted) ?? Families.First(); loadedFamily = Family.Key;
            tags = data["tags"]!.Select(RivenStatOption.FromJson).ToArray();
            Weapons.Clear(); foreach (var row in data["weapons"]!) Weapons.Add(new(row.Value<string>("key")!, row.Value<string>("label")!, row.Value<double>("disposition")));
            Weapon = Weapons.FirstOrDefault(); Rows.Clear(); AddPositive(); AddPositive();
            challengeData = (JArray)data["challenges"]!; Challenges.Clear();
            foreach (var row in challengeData) Challenges.Add(new(row.Value<string>("key")!, row.Value<string>("label")!));
            SelectedChallenge = Challenges.FirstOrDefault();
        }
        finally { selecting = false; }
    }
    private async Task ReadOwnedAsync(string? item = null)
    {
        var account = SelectedAccount?.Id ?? throw new InvalidOperationException("请选择玩家。");
        var data = (JObject)await Service.GetAsync($"accounts/{Uri.EscapeDataString(account)}/editor?category=Upgrades&q=%2FRandomized%2F&skip={offset}" + (item is null ? "" : "&item=" + Uri.EscapeDataString(item)));
        version = data.Value<string>("version"); accountId = account; total = data.Value<int>("total");
        Owned.Clear(); foreach (var row in data["items"]!) Owned.Add(new(row.Value<string>("key")!, row.Value<string>("name")!, row.Value<string>("detail")!));
        PageLabel = $"共 {total} 张 · 第 {offset / 40 + 1} 页";
        if (data["riven"] is JObject riven)
        {
            editingId = data.Value<string>("selectedKey"); editingType = riven.Value<string>("ItemType")!;
            await ReadCatalogAsync(editingType.Split('/').Last());
            Fingerprint = riven.Value<string>("UpgradeFingerprint") ?? "{}";
            await ImportCoreAsync(); CanUpdate = true; EditingLabel = "正在编辑已持有紫卡:" + data.Value<string>("selectedName");
        }
        else New();
    }
    private void EnsureFamily() { if (Family is null || loadedFamily != Family.Key) throw new InvalidOperationException("请先点击“载入类型”。"); }
    private async Task<JObject> Calculate(object body) => (JObject)await Service.PostAsync("riven/calculate?lang=" + Uri.EscapeDataString(Profiles.CrossVersionProfiles.SystemProfile.ItemLanguage), body);
    private static long Integer(double value, string name) => double.IsFinite(value) && value == Math.Truncate(value) ? (long)value : throw new InvalidOperationException(name + "必须为整数。");
    private JObject CalculationRequest()
    {
        EnsureFamily();
        if (!Polarities.Contains(Polarity)) throw new InvalidOperationException("请选择极性。");
        if (Veiled && (SelectedChallenge is null || Complications.Count > 0 && SelectedComplication is null)) throw new InvalidOperationException("请选择挑战及附加条件。");
        if (!Veiled && Weapon is null) throw new InvalidOperationException("请选择武器。");
        return JObject.FromObject(new { includeOptions = true, mode = Veiled ? "veiled" : "revealed", challengeType = SelectedChallenge?.Key ?? "", complication = SelectedComplication?.Key ?? "", required = Required, progress = Progress, sentinel = Sentinel, type = Family!.Key, weapon = Weapon?.Key ?? "", disposition = Disposition, level = Integer(Level, "等级"), mastery = Integer(Mastery, "段位"), rerolls = Integer(Rerolls, "重洗次数"), polarity = Polarity,
            baseFingerprint, rows = Rows.Select(x => x.Request()).ToArray() });
    }
    private async Task<JObject> CalculateCoreAsync()
    {
        var response = await Calculate(CalculationRequest());
        ApplyCalculation(response); Fingerprint = response["fingerprint"]!.ToString(Formatting.Indented);
        return response;
    }
    private void ApplyCalculation(JObject response)
    {
        Name = response.Value<string>("displayName") ?? response.Value<string>("name")!;
        var rows = Rows.Where(x => !x.Negative).Concat(Rows.Where(x => x.Negative)).ToArray();
        for (var i = 0; !Veiled && i < rows.Length; i++) rows[i].ApplyResult(response["stats"]![i]!);
    }
    private async Task ImportCoreAsync()
    {
        EnsureFamily();
        var response = await Calculate(new { type = Family!.Key, disposition = Disposition, fingerprint = Fingerprint });
        var fp = (JObject)response["fingerprint"]!;
        baseFingerprint = (JObject)fp.DeepClone();
        Veiled = response.Value<bool>("veiled"); Sentinel = fp.Value<bool>("IsSentinel");
        if (Veiled)
        {
            var challenge = (JObject)fp["challenge"]!;
            SelectedChallenge = Challenges.FirstOrDefault(x => x.Key == challenge.Value<string>("Type"));
            SelectedComplication = Complications.FirstOrDefault(x => x.Key == (challenge.Value<string>("Complication") ?? ""));
            Required = challenge.Value<double>("Required"); Progress = challenge.Value<double>("Progress");
            Name = response.Value<string>("name")!; Fingerprint = fp.ToString(Formatting.Indented); return;
        }
        Weapon = Weapons.FirstOrDefault(x => x.Key == fp.Value<string>("compat"));
        if (Weapon is null) throw new InvalidOperationException("指纹中的武器不属于所选紫卡类型。");
        Level = fp.Value<int>("lvl"); Mastery = fp.Value<int>("lvlReq"); Rerolls = fp.Value<int>("rerolls"); Polarity = fp.Value<string>("pol") ?? "AP_ANY";
        Rows.Clear();
        foreach (var (field, negative) in new[] { ("buffs", false), ("curses", true) }) foreach (var row in fp[field] as JArray ?? [])
        {
            var encoded = row.Value<long>("Value");
            var stat = new RivenStatRow(tags, x => Rows.Remove(x)) { Negative = negative, Value = encoded is >= 0 and <= 0x3fffffff ? 9000 + 2000 * encoded / (double)0x3fffffff : 9000 };
            stat.SelectedTag = stat.Tags.FirstOrDefault(x => x.Key == row.Value<string>("Tag"));
            stat.Retain((JObject)row); Rows.Add(stat);
        }
        await CalculateCoreAsync();
    }
    private void AddStat(bool negative)
    {
        if (tags.Length == 0) return;
        var row = new RivenStatRow(tags, x => Rows.Remove(x)) { Negative = negative };
        row.SelectedTag = row.Tags[Rows.Count % row.Tags.Count]; Rows.Add(row);
    }
    [RelayCommand] private void AddPositive() => AddStat(false);
    [RelayCommand] private void AddNegative() => AddStat(true);
    [RelayCommand] private void New() { editingId = editingType = null; baseFingerprint = null; CanUpdate = false; EditingLabel = "新建 · 保存后添加到所选玩家库存"; }
    [RelayCommand] private Task CatalogAsync() => RunAsync(async () => { New(); await ReadCatalogAsync(); });
    [RelayCommand] private Task RefreshOwnedAsync() => RunAsync(async () => { offset = 0; await ReadOwnedAsync(); });
    [RelayCommand] private Task OpenOwnedAsync() => RunAsync(() => ReadOwnedAsync(SelectedOwned?.Key ?? throw new InvalidOperationException("请选择已持有紫卡。")));
    [RelayCommand] private Task PreviousAsync() => RunAsync(async () => { if (offset >= 40) { offset -= 40; await ReadOwnedAsync(); } });
    [RelayCommand] private Task NextAsync() => RunAsync(async () => { if (offset + 40 < total) { offset += 40; await ReadOwnedAsync(); } });
    [RelayCommand] private Task CalculateAsync() => RunAsync(async () => { await CalculateCoreAsync(); });
    [RelayCommand] private Task ImportAsync() => RunAsync(ImportCoreAsync);
    [RelayCommand] private Task ExportAsync() => RunAsync(async () => { var result = await CalculateCoreAsync(); await Service.ExportAsync(result["fingerprint"]!, "riven-" + Name); });
    [RelayCommand] private Task CreateAsync() => Save(false);
    [RelayCommand] private Task UpdateAsync() => Save(true);
    private Task Save(bool update) => RunAsync(async () =>
    {
        if (version is null || accountId != SelectedAccount?.Id) throw new InvalidOperationException("请先读取该玩家的紫卡库存。");
        if (update && (editingId is null || editingType?.Split('/').Last() != Family?.Key)) throw new InvalidOperationException("请重新读取要编辑的紫卡。");
        var result = await CalculateCoreAsync();
        if (!await Interaction.ConfirmAsync(update ? "保存紫卡修改" : "添加紫卡", $"玩家:{SelectedAccount!.Name}\n武器:{Weapon?.Label}\n紫卡:{Name}")) return;
        await Service.PostAsync($"accounts/{Uri.EscapeDataString(accountId!)}/editor", new { version, action = update ? "riven.save" : "riven.create", item = editingId, values = new { type = Family!.Key, fingerprint = result["fingerprint"] } });
        await ReadOwnedAsync(update ? editingId : null); Notify("紫卡已保存");
    });
}