using DataSharing.FwDataExchange;
using DataSharing.RawData;
using DataSharing.SendTask;
using DataSharing.SendTask.OtherPlatforms;
using DataSharing.Share.Dtos.ZiGong.TianQue;
using DataSharing.Share.Enums;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Microsoft.Extensions.Logging;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace DataSharing.TianQue
{
    public class TianQuePusherProviderService : ITianQuePusherProviderService, IScopeDependency
    {
        private readonly ILogger<TianQuePusherProviderService> _logger;
        private readonly IRepository<DsUserTokenInfo> _dsUserTokenInfoRepository;
        private readonly IRepository<DsWaitSendTaskOtherPlatforms> _waitSendTaskOtherPlatformsRepository;
        private readonly IRepository<DsSendTaskDetailInfo> _dsSendTaskDetailInfoRepository;
        private readonly IRepository<DsSendTaskOtherPlatforms> _sendTaskOtherPlatformsRepository;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly FwClient _fwClient;
        private readonly ICapPublisher _capPublisher;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="dsUserTokenInfoRepository"></param>
        /// <param name="waitSendTaskOtherPlatformsRepository"></param>
        /// <param name="dsSendTaskDetailInfoRepository"></param>
        /// <param name="sendTaskOtherPlatformsRepository"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="fwClient"></param>
        /// <param name="capPublisher"></param>
        public TianQuePusherProviderService(ILogger<TianQuePusherProviderService> logger,
            IRepository<DsUserTokenInfo> dsUserTokenInfoRepository,
            IRepository<DsWaitSendTaskOtherPlatforms> waitSendTaskOtherPlatformsRepository,
            IRepository<DsSendTaskDetailInfo> dsSendTaskDetailInfoRepository,
            IRepository<DsSendTaskOtherPlatforms> sendTaskOtherPlatformsRepository,
            IChannelConfigurationManager channelConfigurationManager,
            FwClient fwClient,
            ICapPublisher capPublisher)
        {
            _logger = logger;
            _dsUserTokenInfoRepository = dsUserTokenInfoRepository;
            _waitSendTaskOtherPlatformsRepository = waitSendTaskOtherPlatformsRepository;
            _dsSendTaskDetailInfoRepository = dsSendTaskDetailInfoRepository;
            _sendTaskOtherPlatformsRepository = sendTaskOtherPlatformsRepository;
            _channelConfigurationManager = channelConfigurationManager;
            _fwClient = fwClient;
            _capPublisher = capPublisher;
        }

        /// <summary>
        /// 随手拍推送工单数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendDataPusher(DsWaitSendTaskOtherPlatforms dto, CancellationToken cancellationToken)
        {
            if (dto is null || string.IsNullOrEmpty(dto.Request))
                return;

            var userInfo = await _dsUserTokenInfoRepository.GetAsync(p => p.PlatformSource == EPlatformSource.TianQue.ToString(), cancellationToken);
            if (userInfo is null || string.IsNullOrEmpty(userInfo.AddressUrl))
                return;

            var baseAddress = userInfo.AddressUrl;
            if (!baseAddress.EndsWith('/'))
                baseAddress += "/";

            TianQueReceiverResponse result = new();
            string error = "";
            _logger.LogInformation("随手拍天阙请求参数------------------" + dto.Request);
            try
            {
                result = await _fwClient.RequestNoTokenOtherAsync<TianQueReceiverResponse>(baseAddress, baseAddress + dto.Path, "POST", dto.Request, cancellationToken);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            _logger.LogInformation("随手拍天阙返回参数------------------" + System.Text.RegularExpressions.Regex.Unescape(System.Text.Json.JsonSerializer.Serialize(result)));

            //写入推送明细表
            DsSendTaskDetailInfo dsSendTaskInfo = new()
            {
                TaskId = dto.Id,
                Result = System.Text.RegularExpressions.Regex.Unescape(System.Text.Json.JsonSerializer.Serialize(result)),
                ResultErrorData = error,
                ProcessingServices = _channelConfigurationManager.GetConfigurationProcessingServices()
            };
            if (result is not null)
            {
                #region 处理待同步表数据
                //移除待同步表数据
                if (result.success == true && result.code == 200)
                {
                    dsSendTaskInfo.IsSuccess = true;
                    await _waitSendTaskOtherPlatformsRepository.RemoveAsync(dto, cancellationToken: cancellationToken);
                }
                else
                {
                    dto.LastTime = DateTime.Now;
                    dto.SendTimes = dto.SendTimes + 1;

                    if (dto.FirstTime is null)
                        dto.FirstTime = DateTime.Now;

                    if (dto.SendTimes >= 7)
                        dto.State = EWaitSendTaskState.PushFail;
                    else
                        dto.State = EWaitSendTaskState.WaitPush;

                    await _waitSendTaskOtherPlatformsRepository.UpdateAsync(dto, cancellationToken);
                }
                #endregion

                #region 处理推送主表数据
                //处理推送主表数据
                var data = await _sendTaskOtherPlatformsRepository.GetAsync(p => p.Id == dto.Id, cancellationToken);
                if (data != null)
                {
                    data.LastTime = DateTime.Now;
                    data.SendTimes = data.SendTimes + 1;

                    if (data.FirstTime is null)
                        data.FirstTime = DateTime.Now;
                    if (result.success == true && result.code == 200)
                        data.IsSuccess = ESendTaskState.PushSuccess;
                    else
                        data.IsSuccess = ESendTaskState.PushFail;
                    await _sendTaskOtherPlatformsRepository.UpdateAsync(data, cancellationToken);
                }
                #endregion

                //收到天阙返回，推送
                if (result.success == true && result.code == 200 && result.data != null && !string.IsNullOrEmpty(result.data.appealNumber))
                {
                    TianQuePushOrderReceiverDto tianQuePush = new TianQuePushOrderReceiverDto()
                    {
                        OrderNo = dto.ProvinceNo,
                        AppealNumber = result.data.appealNumber,
                        OrgId = result.data.orgId
                    };

                    //推业务系统
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.TianQuePushOrderReceiver, tianQuePush, cancellationToken: cancellationToken);
                }

            }
            await _dsSendTaskDetailInfoRepository.AddAsync(dsSendTaskInfo, cancellationToken);
        }

    }
}
