using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;

namespace AutoTurnOver.Utility
{
    public class RabbitWorkerBase<T> : BackgroundService where T : class
    {
        private List<IModel> _channelList = new List<IModel>();
        private string _taskName;
        private string _queueName;
        private int _exampleNumber;
        private Timer _timer;
        private bool _isZip;

        public RabbitWorkerBase(string taskName, string queueName, int exampleNumber, bool isZip = false)
        {
            _taskName = taskName;
            _queueName = queueName;
            _exampleNumber = exampleNumber;
            _isZip = isZip;
        }


        private void TimerDoWork(object state)
        {
            int changeExampleNumber = 2;
            //for (int i = 0; i < _channelList.Count; i++)
            //{
            //    var channel = _channelList[0];
            //    channel.Close();
            //    channel.Dispose();
            //    _channelList.Remove(channel);
            //}
            while (_channelList.Count >= 1)
            {
                var channel = _channelList[0];
                channel.Close();
                channel.Dispose();
                _channelList.Remove(channel);
            }
            for (int i = 0; i < changeExampleNumber; i++)
            {
                var channel = RabbitMQHelper.GetChannel();
                RabbitMQHelper.Receive<T>("", _queueName, channel, (taskDto) => DoWorkAsync(taskDto).GetAwaiter().GetResult(), _isZip);
                _channelList.Add(channel);
            }

        }

        protected virtual Task DoWork(T taskDto)
        {
            return Task.CompletedTask;
        }


        private async Task DoWorkAsync(T taskDto)
        {
            try
            {
                await DoWork(taskDto);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"异常:{ex.Message},详细{ex.StackTrace}");
            }

        }


        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine($"{_taskName}已启动");
            for (int i = 0; i < _exampleNumber; i++)
            {
                var channel = RabbitMQHelper.GetChannel();
                RabbitMQHelper.Receive<T>("", _queueName, channel, (taskDto) => DoWorkAsync(taskDto).GetAwaiter().GetResult(), _isZip);
                _channelList.Add(channel);
            }
            _timer = new Timer(TimerDoWork, null, TimeSpan.FromMinutes(120), TimeSpan.FromMinutes(120));
            return Task.CompletedTask;
        }

        public override void Dispose()
        {
            base.Dispose();
            _timer?.Dispose();
        }
    }
}
