using DataSharing.Province.SendTask.SubmitCaseRecord;
using DotNetCore.CAP;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using Quartz;
using SqlSugar;
using XF.Domain.Repository;

namespace DataSharing.Province.SendTask
{
    public class TaskAssociateCallRecordsJob : IJob, IDisposable
    {
        private readonly IMapper _mapper;
        private readonly ILogger<TaskRepublishFiledOrdersJob> _logger;
        private readonly IRepository<DsSendTaskSubmitCaseRecord> _dsSendTaskSubmitCaseRecordRepository;
        private readonly ICapPublisher _capPublisher;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        public TaskAssociateCallRecordsJob(IMapper mapper,
            ILogger<TaskRepublishFiledOrdersJob> logger,
           IRepository<DsSendTaskSubmitCaseRecord> dsSendTaskSubmitCaseRecordRepository,
             ICapPublisher capPublisher,
             ISharingConfigurationManager sharingConfigurationManager)
        {
            _mapper = mapper;
            _logger = logger;
            _dsSendTaskSubmitCaseRecordRepository = dsSendTaskSubmitCaseRecordRepository;
            _capPublisher = capPublisher;
            _sharingConfigurationManager = sharingConfigurationManager;
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
                return;

            var items = await _dsSendTaskSubmitCaseRecordRepository.Queryable()
                    .Where(p => p.CreationTime >= Convert.ToDateTime("2024-10-26 00:00:00") && p.CreationTime >= DateTime.Now.AddDays(-5)
                    && p.IsSuccess == DataSharing.Share.Enums.ESendTaskState.PushSuccess
                    && (p.ProvinceNo == null || p.ProvinceNo == ""))
               .Where(p => SqlFunc.Subqueryable<DsSendTaskSubmitCaseRecord>()
                                .Where(s => s.CallId == p.CallId && s.ProvinceNo != null && s.ProvinceNo != "").NotAny())
               .MergeTable()
               .Select(p => p.CallId)
               .ToListAsync();

            if (items != null && items.Any())
            {
                //如果小于1000条数据直接执行
                if (items.Count < 1000)
                {
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.RecUnrelationCalls, items, cancellationToken: context.CancellationToken);
                }
                else
                {
                    //如果大于1000条数据，分批次执行
                    int nPageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(items.Count) / 1000));
                    for (int i = 0; i < nPageCount; i++)
                    {
                        List<string?> lisreturn = [];
                        lisreturn = items.Skip(i * 1000).Take(1000).ToList();
                        await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.RecUnrelationCalls, lisreturn, cancellationToken: context.CancellationToken);

                        Thread.Sleep(2000);
                    }

                }
            }

        }
        public void Dispose()
        {

        }
    }
}
