using DataSharing.Province.SendTask.SubmitCaseInfo;
using DataSharing.Province.SendTask.SubmitCaseRecord;
using DataSharing.Share.Enums;
using DotNetCore.CAP;
using Quartz;
using SqlSugar;
using XF.Domain.Repository;

namespace DataSharing.Province.SendTask
{
    public class TaskGetOrderMatchingCallListJob : IJob, IDisposable
    {
        private readonly ICapPublisher _capPublisher;
        private readonly IRepository<DsSendTaskSubmitCaseInfo> _sendTaskSubmitCaseInfoRepository;

        public TaskGetOrderMatchingCallListJob(
            ICapPublisher capPublisher,
            IRepository<DsSendTaskSubmitCaseInfo> sendTaskSubmitCaseInfoRepository
            )
        {
            _capPublisher = capPublisher;
            _sendTaskSubmitCaseInfoRepository = sendTaskSubmitCaseInfoRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            DateTime startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
            DateTime endTime = DateTime.Now;

            var items = await _sendTaskSubmitCaseInfoRepository.Queryable()
              .Where(p => p.GenerationTime >= startTime && p.GenerationTime <= endTime)
             .Where(p => p.LastTime >= startTime && p.LastTime <= endTime && p.IsSuccess == ESendTaskState.PushSuccess)
               .Select(p => new
               {
                   index = SqlFunc.RowNumber($"{p.CreationTime} DESC ", $"{p.ProvinceNo}"),
                   p.ProvinceNo,
                   p.CaseSource,
                   p.OrderId
               })
               .MergeTable()
               .Where(d => d.index == 1 && d.CaseSource == "RGDH")
               .Where(p => SqlFunc.Subqueryable<DsSendTaskSubmitCaseRecord>().Where(s => s.ProvinceNo == p.ProvinceNo).OrderByDesc(s => s.LastTime).NotAny())
                .Select(p => p.ProvinceNo)
               .ToListAsync();


            if (items != null && items.Any())
            {
                //如果小于1000条数据直接执行
                if (items.Count < 1000)
                {
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.RecUpdateOrderSourceChannel, 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.RecUpdateOrderSourceChannel, lisreturn, cancellationToken: context.CancellationToken);

                        Thread.Sleep(2000);
                    }

                }
            }
        }

        public void Dispose()
        {

        }

    }
}
