using Autofac;
using OpenAuth.App.ServiceApp.DroneDocking;

namespace OpenAuth.WebApi.SystemTask;

public class DelayedExecutionService : BackgroundService
{
    private readonly ILogger<DelayedExecutionService> _logger;
    private readonly ILifetimeScope _lifetimeScope;

    public DelayedExecutionService(ILogger<DelayedExecutionService> logger, ILifetimeScope lifetimeScope)
    {
        _logger = logger;
        //_droneDockApp = droneDockApp;
        _lifetimeScope = lifetimeScope;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("定时任务已启动，将每5分钟执行一次");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await PerformDelayedTask();
                await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("无人机状态上报任务被取消");
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "无人机状态上报任务发生错误");
                // 即使出错也继续下一次执行
                await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
            }
        }
    }

    private async Task PerformDelayedTask()
    {
        var scope = _lifetimeScope.BeginLifetimeScope();
        try
        {
            var appService = scope.Resolve<DroneDockApp>();
            await appService.ReportDroneStatus();
            _logger.LogInformation("ReportDroneStatus 方法执行成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "ReportDroneStatus 方法执行失败");
        }
        finally
        {
            scope.Dispose();
        }
    }
}