DeleteMapFileCommandHandler.cs 2.01 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.Services;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 删除地图背景图文件命令处理器
/// </summary>
public class DeleteMapFileCommandHandler : IConsumer<DeleteMapFileCommand>
{
    private readonly ILogger<DeleteMapFileCommandHandler> _logger;
    private readonly IFileStorageService _fileStorageService;
    private readonly IMapFileRepository _mapFileRepository;

    public DeleteMapFileCommandHandler(
        ILogger<DeleteMapFileCommandHandler> logger,
        IFileStorageService fileStorageService,
        IMapFileRepository mapFileRepository)
    {
        _logger = logger;
        _fileStorageService = fileStorageService;
        _mapFileRepository = mapFileRepository;
    }

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

        try
        {
            // 查找该地图的文件记录
            var existingMapFile = await _mapFileRepository.GetByMapIdAsync(command.MapId, context.CancellationToken);
            
            if (existingMapFile == null)
            {
                await context.RespondAsync(ApiResponse.Failed("未找到地图背景图文件"));
                return;
            }

            // 删除物理文件
            await _fileStorageService.DeleteFileAsync(existingMapFile.FilePath, context.CancellationToken);
            
            // 删除数据库记录
            await _mapFileRepository.DeleteAsync(existingMapFile, context.CancellationToken);

            await context.RespondAsync(ApiResponse.Successful("背景图删除成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除地图背景图失败: MapId={MapId}", command.MapId);
            await context.RespondAsync(ApiResponse.Failed($"删除失败: {ex.Message}"));
        }
    }
}