TaskCompletedDomainEventHandler.cs 2.73 KB
using Microsoft.Extensions.Logging;
using Rcs.Domain.Entities;
using Rcs.Domain.Entities.DomainEvents.RobotTask;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Events.RobotTask
{
    /// <summary>
    /// 任务完成领域事件处理器
    /// 更新库位状态:起点改为空闲,终点改为有货
    /// @author zzy
    /// </summary>
    public class TaskCompletedDomainEventHandler
    {
        private readonly ILogger<TaskCompletedDomainEventHandler> _logger;
        private readonly IRobotTaskRepository _taskRepository;
        private readonly IStorageLocationRepository _locationRepository;

        public TaskCompletedDomainEventHandler(
            ILogger<TaskCompletedDomainEventHandler> logger,
            IRobotTaskRepository taskRepository,
            IStorageLocationRepository locationRepository)
        {
            _logger = logger;
            _taskRepository = taskRepository;
            _locationRepository = locationRepository;
        }

        public async System.Threading.Tasks.Task Handle(TaskCompletedDomainEvent domainEvent)
        {
            _logger.LogInformation("TaskCompletedDomainEvent - 任务ID: {TaskId}", domainEvent.TaskId);

            var task = await _taskRepository.GetByIdAsync(domainEvent.TaskId);
            if (task == null)
            {
                _logger.LogWarning("任务不存在: {TaskId}", domainEvent.TaskId);
                return;
            }

            // 更新起点库位为空闲
            if (task.BeginLocationId.HasValue)
            {
                var beginLocation = await _locationRepository.GetByIdAsync(task.BeginLocationId.Value);
                if (beginLocation != null)
                {
                    beginLocation.Status = StorageLocationStatus.Empty;
                    beginLocation.UpdatedAt = DateTime.Now;
                    await _locationRepository.UpdateAsync(beginLocation);
                    _logger.LogInformation("起点库位 {LocationId} 状态更新为空闲", task.BeginLocationId.Value);
                }
            }

            // 更新终点库位为有货
            if (task.EndLocationId.HasValue)
            {
                var endLocation = await _locationRepository.GetByIdAsync(task.EndLocationId.Value);
                if (endLocation != null)
                {
                    endLocation.Status = StorageLocationStatus.Occupied;
                    endLocation.UpdatedAt = DateTime.Now;
                    await _locationRepository.UpdateAsync(endLocation);
                    _logger.LogInformation("终点库位 {LocationId} 状态更新为有货", task.EndLocationId.Value);
                }
            }

            await _locationRepository.SaveChangesAsync();
        }
    }
}