using DataSharing.Province;
using DataSharing.Province.SendTask.SubmitCaseInfo;
using DataSharing.Province.SendTask.SubmitCaseRecord;
using DataSharing.Province.SendTask.SubmitCaseResult;
using DataSharing.Share.Dtos.Province;
using DataSharing.Share.Dtos.Province.XieTong;
using DataSharing.Share.Dtos.Province.XieTong.Receive;
using DataSharing.Share.Requests;
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 Quartz;
using SqlSugar;
using XF.Domain.Repository;

namespace DataSharing.Host.Controllers
{
    /// <summary>
    /// 处理数据
    /// </summary>
    public class ProcessingDataController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly ILogger<ProcessingDataController> _logger;
        private readonly IRepository<DsSendTaskSubmitCaseInfo> _sendTaskSubmitCaseInfoRepository;
        private readonly ICapPublisher _capPublisher;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IRepository<DsSendTaskSubmitCaseRecord> _dsSendTaskSubmitCaseRecordRepository;
        private readonly IRepository<DsSendCaseInfo> _sendCaseInfoRepository;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly XieTongClient _xieTongClient;
        private readonly IRepository<DsGetCaseDistrecordSend> _getCaseDistrecordSendRepository;
        private readonly IRepository<DsGetCaseMaterialInfo> _getCaseMaterialInfoRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="sendTaskSubmitCaseInfoRepository"></param>
        /// <param name="capPublisher"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="dsSendTaskSubmitCaseRecordRepository"></param>
        /// <param name="sendCaseInfoRepository"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="xieTongClient"></param>
        /// <param name="getCaseDistrecordSendRepository"></param>
        /// <param name="getCaseMaterialInfoRepository"></param>
        public ProcessingDataController(IMapper mapper,
            ILogger<ProcessingDataController> logger,
            IRepository<DsSendTaskSubmitCaseInfo> sendTaskSubmitCaseInfoRepository,
            ICapPublisher capPublisher,
            ISharingConfigurationManager sharingConfigurationManager,
             IRepository<DsSendTaskSubmitCaseRecord> dsSendTaskSubmitCaseRecordRepository,
             IRepository<DsSendCaseInfo> sendCaseInfoRepository,
             IChannelConfigurationManager channelConfigurationManager,
             XieTongClient xieTongClient,
             IRepository<DsGetCaseDistrecordSend> getCaseDistrecordSendRepository,
             IRepository<DsGetCaseMaterialInfo> getCaseMaterialInfoRepository)
        {
            _mapper = mapper;
            _logger = logger;
            _sendTaskSubmitCaseInfoRepository = sendTaskSubmitCaseInfoRepository;
            _capPublisher = capPublisher;
            _sharingConfigurationManager = sharingConfigurationManager;
            _dsSendTaskSubmitCaseRecordRepository = dsSendTaskSubmitCaseRecordRepository;
            _sendCaseInfoRepository = sendCaseInfoRepository;
            _channelConfigurationManager = channelConfigurationManager;
            _xieTongClient = xieTongClient;
            _getCaseDistrecordSendRepository = getCaseDistrecordSendRepository;
            _getCaseMaterialInfoRepository = getCaseMaterialInfoRepository;
        }

        /// <summary>
        /// 处理每天办理完成未及时推送办理结果的数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotlinefiledordersrepublish")]
        [AllowAnonymous]
        public async Task HotlineFiledOrdersRepublish([FromQuery] ReportPagedRequest dto)
        {
            //查询推送了受理信息，没有推送工单结果的数据
            var items = await _sendTaskSubmitCaseInfoRepository.Queryable()
                  .Where(p => p.FirstTime >= Convert.ToDateTime("2024-08-01"))
                  .WhereIF(dto.StartTime.HasValue, p => p.FirstTime >= dto.StartTime)
                  .WhereIF(dto.EndTime.HasValue, p => p.FirstTime <= dto.EndTime)
                  .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>
        ///  查询未关联工单的通话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("recunrelationcalls")]
        [AllowAnonymous]
        public async Task RecUnrelationCalls([FromQuery] ReportPagedRequest dto)
        {
            if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
                return;

            var items = await _dsSendTaskSubmitCaseRecordRepository.Queryable()
                   .WhereIF(dto.StartTime.HasValue, p => p.CreationTime >= dto.StartTime)
                   .WhereIF(dto.EndTime.HasValue, p => p.CreationTime <= dto.EndTime)
                   .Where(p => p.CreationTime >= Convert.ToDateTime("2024-10-26 00:00:00")
                    && 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.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>
        /// 定时拉取12315的数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("getcasedistrecord")]
        public async Task GetCaseDistrecord([FromQuery] ReportPagedRequest dto)
        {
            #region 定时拉取12315的数据
            //定时拉取12315的数据
            var listSendCaseInfo = await _sendCaseInfoRepository
                    .Queryable()
                    .Where(p => p.IsEnd == false && p.State == "0")
                    .WhereIF(dto.StartTime.HasValue, p => p.CreationTime >= dto.StartTime)
                    .WhereIF(dto.EndTime.HasValue, p => p.CreationTime <= dto.EndTime)
                    .WhereIF(string.IsNullOrEmpty(dto.Keyword) == false, p => p.No == dto.Keyword)
                    .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.No,
                                        Opinion = item.HandleOpinion,
                                        Files = listFiles,
                                        Source = "province"
                                    };
                                    if (item.OperateStatus == "市场监管局反馈")
                                    {
                                        orderResult.FinishType = "1";
                                    }
                                    else if (item.OperateStatus == "市场监管局不立案")
                                    {
                                        orderResult.FinishType = "0";
                                    }
                                    //向业务系统推送消息
                                    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.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
          _logger.LogInformation($"进来了时间是{DateTime.Now}");
        }

        /// <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;
        }


    }
}
