using Hotline.Caching.Interfaces;
using Hotline.JudicialManagement;
using Hotline.Realtimes;
using Hotline.Settings;
using Hotline.Share.Dtos.JudicialManagement;
using MapsterMapper;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using XF.Domain.Repository;

namespace Hotline.Application.Bigscreen
{
    internal class EnforcementDataScreenRefreshService : BackgroundService
    {
        private readonly IServiceScopeFactory _serviceScopeFactory;

        public EnforcementDataScreenRefreshService(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using var scope = _serviceScopeFactory.CreateScope();
            var realtimeService = scope.ServiceProvider.GetRequiredService<IRealtimeService>();
            var _judicialManagementOrdersRepository = scope.ServiceProvider.GetRequiredService<IRepository<JudicialManagementOrders>>();
            var _mapper = scope.ServiceProvider.GetRequiredService<IMapper>();
            var systemSettingCacheManager = scope.ServiceProvider.GetRequiredService<ISystemSettingCacheManager>();

            int times = int.Parse(systemSettingCacheManager.GetSetting(SettingConstants.EnforcementDataOrderChangedTimes)?.SettingValue[0]);
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {

                    var list = await _judicialManagementOrdersRepository.Queryable()
                  .LeftJoin<SystemArea>((o, s) => o.AreaCode == s.Id)
                  .Where((o, s) => o.CreationTime.Date == DateTime.Now.Date)
                  .Select((o, s) => new 
                  {
                      o.Id,
                      o.SourceChannel,
                      o.SourceChannelCode,
                      o.Title,
                      o.AcceptType,
                      o.AcceptTypeCode,
                      o.HotspotId,
                      o.HotspotName,
                      o.EnforcementOrdersHandler,
                      s.AreaName,
                      o.CreationTime
                  })
                  .OrderByDescending(d => d.CreationTime)
                  .Take(50)
                  .ToListAsync();

                    var orderlist = _mapper.Map<List<OrderOverviewDto>>(list);

                    await realtimeService.EnforcementOrderHandlingDetailAsync(orderlist, stoppingToken);
                }
                catch { }

                await Task.Delay(times);
            }
        }
    }
}
