Files
DMS/DMS.WPF/ViewModels/VariableHistoryViewModel.cs

289 lines
9.8 KiB
C#
Raw Normal View History

2025-09-11 11:04:07 +08:00
using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
2025-09-17 17:18:10 +08:00
using DMS.Application.Interfaces.Database;
using DMS.Core.Events;
2025-09-11 11:04:07 +08:00
using DMS.WPF.Interfaces;
using DMS.WPF.ViewModels.Items;
2025-09-17 14:13:48 +08:00
using LiveCharts;
using LiveCharts.Defaults;
2025-09-17 17:18:10 +08:00
using LiveCharts.Wpf;
using ObservableCollections;
2025-09-11 11:04:07 +08:00
namespace DMS.WPF.ViewModels;
partial class VariableHistoryViewModel : ViewModelBase, INavigatable
2025-09-11 11:04:07 +08:00
{
private readonly IMapper _mapper;
private readonly IDialogService _dialogService;
private readonly IHistoryAppService _historyAppService;
2025-09-11 11:04:07 +08:00
private readonly IWPFDataService _wpfDataService;
private readonly IDataStorageService _dataStorageService;
2025-09-17 17:18:10 +08:00
private readonly IEventService _eventService;
2025-09-11 11:04:07 +08:00
private readonly INotificationService _notificationService;
/// <summary>
/// 历史记录条数限制
2025-09-11 11:04:07 +08:00
/// </summary>
[ObservableProperty]
private int? _historyLimit;
2025-09-11 11:04:07 +08:00
/// <summary>
/// 历史记录开始时间
2025-09-11 11:04:07 +08:00
/// </summary>
[ObservableProperty]
private DateTime? _startTime;
2025-09-11 11:04:07 +08:00
/// <summary>
/// 历史记录结束时间
2025-09-11 11:04:07 +08:00
/// </summary>
[ObservableProperty]
private DateTime? _endTime;
2025-09-12 08:35:35 +08:00
/// <summary>
/// 选中的变量历史记录
/// </summary>
[ObservableProperty]
private VariableItemViewModel _currentVariable;
2025-09-11 11:04:07 +08:00
/// <summary>
/// 变量历史记录列表
/// </summary>
public NotifyCollectionChangedSynchronizedViewList<VariableHistoryDto> VariableHistories { get; }
2025-09-17 14:13:48 +08:00
// 折线图相关属性
public SeriesCollection LineSeriesCollection { get; set; }
[ObservableProperty]
private AxesCollection _lineAxisX;
[ObservableProperty]
private AxesCollection _lineAxisY;
2025-09-11 11:04:07 +08:00
private readonly ObservableList<VariableHistoryDto> _variableHistoryList;
private readonly ISynchronizedView<VariableHistoryDto, VariableHistoryDto> _variableHistorySynchronizedView;
/// <summary>
/// 所有变量的缓存列表,用于搜索
/// </summary>
private List<VariableHistoryDto> _allVariableHistories;
public VariableHistoryViewModel(IMapper mapper, IDialogService dialogService, IHistoryAppService historyAppService,
IWPFDataService wpfDataService, IDataStorageService dataStorageService,
2025-09-17 17:18:10 +08:00
IEventService eventService,
INotificationService notificationService)
2025-09-11 11:04:07 +08:00
{
_mapper = mapper;
_dialogService = dialogService;
_historyAppService = historyAppService;
2025-09-11 11:04:07 +08:00
_wpfDataService = wpfDataService;
_dataStorageService = dataStorageService;
2025-09-17 17:18:10 +08:00
_eventService = eventService;
2025-09-11 11:04:07 +08:00
_notificationService = notificationService;
_variableHistoryList = new ObservableList<VariableHistoryDto>();
_variableHistorySynchronizedView = _variableHistoryList.CreateView(v => v);
VariableHistories = _variableHistorySynchronizedView.ToNotifyCollectionChanged();
_allVariableHistories = new List<VariableHistoryDto>();
// 初始化默认值
_historyLimit = 1000; // 默认限制1000条记录
_startTime = null;
_endTime = null;
2025-09-17 14:13:48 +08:00
// 初始化图表属性
LineAxisX = new AxesCollection { new Axis() };
LineAxisY = new AxesCollection { new Axis() };
LineSeriesCollection = new SeriesCollection();
2025-09-17 17:18:10 +08:00
_eventService.OnVariableValueChanged += OnVariableValueChanged;
}
private void OnVariableValueChanged(object? sender, VariableValueChangedEventArgs e)
{
if (e.VariableId!= CurrentVariable.Id)
{
return;
}
var variableHistory = new VariableHistoryDto()
{
VariableId = CurrentVariable.Id,
Timestamp = DateTime.Now,
Value = e.NewValue
};
_variableHistoryList.Add(variableHistory);
2025-09-11 11:04:07 +08:00
}
/// <summary>
/// 加载所有变量的历史记录
2025-09-11 11:04:07 +08:00
/// </summary>
/// <param name="limit">返回记录的最大数量null表示无限制</param>
/// <param name="startTime">开始时间null表示无限制</param>
/// <param name="endTime">结束时间null表示无限制</param>
2025-09-17 14:13:48 +08:00
private async void LoadAllVariableHistories(int variableId, int? limit = null, DateTime? startTime = null,
DateTime? endTime = null)
2025-09-11 11:04:07 +08:00
{
try
2025-09-11 11:04:07 +08:00
{
_variableHistoryList.Clear();
2025-09-17 14:13:48 +08:00
var allHistories
= await _historyAppService.GetVariableHistoriesAsync(variableId, limit, startTime, endTime);
_allVariableHistories = allHistories.ToList();
_variableHistoryList.AddRange(_allVariableHistories);
2025-09-17 14:13:48 +08:00
// 更新图表数据
UpdateChartData();
2025-09-11 11:04:07 +08:00
}
catch (Exception ex)
2025-09-11 11:04:07 +08:00
{
// 记录更详细的错误信息
_notificationService.ShowError($"加载变量历史记录失败: {ex.Message}", ex);
2025-09-11 11:04:07 +08:00
}
}
2025-09-12 08:35:35 +08:00
public async Task OnNavigatedToAsync(MenuItemViewModel menu)
{
if (_dataStorageService.Variables.TryGetValue(menu.TargetId, out VariableItemViewModel variableItem))
{
CurrentVariable = variableItem;
// 加载所有变量的历史记录
2025-09-17 14:13:48 +08:00
LoadAllVariableHistories(variableItem.Id, HistoryLimit, StartTime, EndTime);
}
2025-09-12 08:35:35 +08:00
}
2025-09-12 08:35:35 +08:00
/// <summary>
/// 重新加载历史记录命令
/// </summary>
[RelayCommand]
private void Reload()
{
2025-09-17 14:13:48 +08:00
if (CurrentVariable != null)
2025-09-11 11:04:07 +08:00
{
2025-09-17 14:13:48 +08:00
LoadAllVariableHistories(CurrentVariable.Id, HistoryLimit, StartTime, EndTime);
2025-09-11 11:04:07 +08:00
}
}
2025-09-12 08:35:35 +08:00
/// <summary>
/// 根据搜索文本过滤历史记录
/// </summary>
/// <param name="searchText"></param>
private void FilterHistoriesBySearchText(string searchText)
{
2025-09-12 08:35:35 +08:00
if (string.IsNullOrWhiteSpace(searchText))
{
// 如果搜索文本为空,显示所有历史记录
_variableHistoryList.Clear();
_variableHistoryList.AddRange(_allVariableHistories);
}
else
{
// 根据搜索文本过滤历史记录
var filteredHistories = _allVariableHistories
.Where(h =>
h.VariableName?.Contains(
searchText, StringComparison.OrdinalIgnoreCase) == true)
.ToList();
_variableHistoryList.Clear();
_variableHistoryList.AddRange(filteredHistories);
}
}
/// <summary>
/// 根据变量ID加载历史记录
/// </summary>
/// <param name="variableId">变量ID</param>
/// <param name="limit">返回记录的最大数量null表示无限制</param>
/// <param name="startTime">开始时间null表示无限制</param>
/// <param name="endTime">结束时间null表示无限制</param>
public async Task LoadVariableHistoriesAsync(int variableId, int? limit = null, DateTime? startTime = null,
DateTime? endTime = null)
2025-09-11 11:04:07 +08:00
{
try
2025-09-11 11:04:07 +08:00
{
_variableHistoryList.Clear();
var histories = await _historyAppService.GetVariableHistoriesAsync(variableId, limit, startTime, endTime);
_variableHistoryList.AddRange(histories);
2025-09-17 14:13:48 +08:00
// 更新图表数据
UpdateChartData();
}
catch (Exception ex)
{
// 记录更详细的错误信息
_notificationService.ShowError($"加载变量历史记录失败: {ex.Message}", ex);
2025-09-11 11:04:07 +08:00
}
}
2025-09-17 14:13:48 +08:00
/// <summary>
/// 更新图表数据
/// </summary>
private void UpdateChartData()
{
if (_variableHistoryList == null || _variableHistoryList.Count == 0)
{
// 清空图表数据
LineSeriesCollection?.Clear();
OnPropertyChanged(nameof(LineSeriesCollection));
return;
}
// 创建数值点集合
var values = new ChartValues<DateTimePoint>();
foreach (var history in _variableHistoryList)
{
// 尝试将值转换为double
if (double.TryParse(history.Value, out double value))
{
values.Add(new DateTimePoint(history.Timestamp, value));
}
}
// 确保LineSeriesCollection已初始化
if (LineSeriesCollection == null)
{
LineSeriesCollection = new SeriesCollection();
}
// 清空旧数据并添加新系列
LineSeriesCollection.Clear();
LineSeriesCollection.Add(new LineSeries
{
Title = "变量值",
Values = values,
PointGeometry = null, // 不显示数据点,只显示线条
LineSmoothness = 0.5, // 设置线条平滑度
StrokeThickness = 2
});
// 确保坐标轴集合已初始化
if (LineAxisX == null || LineAxisX.Count == 0)
{
LineAxisX = new AxesCollection { new Axis() };
}
if (LineAxisY == null || LineAxisY.Count == 0)
{
LineAxisY = new AxesCollection { new Axis() };
}
// 设置坐标轴
// X轴使用时间格式化
LineAxisX[0].LabelFormatter = value => new DateTime((long)value).ToString("MM-dd HH:mm:ss");
// Y轴使用数值格式化
LineAxisY[0].Title = "值";
LineAxisY[0].LabelFormatter = value => value.ToString("F2");
// 通知属性更改
OnPropertyChanged(nameof(LineSeriesCollection));
OnPropertyChanged(nameof(LineAxisX));
OnPropertyChanged(nameof(LineAxisY));
}
2025-09-11 11:04:07 +08:00
}