using AutoMapper;
using DMS.Application.DTOs;
using DMS.Application.DTOs.Events;
using DMS.Core.Models;
using DMS.Application.Interfaces;
using DMS.Core.Interfaces;
using DMS.Core.Enums;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
namespace DMS.Application.Services;
///
/// 设备管理服务,负责设备相关的业务逻辑。
///
public class DeviceManagementService
{
private readonly IDeviceAppService _deviceAppService;
private readonly ConcurrentDictionary _devices;
///
/// 当设备数据发生变化时触发
///
public event EventHandler DeviceChanged;
public DeviceManagementService(IDeviceAppService deviceAppService, ConcurrentDictionary devices)
{
_deviceAppService = deviceAppService;
_devices = devices;
}
///
/// 异步根据ID获取设备DTO。
///
public async Task GetDeviceByIdAsync(int id)
{
return await _deviceAppService.GetDeviceByIdAsync(id);
}
///
/// 异步获取所有设备DTO列表。
///
public async Task> GetAllDevicesAsync()
{
return await _deviceAppService.GetAllDevicesAsync();
}
///
/// 异步创建一个新设备及其关联的变量表和菜单(事务性操作)。
///
public async Task CreateDeviceWithDetailsAsync(CreateDeviceWithDetailsDto dto)
{
return await _deviceAppService.CreateDeviceWithDetailsAsync(dto);
}
///
/// 异步更新一个已存在的设备。
///
public async Task UpdateDeviceAsync(DeviceDto deviceDto)
{
return await _deviceAppService.UpdateDeviceAsync(deviceDto);
}
///
/// 异步删除一个设备。
///
public async Task DeleteDeviceByIdAsync(int deviceId)
{
return await _deviceAppService.DeleteDeviceByIdAsync(deviceId);
}
///
/// 异步切换设备的激活状态。
///
public async Task ToggleDeviceActiveStateAsync(int id)
{
await _deviceAppService.ToggleDeviceActiveStateAsync(id);
}
///
/// 在内存中添加设备
///
public void AddDeviceToMemory(DeviceDto deviceDto, ConcurrentDictionary variableTables,
ConcurrentDictionary variables)
{
if (_devices.TryAdd(deviceDto.Id, deviceDto))
{
OnDeviceChanged(new DeviceChangedEventArgs(DataChangeType.Added, deviceDto));
}
}
///
/// 在内存中更新设备
///
public void UpdateDeviceInMemory(DeviceDto deviceDto)
{
_devices.AddOrUpdate(deviceDto.Id, deviceDto, (key, oldValue) => deviceDto);
OnDeviceChanged(new DeviceChangedEventArgs(DataChangeType.Updated, deviceDto));
}
///
/// 在内存中删除设备
///
public void RemoveDeviceFromMemory(int deviceId, ConcurrentDictionary variableTables,
ConcurrentDictionary variables)
{
if (_devices.TryGetValue(deviceId, out var deviceDto))
{
foreach (var variableTable in deviceDto.VariableTables)
{
foreach (var variable in variableTable.Variables)
{
variables.TryRemove(variable.Id, out _);
}
variableTables.TryRemove(variableTable.Id, out _);
}
_devices.TryRemove(deviceId, out _);
OnDeviceChanged(new DeviceChangedEventArgs(DataChangeType.Deleted, deviceDto));
}
}
///
/// 触发设备变更事件
///
protected virtual void OnDeviceChanged(DeviceChangedEventArgs e)
{
DeviceChanged?.Invoke(this, e);
}
}