Files

141 lines
4.7 KiB
C#
Raw Permalink Normal View History

2026-06-17 15:04:35 +08:00
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HME_MoistureLossMeter.Models;
using HME_MoistureLossMeter.Services;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using Serilog;
using System;
namespace HME_MoistureLossMeter.ViewModels
{
public partial class RecordViewModel : ViewModelBase
{
private readonly IMesService _mesService;
private readonly DeviceConfiguration _deviceConfig;
[ObservableProperty]
private ObservableCollection<HistoryRecordModel> _records = new();
[ObservableProperty]
private HistoryRecordModel _selectedRecord;
public RecordViewModel(IMesService mesService, DeviceConfiguration deviceConfig)
{
_mesService = mesService;
_deviceConfig = deviceConfig;
// 加载测试数据
LoadTestRecords();
}
private void LoadTestRecords()
{
// 从本地存储或数据库加载历史记录
// 这里使用示例数据,实际应从数据库读取
Records.Add(new HistoryRecordModel
{
RecordId = 1,
TestTime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss"),
OperatorId = 1001,
BatchNo = "BATCH-2024-001",
ExperimentId = 1,
InitialMass = 50.5f,
FinalMass = 48.2f,
MoistureLoss = 2.3f
});
Records.Add(new HistoryRecordModel
{
RecordId = 2,
TestTime = DateTime.Now.AddHours(-2).ToString("yyyy-MM-dd HH:mm:ss"),
OperatorId = 1002,
BatchNo = "BATCH-2024-002",
ExperimentId = 2,
InitialMass = 45.8f,
FinalMass = 44.1f,
MoistureLoss = 1.7f
});
}
[RelayCommand]
private async Task SyncToMes()
{
try
{
IsBusy = true;
StatusMessage = "正在同步历史数据到MES...";
var historyData = new HistoryDataModel
{
DeviceId = _deviceConfig.DeviceId,
Records = Records.ToList()
};
bool success = await _mesService.SendHistoryDataAsync(historyData);
if (success)
{
StatusMessage = "历史数据同步成功";
Log.Information("历史数据同步到MES成功");
MessageBox.Show("历史数据同步成功", "提示",
MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
StatusMessage = "历史数据同步失败";
MessageBox.Show("历史数据同步失败,请检查网络连接", "错误",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
StatusMessage = $"同步失败: {ex.Message}";
Log.Error(ex, "同步历史数据到MES失败");
MessageBox.Show($"同步失败: {ex.Message}", "错误",
MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
IsBusy = false;
}
}
[RelayCommand]
private void ClearRecords()
{
var result = MessageBox.Show("确定要清除所有历史记录吗?", "确认清除",
MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
{
Records.Clear();
StatusMessage = "历史记录已清除";
Log.Information("历史记录已清除");
}
}
[RelayCommand]
private void DeleteSelectedRecord()
{
if (SelectedRecord == null)
{
MessageBox.Show("请先选择要删除的记录", "提示",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
var result = MessageBox.Show($"确定要删除记录 #{SelectedRecord.RecordId} 吗?", "确认删除",
MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
{
Records.Remove(SelectedRecord);
SelectedRecord = null;
StatusMessage = "记录已删除";
Log.Information("记录已删除");
}
}
}
}