Files
DMS/Services/DataServices.cs

93 lines
2.7 KiB
C#
Raw Normal View History

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PMSWPF.Data.Repositories;
using PMSWPF.Enums;
using PMSWPF.Helper;
using PMSWPF.Message;
using PMSWPF.Models;
using PMSWPF.ViewModels;
2025-07-01 21:34:20 +08:00
using SqlSugar;
namespace PMSWPF.Services;
2025-06-30 13:06:51 +08:00
public partial class DataServices : ObservableRecipient, IRecipient<LoadMessage>
{
private readonly ILogger<DataServices> _logger;
[ObservableProperty] private List<Device> _devices;
[ObservableProperty] private List<VariableTable> _variableTables;
2025-07-01 21:34:20 +08:00
[ObservableProperty] private List<MenuBean> menuTrees;
private readonly DeviceRepository _deviceRepository;
private readonly MenuRepository _menuRepository;
public event Action<List<Device>> OnDeviceListChanged;
2025-07-01 21:34:20 +08:00
public event Action<List<MenuBean>> OnMenuTreeListChanged;
2025-06-30 13:06:51 +08:00
partial void OnDevicesChanged(List<Device> devices)
{
OnDeviceListChanged?.Invoke(devices);
}
2025-07-01 21:34:20 +08:00
partial void OnMenuTreesChanged(List<MenuBean> MenuTrees)
{
2025-07-01 21:34:20 +08:00
OnMenuTreeListChanged?.Invoke(MenuTrees);
}
2025-06-30 13:06:51 +08:00
public DataServices(ILogger<DataServices> logger)
{
_logger = logger;
IsActive = true;
2025-06-30 13:06:51 +08:00
_deviceRepository = new DeviceRepository();
_menuRepository = new MenuRepository();
}
/// <summary>
/// 接受加载消息,收到消息后从数据库加载对应的数据
/// </summary>
/// <param name="message">消息的类型如加载菜单LoadMessage.Menu</param>
/// <exception cref="ArgumentException"></exception>
2025-06-30 13:06:51 +08:00
public async void Receive(LoadMessage message)
{
try
{
switch (message.LoadType)
{
2025-06-30 13:06:51 +08:00
case LoadTypes.All:
await LoadDevices();
await LoadMenus();
break;
case LoadTypes.Devices:
await LoadDevices();
break;
case LoadTypes.Menu:
await LoadMenus();
break;
}
}
catch (Exception e)
{
NotificationHelper.ShowMessage($"加载数据出现了错误:{e.Message}");
_logger.LogError($"加载数据出现了错误:{e}");
}
}
2025-06-30 13:06:51 +08:00
private async Task LoadDevices()
{
Devices = await _deviceRepository.GetAll();
}
private async Task LoadMenus()
{
2025-07-01 21:34:20 +08:00
MenuTrees = await _menuRepository.GetMenuTrees();
foreach (MenuBean menu in MenuTrees)
{
MenuHelper.MenuAddParent(menu);
DataServicesHelper.SortMenus(menu);
}
}
}