using DataSharing.Share.Dtos.Province;
using DataSharing.Share.Dtos.Province.XieTong;
using DataSharing.Share.Dtos.Province.XieTong.Receive;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.File;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using Quartz;
using XF.Domain.Repository;

namespace DataSharing.Province.SendTask
{
    /// <summary>
    /// 定时拉取12315的过程数据
    /// </summary>
    public class TaskCaseDistrecordJob : IJob, IDisposable
    {
        private readonly ILogger<TaskCaseDistrecordJob> _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;

        /// <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>
        public TaskCaseDistrecordJob(ILogger<TaskCaseDistrecordJob> logger,
            IRepository<DsSendCaseInfo> sendCaseInfoRepository,
            IChannelConfigurationManager channelConfigurationManager,
            XieTongClient xieTongClient,
            IMapper mapper,
            IRepository<DsGetCaseDistrecordSend> getCaseDistrecordSendRepository,
            ICapPublisher capPublisher,
            ISharingConfigurationManager sharingConfigurationManager,
            IRepository<DsGetCaseMaterialInfo> getCaseMaterialInfoRepository)
        {
            _logger = logger;
            _sendCaseInfoRepository = sendCaseInfoRepository;
            _channelConfigurationManager = channelConfigurationManager;
            _xieTongClient = xieTongClient;
            _mapper = mapper;
            _getCaseDistrecordSendRepository = getCaseDistrecordSendRepository;
            _capPublisher = capPublisher;
            _sharingConfigurationManager = sharingConfigurationManager;
            _getCaseMaterialInfoRepository = getCaseMaterialInfoRepository;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            #region 定时拉取12315的数据
            Random random = new Random();
            int randomNumber = random.Next(0, 2); // 生成0到99之间的整数
            //定时拉取12315的数据
            var listSendCaseInfo = await _sendCaseInfoRepository
                    .Queryable()
                    .Where(p => p.IsEnd == false && p.State == "0")
                     //.OrderBy(p => p.CreationTime)
                     .OrderByIF(randomNumber == 0, d => d.CreationTime, SqlSugar.OrderByType.Asc)
                     .OrderByIF(randomNumber != 0, d => d.CreationTime, SqlSugar.OrderByType.Desc)
                    .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, context.CancellationToken);

                    _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: context.CancellationToken);
                        continue;
                    }

                    //如果没有成功，修改为待读取
                    if (response.status.code != "1")
                    {
                        itemData.State = "0";
                        await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: context.CancellationToken);
                        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, context.CancellationToken))
                            {
                                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: context.CancellationToken);
                                        //修改为工单已经办结
                                        itemData.IsEnd = true;
                                        itemData.State = "1";
                                        await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: context.CancellationToken);
                                    }
                                }
                                #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: context.CancellationToken);
                                        //修改为工单已经办结
                                        itemData.IsEnd = true;
                                        itemData.State = "1";
                                        await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: context.CancellationToken);
                                    }
                                }
                                #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: context.CancellationToken);
                        }
                        #endregion
                    }

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

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

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

        }

    }
}
