Files
DMS/ViewModels/MqttsViewModel.cs

113 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using PMSWPF.Data;
using PMSWPF.Data.Repositories;
using PMSWPF.Enums;
using PMSWPF.Helper;
using PMSWPF.Models;
using PMSWPF.Services;
namespace PMSWPF.ViewModels;
public partial class MqttsViewModel : ViewModelBase
{
private readonly DataServices _dataServices;
private readonly IDialogService _dialogService;
private readonly MqttRepository _mqttRepository;
private readonly ILogger<MqttsViewModel> _logger;
[ObservableProperty]
private ObservableCollection<Mqtt> _mqtts;
[ObservableProperty]
private Mqtt _selectedMqtt;
public MqttsViewModel(
ILogger<MqttsViewModel> logger, IDialogService dialogService, DataServices dataServices
)
{
_mqttRepository = new MqttRepository();
_logger = logger;
_dialogService = dialogService;
_dataServices = dataServices;
MessageHelper.SendLoadMessage(LoadTypes.Mqtts);
_dataServices.OnMqttListChanged += (mqtts) => { Mqtts = new ObservableCollection<Mqtt>(mqtts); };
}
[RelayCommand]
public async void AddMqtt()
{
try
{
var mqtt = await _dialogService.ShowAddMqttDialog();
if (mqtt == null)
{
_logger.LogInformation("用户取消了添加MQTT操作。");
return;
}
await _mqttRepository.Add(mqtt);
}
catch (Exception e)
{
NotificationHelper.ShowMessage($"添加MQTT的过程中发生错误{e.Message}", NotificationType.Error);
_logger.LogError($"添加MQTT的过程中发生错误{e}");
}
}
[RelayCommand]
public async void DeleteMqtt()
{
try
{
if (SelectedMqtt == null)
{
NotificationHelper.ShowMessage("你没有选择任何MQTT请选择MQTT后再点击删除", NotificationType.Error);
return;
}
string msg = $"确认要删除MQTT名为:{SelectedMqtt.Name}";
var isDel = await _dialogService.ShowConfrimeDialog("删除MQTT", msg, "删除MQTT");
if (isDel)
{
await _mqttRepository.Delete(SelectedMqtt);
MessageHelper.SendLoadMessage(LoadTypes.Mqtts);
NotificationHelper.ShowMessage($"删除MQTT成功,MQTT名{SelectedMqtt.Name}", NotificationType.Success);
}
}
catch (Exception e)
{
NotificationHelper.ShowMessage($"删除MQTT的过程中发生错误{e.Message}", NotificationType.Error);
_logger.LogError($"删除MQTT的过程中发生错误{e}");
}
}
[RelayCommand]
public async void EditMqtt()
{
try
{
if (SelectedMqtt == null)
{
NotificationHelper.ShowMessage("你没有选择任何MQTT请选择MQTT后再点击编辑", NotificationType.Error);
return;
}
var editMqtt = await _dialogService.ShowEditMqttDialog(SelectedMqtt);
if (editMqtt != null)
{
var res = await _mqttRepository.Edit(editMqtt);
MessageHelper.SendLoadMessage(LoadTypes.Mqtts);
}
}
catch (Exception e)
{
NotificationHelper.ShowMessage($"编辑MQTT的过程中发生错误{e.Message}", NotificationType.Error);
_logger.LogError($"编辑MQTT的过程中发生错误{e}");
}
}
}