using DataSharing.FwDataExchange;
using DataSharing.Province;
using DataSharing.Province.SendTask;
using DataSharing.Province.SendTask.SubmitCaseInfo;
using DataSharing.Province.SendTask.SubmitCaseRecord;
using DataSharing.Province.SendTask.SubmitCaseResult;
using DataSharing.RawData;
using DataSharing.SendTask;
using DataSharing.Share.Consts;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.HotlineWeb;
using DataSharing.Share.Dtos.Province;
using DataSharing.Share.Dtos.Province.HuiJu;
using DataSharing.Share.Dtos.Province.XieTong;
using DataSharing.Share.Dtos.Province.XieTong.Receive;
using DataSharing.Share.Dtos.Province.XieTong.Send;
using DataSharing.Share.Enums;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.File;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text.Json;
using XF.Domain.Cache;
using XF.Domain.Repository;

namespace DataSharing.Host.Controllers
{
    /// <summary>
    /// 任务调度程序
    /// </summary>
    public class TaskSchedulerController : BaseController
    {
        #region 注入
        private readonly ILogger<TaskSchedulerController> _logger;
        private readonly IRepository<DsSendCaseInfo> _sendCaseInfoRepository;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly XieTongClient _xieTongClient;
        private readonly IMapper _mapper;
        private readonly IRepository<DsGetCaseDistrecordSend> _getCaseDistrecordSendRepository;
        private readonly ICapPublisher _capPublisher;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IRepository<DsGetCaseMaterialInfo> _getCaseMaterialInfoRepository;
        private readonly ITypedCache<ConfigurationInformationDto> _configurationInformationDtoTypedCache;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly IRepository<DsTelCall> _dsTelCallRepository;
        private readonly IInitPushDataService _initPushDataService;
        private readonly FwClient _fwClient;
        private readonly IRepository<DsSendTaskSubmitCaseInfo> _sendTaskSubmitCaseInfoRepository;
        private readonly IRepository<DsSendTaskSubmitCaseRecord> _dsSendTaskSubmitCaseRecordRepository;
        private readonly IWaitSendTaskRepository _waitSendTaskRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="sendCaseInfoRepository"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="xieTongClient"></param>
        /// <param name="mapper"></param>
        /// <param name="getCaseDistrecordSendRepository"></param>
        /// <param name="capPublisher"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="getCaseMaterialInfoRepository"></param>
        /// <param name="configurationInformationDtoTypedCache"></param>
        /// <param name="dsOrderRepository"></param>
        /// <param name="dsTelCallRepository"></param>
        /// <param name="initPushDataService"></param>
        /// <param name="fwClient"></param>
        /// <param name="sendTaskSubmitCaseInfoRepository"></param>
        /// <param name="dsSendTaskSubmitCaseRecordRepository"></param>
        /// <param name="waitSendTaskRepository"></param>
        public TaskSchedulerController(ILogger<TaskSchedulerController> logger,
            IRepository<DsSendCaseInfo> sendCaseInfoRepository,
            IChannelConfigurationManager channelConfigurationManager,
            XieTongClient xieTongClient,
            IMapper mapper,
            IRepository<DsGetCaseDistrecordSend> getCaseDistrecordSendRepository,
            ICapPublisher capPublisher,
            ISharingConfigurationManager sharingConfigurationManager,
            IRepository<DsGetCaseMaterialInfo> getCaseMaterialInfoRepository,
            ITypedCache<ConfigurationInformationDto> configurationInformationDtoTypedCache,
            IRepository<DsOrder> dsOrderRepository,
            IRepository<DsTelCall> dsTelCallRepository,
            IInitPushDataService initPushDataService,
            FwClient fwClient,
            IRepository<DsSendTaskSubmitCaseInfo> sendTaskSubmitCaseInfoRepository,
             IRepository<DsSendTaskSubmitCaseRecord> dsSendTaskSubmitCaseRecordRepository,
              IWaitSendTaskRepository waitSendTaskRepository
            )
        {
            _logger = logger;
            _sendCaseInfoRepository = sendCaseInfoRepository;
            _channelConfigurationManager = channelConfigurationManager;
            _xieTongClient = xieTongClient;
            _mapper = mapper;
            _getCaseDistrecordSendRepository = getCaseDistrecordSendRepository;
            _capPublisher = capPublisher;
            _sharingConfigurationManager = sharingConfigurationManager;
            _getCaseMaterialInfoRepository = getCaseMaterialInfoRepository;
            _configurationInformationDtoTypedCache = configurationInformationDtoTypedCache;
            _dsOrderRepository = dsOrderRepository;
            _dsTelCallRepository = dsTelCallRepository;
            _initPushDataService = initPushDataService;
            _fwClient = fwClient;
            _sendTaskSubmitCaseInfoRepository = sendTaskSubmitCaseInfoRepository;
            _dsSendTaskSubmitCaseRecordRepository = dsSendTaskSubmitCaseRecordRepository;
            _waitSendTaskRepository = waitSendTaskRepository;
        }
        #endregion

        /// <summary>
        /// 每2个小时定时拉取12315的过程数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("taskcasedistrecordjob")]
        [AllowAnonymous]
        public async Task TaskCaseDistrecordJob()
        {
            _logger.LogInformation($"每2个小时定时拉取12315的过程数据进来了时间是{DateTime.Now}");
            return;
            #region 定时拉取12315的数据
            ////定时拉取12315的数据
            //var listSendCaseInfo = await _sendCaseInfoRepository
            //        .Queryable()
            //        .Where(p => p.IsEnd == false && p.State == "0")
            //        .OrderBy(p => p.CreationTime)
            //        .ToListAsync();
            //List<DsSendCaseInfo> dsData = [];

            //if (listSendCaseInfo != null && listSendCaseInfo.Count > 0)
            //{
            //    foreach (var item in listSendCaseInfo)
            //    {
            //        //状态更改为推送中
            //        item.State = "1";
            //        //使用乐观锁，控制数据
            //        if (await _sendCaseInfoRepository.Updateable(item).ExecuteCommandWithOptLockAsync() > 0)
            //        {
            //            dsData.Add(item);
            //        }
            //    }
            //}

            //_logger.LogInformation($"定时拉取12315数据获取条数：-------------" + dsData.Count);

            ////处理数据
            //if (dsData != null && dsData.Count > 0)
            //{
            //    foreach (var itemData in dsData)
            //    {
            //        GetCaseDistrecordSendInfo distrecordSendInfo = new() { CaseSerial = itemData.CaseSerial };

            //        #region 处理请求参数
            //        var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            //        var request = new ProvinceRequest<GetCaseDistrecordSendInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
            //        request.SetData(distrecordSendInfo);
            //        var jsonData = request.ToString();

            //        var baseAddress = configProvince.XieTong;
            //        if (!baseAddress.EndsWith('/'))
            //            baseAddress += "/";

            //        var url = baseAddress + "market/get_case_distrecord_send";
            //        #endregion
            //        _logger.LogInformation("工单：{itemData.CaseSerial}，定时拉取12315请求参数--------------------------------------" + jsonData);
            //        var response = await _xieTongClient.RequestAsync<ProvinceDistrecordResponse>(url, "Post", jsonData, HttpContext.RequestAborted);

            //        _logger.LogInformation($"工单：{itemData.CaseSerial}，请求的结果：-------------" + System.Text.Json.JsonSerializer.Serialize(response));

            //        if (response is null || response.status is null || response.custom is null)
            //        {
            //            itemData.State = "0";
            //            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //            continue;
            //        }

            //        //如果没有成功，修改为待读取
            //        if (response.status.code != "1")
            //        {
            //            itemData.State = "0";
            //            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //            continue;
            //        }


            //        //这里处理业务
            //        if (response.custom.STEP_List != null && response.custom.STEP_List.Count > 0)
            //        {
            //            //这里调用业务接口，推送办理数据
            //            List<SharingWorkflowTraceDto> Traces = [];
            //            //遍历返回的数据
            //            foreach (var item in response.custom.STEP_List)
            //            {
            //                //检测当前数据是否存在，如果存在不处理，不存在新增到数据库并推送到业务系统
            //                if (!await _getCaseDistrecordSendRepository.AnyAsync(p => p.CaseSerial == response.custom.CASE_SERIAL && p.RowGuid == item.RowGuid, HttpContext.RequestAborted))
            //                {
            //                    var tempData = _mapper.Map<DsGetCaseDistrecordSend>(item);
            //                    tempData.CaseSerial = response.custom.CASE_SERIAL;
            //                    tempData.AreaCode = _sharingConfigurationManager.GetCityCode();
            //                    await _getCaseDistrecordSendRepository.AddAsync(tempData);

            //                    #region 宜宾正常流程推送
            //                    //宜宾正常流程推送
            //                    if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
            //                    {
            //                        Traces.Add(new()
            //                        {
            //                            HandlerName = item.OperatorName,
            //                            HandlerOrgName = item.OperatorouName,
            //                            HandleTime = string.IsNullOrEmpty(item.HandleTime) == true ? null : Convert.ToDateTime(item.HandleTime),
            //                            Opinion = item.HandleOpinion
            //                        });
            //                    }
            //                    #endregion

            //                    #region 自贡只要有返回直接归档
            //                    //自贡只要有返回直接归档
            //                    if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.ZiGong)
            //                    {
            //                        if (item.OperateStatus == "市场监管局反馈" || item.OperateStatus == "市场监管局不立案")
            //                        {
            //                            var listFiles = await GetFileData(item.CliengGuid, response.custom.CASE_SERIAL, "办理上传");
            //                            OrderResultDto orderResult = new()
            //                            {
            //                                OrderId = itemData.OrderID,
            //                                FinishType = "1",
            //                                Opinion = item.HandleOpinion,
            //                                Files = listFiles,
            //                                Source = "province"
            //                            };
            //                            //向业务系统推送消息
            //                            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResult, cancellationToken: HttpContext.RequestAborted);
            //                            //修改为工单已经办结
            //                            itemData.IsEnd = true;
            //                            itemData.State = "1";
            //                            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //                        }
            //                    }
            //                    #endregion

            //                    #region 广元、泸州、自贡 根据查询明细办结工单
            //                    //广元、泸州、自贡 根据查询明细办结工单
            //                    if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.GuangYuan
            //                        || _sharingConfigurationManager.GetCityCode() == ConfigurationConsts.LuZhou
            //                        || _sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YaAn)
            //                    {
            //                        var listFiles = await GetFileData(item.CliengGuid, response.custom.CASE_SERIAL, "办理上传");
            //                        OrderResultDto orderResult = new()
            //                        {
            //                            OrderId = itemData.OrderID,
            //                            Opinion = item.HandleOpinion,
            //                            Files = listFiles,
            //                            Source = "province"
            //                        };
            //                        if (item.OperateStatus == "市场监管局反馈")
            //                        {
            //                            orderResult.FinishType = "1";
            //                        }
            //                        else if (item.OperateStatus == "市场监管局不立案")
            //                        {
            //                            orderResult.FinishType = "0";
            //                        }
            //                        if (item.OperateStatus == "市场监管局反馈" || item.OperateStatus == "市场监管局不立案")
            //                        {
            //                            //向业务系统推送消息
            //                            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResult, cancellationToken: HttpContext.RequestAborted);
            //                            //修改为工单已经办结
            //                            itemData.IsEnd = true;
            //                            itemData.State = "1";
            //                            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //                        }
            //                    }
            //                    #endregion

            //                }
            //            }
            //            #region 宜宾推送办理明细数据   取消推送办理明细，明细直接查询ds服务
            //            //宜宾推送办理明细数据   
            //            if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
            //            {
            //                if (Traces != null && Traces.Count > 0)
            //                {
            //                    SharingAddOrderTracesDto addOrderTracesDto = new()
            //                    {
            //                        OrderId = itemData.OrderID,
            //                        Traces = Traces
            //                    };
            //                    //往业务系统推送数据
            //                    // await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderAddTraces, addOrderTracesDto, cancellationToken: HttpContext.RequestAborted);
            //                }
            //                itemData.State = "0";
            //                await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //            }
            //            #endregion
            //        }

            //        if (itemData.IsEnd == false)
            //        {
            //            itemData.State = "0";
            //            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //        }

            //        Thread.Sleep(2000);
            //    }
            //}

            #endregion
        }

        /// <summary>
        /// 2小时上传实时服务上报
        /// </summary>
        /// <returns></returns>
        [HttpPost("tasksendrealtimestatusjob")]
        [AllowAnonymous]
        public async Task TaskSendRealTimeStatusJob()
        {
            _logger.LogInformation($"2小时上传实时服务上报进来了时间是{DateTime.Now}");
            #region 2小时上传实时服务上报
            //实时服务信息
            SendRealTimeStatusInfo dto = new()
            {
                AreaCode = _sharingConfigurationManager.GetCityCode(),
                AreaName = _sharingConfigurationManager.GetCityName()
            };

            //获取系统配置的数据
            var configurationInformation = await _configurationInformationDtoTypedCache.GetAsync(ConstantSettings.ConfigurationInformationCacheKey, HttpContext.RequestAborted);
            if (configurationInformation != null)
            {
                dto.CrntSeatNum = configurationInformation.CrntSeatNum;
                dto.CrntTelNum = configurationInformation.CrntTelNum;
            }

            #region 数据查询
            //数据查询
            var list = await _dsOrderRepository.Queryable()
                .Where(p => p.CaseDate >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))
                .Where(p => p.CaseDate <= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")))
                .Select(it => new
                {
                    it.CaseSourceCode
                })
                 //.MergeTable()//将查询出来的结果合并成一个新表
                 // .GroupBy(it => new { it.CaseSourceCode })//对新表进行分组
                 .Select(it => new SendRealTimeStatusInfo
                 {
                     TdyNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode != "", 1, 0)),
                     TdyTelNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode == "RGDH", 1, 0)),
                     TdyZwNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode == "SCZWFWW", 1, 0)),
                     TdyWzNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode == "YTW" || it.CaseSourceCode == "WZ", 1, 0)),
                     TdyWxNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode == "WX", 1, 0)),
                     TdyApNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode == "AP", 1, 0)),
                     TdyOtNum = SqlFunc.AggregateSum(SqlFunc.IIF(it.CaseSourceCode != "RGDH" && it.CaseSourceCode != "SCZWFWW"
                     && it.CaseSourceCode != "YTW" && it.CaseSourceCode != "WZ" && it.CaseSourceCode != "WX" && it.CaseSourceCode != "AP", 1, 0)),
                 })
                 .ToListAsync();
            if (list != null && list.Count > 0)
            {
                dto.TdyNum = list.Sum(x => x.TdyNum);
                dto.TdyTelNum = list.Sum(x => x.TdyTelNum);
                dto.TdyZwNum = list.Sum(x => x.TdyZwNum);
                dto.TdyWzNum = list.Sum(x => x.TdyWzNum);
                dto.TdyWxNum = list.Sum(x => x.TdyWxNum);
                dto.TdyApNum = list.Sum(x => x.TdyApNum);
                dto.TdyOtNum = list.Sum(x => x.TdyOtNum);
            }
            #endregion

            #region 计算今日接通率
            //计算今日接通率
            ///电话
            var callRate = await _dsTelCallRepository.Queryable()
              .Where(p => p.OverTime >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")) && p.OverTime <= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")))
               .Select(p => new TelCallInfoDto
               {
                   CountNum = SqlFunc.AggregateSum(SqlFunc.IIF(p.CallId != null, 1, 0)),//总数
                   ConnectNum = SqlFunc.AggregateSum(SqlFunc.IIF(p.OnState == "1", 1, 0)),//接通
               })
               .ToListAsync();
            if (callRate != null && callRate.Count > 0)
            {
                var data = callRate[0];
                dto.TdyTelRate = data.ConnectionRate;
            }
            #endregion


            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<SendRealTimeStatusInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(dto);
            var jsonData = request.ToString();
            var url = configProvince.HuiJu + "sendrealtimestatus";
            #endregion

            //组装参数
            await _initPushDataService.InitDsSendTaskProvinceOther("SendRealTimeStatus", "sendrealtimestatus", "", jsonData,
                JsonSerializer.Serialize(dto, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions),
                pathType: EPathType.HuiJu, cancellationToken: HttpContext.RequestAborted);
            #endregion

        }

        /// <summary>
        /// 每天凌晨1点推送业务汇聚-统计数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("tasksubmitcasetotaljob")]
        [AllowAnonymous]
        public async Task TaskSubmitCaseTotalJob()
        {
            _logger.LogInformation($"每天凌晨1点推送业务汇聚-统计数据进来了时间是{DateTime.Now}");
            var data = await _fwClient.RequestNoTokenAsync<SubmitCaseTotalnfoResponse>("api/v1/Order/get-orderurge-count", "Get", null);
            SubmitCaseTotalInfo submitCaseTotal = new()
            {
                AreaCode = _sharingConfigurationManager.GetCityCode(),
                SubmitDate = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00"))
            };
            if (data != null && data.code == 0)
            {
                submitCaseTotal.CBZL = data.result.Totle;
            }
            var configurationInformation = await _configurationInformationDtoTypedCache.GetAsync(ConstantSettings.ConfigurationInformationCacheKey, HttpContext.RequestAborted);
            if (configurationInformation != null)
            {
                submitCaseTotal.SeatNum = configurationInformation.SeatNum;
                submitCaseTotal.SeatHwyNum = configurationInformation.SeatHwyNum;
            }
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseTotalInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseTotalInfo>() { submitCaseTotal });
            var jsonData = request.ToString();

            #endregion

            //组装参数
            await _initPushDataService.InitDsSendTaskProvinceOther("SubmitCaseTotal", "submit_case_total", "", jsonData,
                JsonSerializer.Serialize(submitCaseTotal, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions),
                pathType: EPathType.HuiJu, cancellationToken: HttpContext.RequestAborted);
        }

        /// <summary>
        /// 每天晚上23点处理每天办理完成未及时推送办理结果的数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("taskrepublishfiledordersjob")]
        [AllowAnonymous]
        public async Task TaskRepublishFiledOrdersJob()
        {
            _logger.LogInformation($"每天晚上23点处理每天办理完成未及时推送办理结果的数据进来了时间是{DateTime.Now}");
            //查询推送了受理信息，没有推送工单结果的数据
            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: HttpContext.RequestAborted);
                }
                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: HttpContext.RequestAborted);

                        Thread.Sleep(2000);
                    }
                }
            }
        }

        /// <summary>
        /// 每天晚上23点处理未关联工单的通话记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("taskassociatecallrecordsjob")]
        [AllowAnonymous]
        public async Task TaskAssociateCallRecordsJob()
        {
            _logger.LogInformation($"每天晚上23点处理未关联工单的通话记录数据进来了时间是{DateTime.Now}");
            if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
                return;

            var items = await _dsSendTaskSubmitCaseRecordRepository.Queryable()
                    .Where(p => 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: HttpContext.RequestAborted);
                }
                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: HttpContext.RequestAborted);

                        Thread.Sleep(2000);
                    }

                }
            }

        }

        /// <summary>
        /// 每天晚上23点50处理未查询到通话记录的工单，修改为其他来源
        /// </summary>
        /// <returns></returns>
        [HttpPost("taskgetordermatchingcalllistjob")]
        [AllowAnonymous]
        public async Task TaskGetOrderMatchingCallListJob()
        {
            _logger.LogInformation($"每天晚上23点50处理未查询到通话记录的工单数据进来了时间是{DateTime.Now}");
            DateTime startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
            DateTime endTime = DateTime.Now;

            //string strSql = @"SELECT ""ProvinceNo"" FROM( SELECT ""SCO"".""ProvinceNo"",""FirstTime"",  ""LastTime"",""SendTimes"", ""GenerationTime"",""CreationTime"",""RequestData"",""ExpiredTime"", ""CaseSource"",""OrderId""
            //        FROM(
            //        SELECT *  FROM 
            //        (
            //        SELECT ROW_NUMBER() OVER(PARTITION BY ""ProvinceNo"" ORDER BY ""CreationTime"" DESC)  AS ""newIndex"",""ProvinceNo"",""FirstTime"",""OrderId"",
            //        ""LastTime"",""SendTimes"",""GenerationTime""AS ""GenerationTime"",""CreationTime"",""RequestData"",""ExpiredTime"",""CaseSource"" AS ""CaseSource""
            //        FROM ""ds_send_task_submit_case_info"" 
            //         where  ""GenerationTime"" >= '{0}'  AND  ""GenerationTime"" <= '{1}'     AND  ""LastTime"" >= '{0}'  AND  ""LastTime"" <= '{1}' AND  ""IsSuccess"" = 1 
            //        ) ""SCI"" WHERE ""newIndex""=1  	AND  ""CaseSource"" =  'RGDH' 
            //        ) ""SCO""
            //         LEFT JOIN 
            //        (
            //        SELECT * FROM (
            //        SELECT ROW_NUMBER() OVER(PARTITION BY ""CallId"" ORDER BY ""CreationTime"" DESC) as ""newIndex"",""ProvinceNo"",""CallId"",""CallLogId""
            //        FROM  ""ds_send_task_submit_case_record"" 
            //   WHERE   ""GenerationTime"" >= '{0}'   AND  ""LastTime"" >= '{0}'  AND  ""IsSuccess"" = 1 AND ""CallDirection""='0'
            //            ) ""SCR"" WHERE ""newIndex""=1 and (""ProvinceNo""  IS NOT NULL or ""ProvinceNo""  !='') 
            //        )""SCRC""
            //        ON ""SCO"".""ProvinceNo""=""SCRC"".""ProvinceNo""  WHERE  ""SCRC"".""ProvinceNo""  IS NULL   
            //          )""te"" ";
            string strSql = @"select provinceno ""ProvinceNo"",firsttime""FirstTime"",  lasttime""LastTime"",generationtime""GenerationTime"",
                    creationtime""CreationTime"",requestdata""RequestData"",
                    casesource""CaseSource"",orderid""OrderId"" FROM 
                    get_order_matching_call_list('{0}','{1}')";
            strSql = string.Format(strSql, startTime, endTime);

            var list = await _waitSendTaskRepository.GetDataBySql(strSql).ToListAsync();

            List<string> items = [];

            if (list != null && list.Any())
            {
                items = list.Select(p => p.ProvinceNo).ToList();

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

                            Thread.Sleep(2000);
                        }

                    }
                }
            }
        }

        #region 根据附件Id,工单编号查询所有附件
        /// <summary>
        ///  根据附件Id,工单编号查询所有附件
        /// </summary>
        /// <param name="CliengGuid">材料标识ID</param>
        /// <param name="CaseSerial">工单编号</param>
        /// <param name="Classify">材料分类</param>
        /// <returns></returns>
        private async Task<List<FileDto>> GetFileData(string CliengGuid, string CaseSerial, string Classify)
        {
            var list = await _getCaseMaterialInfoRepository.Queryable().Where(p => p.CliengGuid == CliengGuid && p.CaseSerial == CaseSerial).ToListAsync();

            List<FileDto> fileDtos = new();
            if (fileDtos == null || fileDtos.Count == 0)
                return fileDtos;
            foreach (var item in list)
            {
                fileDtos.Add(new FileDto()
                {
                    Name = item.FileName,
                    Type = item.Type,
                    Classify = Classify,
                    Additions = item.Additions,
                    Path = item.Path
                });
            }
            return fileDtos;
        }

        #endregion
    }
}
