DeleteRobotCommandHandler.cs 1.68 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 删除机器人命令处理器
/// </summary>
public class DeleteRobotCommandHandler : IConsumer<DeleteRobotCommand>
{
    private readonly ILogger<DeleteRobotCommandHandler> _logger;
    private readonly IRobotRepository _robotRepository;

    public DeleteRobotCommandHandler(
        ILogger<DeleteRobotCommandHandler> logger,
        IRobotRepository robotRepository)
    {
        _logger = logger;
        _robotRepository = robotRepository;
    }

    public async Task Consume(ConsumeContext<DeleteRobotCommand> context)
    {
        var command = context.Message;

        try
        {
            // 获取机器人
            var robot = await _robotRepository.GetByIdAsync(
                command.RobotId, 
                context.CancellationToken);

            if (robot == null)
            {
                throw new InvalidOperationException($"机器人ID {command.RobotId} 不存在");
            }

            // 检查机器人状态,如果正在忙碌则不允许删除
            if (robot.Status == Domain.Entities.RobotStatus.Busy)
            {
                throw new InvalidOperationException($"机器人 {robot.RobotCode} 正在忙碌,不允许删除");
            }

            await _robotRepository.DeleteByIdAsync(command.RobotId);
            await context.RespondAsync(ApiResponse.Successful());
        }
        catch (Exception ex)
        {
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }
}