using DataSharing.RawData;
using DataSharing.SendTask;
using DataSharing.Share.Consts;
using DataSharing.Share.Dtos.HotlineWeb;
using DataSharing.Share.Dtos.Province.XieTong.Send;
using DataSharing.Share.Enums;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using Quartz;
using SqlSugar;
using System.Text.Json;
using XF.Domain.Cache;
using XF.Domain.Repository;

namespace DataSharing.Province.SendTask
{
    public class TaskSendRealTimeStatusJob : IJob, IDisposable
    {
        private readonly ILogger<TaskSendRealTimeStatusJob> _logger;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly IMapper _mapper;
        private readonly ITypedCache<ConfigurationInformationDto> _configurationInformationCache;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly IRepository<DsTelCall> _dsTelCallRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IInitPushDataService _initPushDataService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="mapper"></param>
        /// <param name="configurationInformationCache"></param>
        /// <param name="dsOrderRepository"></param>
        /// <param name="dsTelCallRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="initPushDataService"></param>
        public TaskSendRealTimeStatusJob(ILogger<TaskSendRealTimeStatusJob> logger,
            IChannelConfigurationManager channelConfigurationManager,
            IMapper mapper,
            ITypedCache<ConfigurationInformationDto> configurationInformationCache,
            IRepository<DsOrder> dsOrderRepository,
            IRepository<DsTelCall> dsTelCallRepository,
            ISharingConfigurationManager sharingConfigurationManager,
            IInitPushDataService initPushDataService)
        {
            _logger = logger;
            _channelConfigurationManager = channelConfigurationManager;
            _mapper = mapper;
            _configurationInformationCache = configurationInformationCache;
            _dsOrderRepository = dsOrderRepository;
            _dsTelCallRepository = dsTelCallRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
            _initPushDataService = initPushDataService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation($"进来了时间是{DateTime.Now}");
            //实时服务信息
            SendRealTimeStatusInfo dto = new()
            {
                AreaCode = _sharingConfigurationManager.GetCityCode(),
                AreaName = _sharingConfigurationManager.GetCityName()
            };

            //获取系统配置的数据
            var configurationInformation = await _configurationInformationCache.GetAsync(ConstantSettings.ConfigurationInformationCacheKey, context.CancellationToken);
            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: context.CancellationToken);

        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {

        }

    }
}
