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

namespace DataSharing.Province.SendTask
{
    /// <summary>
    /// 处理每天办理完成未及时推送办理结果的数据
    /// </summary>
    public class TaskRepublishFiledOrdersJob : IJob, IDisposable
    {
        private readonly IMapper _mapper;
        private readonly ILogger<TaskRepublishFiledOrdersJob> _logger;
        private readonly IRepository<DsSendTaskSubmitCaseInfo> _sendTaskSubmitCaseInfoRepository;
        private readonly ICapPublisher _capPublisher;

        public TaskRepublishFiledOrdersJob(IMapper mapper,
            ILogger<TaskRepublishFiledOrdersJob> logger,
            IRepository<DsSendTaskSubmitCaseInfo> sendTaskSubmitCaseInfoRepository,
             ICapPublisher capPublisher)
        {
            _mapper = mapper;
            _logger = logger;
            _sendTaskSubmitCaseInfoRepository = sendTaskSubmitCaseInfoRepository;
            _capPublisher = capPublisher;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            //查询推送了受理信息，没有推送工单结果的数据
            var items = await _sendTaskSubmitCaseInfoRepository.Queryable()
                  .Where(p => p.FirstTime >= Convert.ToDateTime("2024-08-01"))
                  .Where(p => SqlFunc.Subqueryable<DsSendTaskSubmitCaseResult>().Where(s => s.ProvinceNo == p.ProvinceNo).NotAny())
                  .GroupBy(p => p.ProvinceNo)
                  .Select(p => p.ProvinceNo)
                  .ToListAsync();
            if (items.Any())
            {
                //如果小于1000条数据直接执行
                if (items.Count < 1000)
                {
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineFiledOrdersRepublish, 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.HotlineFiledOrdersRepublish, lisreturn, cancellationToken: context.CancellationToken);

                        Thread.Sleep(2000);
                    }
                }
            }
        }

        public void Dispose()
        {

        }

    }
}
