Files
WCTDataMiner/src/WCTDataMiner.Wpf/ViewModels/PlossChartViewModel.cs

140 lines
4.1 KiB
C#

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView;
using Microsoft.Extensions.Logging;
using WCTDataMiner.Core.Services;
using WCTDataMiner.Wpf.Messages;
namespace WCTDataMiner.Wpf.ViewModels;
/// <summary>
/// Ploss 折线图 ViewModel
/// </summary>
public partial class PlossChartViewModel : ObservableObject
{
private readonly ScenarioService _scenarioService;
private readonly ILogger<PlossChartViewModel> _logger;
[ObservableProperty]
private Guid _scenarioId;
[ObservableProperty]
private ISeries[] _series;
[ObservableProperty]
private Axis[] _xAxes;
[ObservableProperty]
private Axis[] _yAxes;
[ObservableProperty]
private bool _isLoading;
[ObservableProperty]
private string _loadingMessage = "";
public PlossChartViewModel(
ScenarioService scenarioService,
ILogger<PlossChartViewModel> logger)
{
_scenarioService = scenarioService;
_logger = logger;
// 初始化图表配置
Series = Array.Empty<ISeries>();
XAxes = new Axis[] { new Axis { Name = "Trigger Count" } };
YAxes = new Axis[] { new Axis { Name = "Power Loss (mW)" } };
}
/// <summary>
/// ScenarioId 属性变更时自动触发数据加载
/// </summary>
partial void OnScenarioIdChanged(Guid value)
{
if (value != Guid.Empty)
{
_ = LoadDataAsync().ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(t.Exception, "LoadDataAsync 失败: ScenarioId={ScenarioId}", value);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
[RelayCommand]
private void SwitchToTable()
{
WeakReferenceMessenger.Default.Send(new NavigateToPlossTableMessage(ScenarioId));
}
public async Task LoadDataAsync()
{
if (IsLoading) return; // 防并发
IsLoading = true;
LoadingMessage = "正在加载数据...";
try
{
var records = await _scenarioService.GetPlossRecordsByScenarioIdAsync(ScenarioId);
if (records.Count == 0)
{
Series = Array.Empty<ISeries>();
_logger.LogWarning("未找到 Ploss 数据: ScenarioId={ScenarioId}", ScenarioId);
LoadingMessage = "无数据";
return;
}
// 构建 Ploss 曲线 (Field7) 和 Threshold 阈值线 (Field8)
var plossValues = records.Select(r => (double)r.Field7).ToArray();
var thresholdValues = records.Select(r => (double)r.Field8).ToArray();
var triggerLabels = records.Select(r => r.Field9.ToString()).ToArray();
Series = new ISeries[]
{
new LineSeries<double>
{
Name = "Ploss",
Values = plossValues,
Fill = null,
GeometrySize = 5
},
new LineSeries<double>
{
Name = "Threshold",
Values = thresholdValues,
Fill = null,
GeometrySize = 0,
LineSmoothness = 0 // 直线
}
};
// 更新 X 轴标签
XAxes = new Axis[]
{
new Axis
{
Name = "Trigger Count",
Labels = triggerLabels
}
};
_logger.LogInformation("加载 Ploss 图表数据成功: ScenarioId={ScenarioId}, 记录数={Count}", ScenarioId, records.Count);
LoadingMessage = "";
}
catch (Exception ex)
{
_logger.LogError(ex, "加载 Ploss 图表数据失败: ScenarioId={ScenarioId}", ScenarioId);
LoadingMessage = $"加载失败: {ex.Message}";
}
finally
{
IsLoading = false;
}
}
}