using DocumentFormat.OpenXml.Spreadsheet;
using Infrastructure.Helpers;
using OpenAuth.App.ServiceApp.Algo;
using OpenAuth.WebApi.Model.mqtt;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace OpenAuth.WebApi.Model.RabbitMQService
{
    public class RabbitMqListenerService : BackgroundService
    {
        private readonly ILogger<RabbitMqListenerService> _logger;
        private readonly DaHuaAiApp _app;
        private IConnection _connection;
        private IChannel _channel;
        private readonly ConnectionFactory _factory;

        public RabbitMqListenerService(ILogger<RabbitMqListenerService> logger, DaHuaAiApp app)
        {
            _logger = logger;
            _app = app;
            var config = ConfigHelper.GetConfigRoot();
            _factory = new()
            {
                HostName = config["RabbitMQ:HostName"],
                UserName = config["RabbitMQ:UserName"],
                Password = config["RabbitMQ:Password"],
                Port = int.Parse(config["RabbitMQ:Port"]),
            };
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("RabbitMQ listener starting...");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // 建立连接
                    _connection = await _factory.CreateConnectionAsync(stoppingToken);
                    _channel = await _connection.CreateChannelAsync();

                    _logger.LogInformation("RabbitMQ connected successfully.");

                    await StartConsumeAsync(_channel, stoppingToken);

                    // 阻塞直到断开
                    await Task.Delay(Timeout.Infinite, stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "RabbitMQ connection failed. Retrying in 5 seconds...");
                    await Task.Delay(5000, stoppingToken);
                }
            }
        }

        private async Task StartConsumeAsync(IChannel channel, CancellationToken token)
        {
            var q = await channel.QueueDeclareAsync("", false, true, true);
            await channel.QueueBindAsync(q.QueueName, "processing_event", "event.behaviorAlarm.picture.1.#");
            await channel.QueueBindAsync(q.QueueName, "storage_event", "event.trafficEvent.1.#");

            var consumer = new AsyncEventingBasicConsumer(channel);
            consumer.ReceivedAsync += async (_, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                try
                {
                    switch (ea.Exchange)
                    {
                        case "processing_event":
                            await _app.AddDaHuaImg(message);
                            break;
                        case "storage_event":
                            await _app.AddDaHuaSmokeDetectionImg(message);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "处理消息失败");
                }
            };

            await channel.BasicConsumeAsync(q.QueueName, autoAck: true, consumer);

            _logger.LogInformation("RabbitMQ Consumer started.");
        }
    }

}
