DeleteRobotTaskCommandHandler.cs 2.18 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>
/// 删除任务命令处理器
/// @author zzy
/// </summary>
public class DeleteRobotTaskCommandHandler : IConsumer<DeleteRobotTaskCommand>
{
    private readonly ILogger<DeleteRobotTaskCommandHandler> _logger;
    private readonly IRobotTaskRepository _robotTaskRepository;
    private readonly IRobotRepository _robotRepository;

    public DeleteRobotTaskCommandHandler(
        ILogger<DeleteRobotTaskCommandHandler> logger,
        IRobotTaskRepository robotTaskRepository,
        IRobotRepository robotRepository)
    {
        _logger = logger;
        _robotTaskRepository = robotTaskRepository;
        _robotRepository = robotRepository;
    }

    public async Task Consume(ConsumeContext<DeleteRobotTaskCommand> context)
    {
        var command = context.Message;
        try
        {
            var task = await _robotTaskRepository.GetByIdAsync(command.TaskId, context.CancellationToken);
            if (task == null)
            {
                await context.RespondAsync(ApiResponse.Failed($"未找到任务ID为 {command.TaskId} 的任务"));
                return;
            }

            // 如果任务状态是执行中,需要触发机器人取消任务
            // @author zzy
            if (task.IsInProgress() && task.RobotId.HasValue)
            {
                var robot = await _robotRepository.GetByIdAsync(task.RobotId.Value, context.CancellationToken);
                if (robot != null)
                {
                    robot.CancelTask(task.TaskCode);
                    await _robotRepository.UpdateAsync(robot, context.CancellationToken);
                }
            }

            await _robotTaskRepository.DeleteAsync(task, context.CancellationToken);

            await context.RespondAsync(ApiResponse.Successful("删除成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除任务失败");
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }
}