using DataSharing.FwDataExchange;
using DataSharing.SendTask;
using DataSharing.SendTask.OtherPlatforms;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Enums;
using Microsoft.Extensions.Logging;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace DataSharing.ZiGong
{
    public class SmartCitySystemPusherProviderService : ISmartCitySystemPusherProviderService, IScopeDependency
    {
        private readonly ILogger<SmartCitySystemPusherProviderService> _logger;
        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 ISharingConfigurationManager _sharingConfigurationManager;

        /// <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 SmartCitySystemPusherProviderService(ILogger<SmartCitySystemPusherProviderService> logger,
            IRepository<DsWaitSendTaskOtherPlatforms> waitSendTaskOtherPlatformsRepository,
            IRepository<DsSendTaskDetailInfo> dsSendTaskDetailInfoRepository,
            IRepository<DsSendTaskOtherPlatforms> sendTaskOtherPlatformsRepository,
            IChannelConfigurationManager channelConfigurationManager,
            FwClient fwClient,
            ISharingConfigurationManager sharingConfigurationManager)
        {
            _logger = logger;
            _waitSendTaskOtherPlatformsRepository = waitSendTaskOtherPlatformsRepository;
            _dsSendTaskDetailInfoRepository = dsSendTaskDetailInfoRepository;
            _sendTaskOtherPlatformsRepository = sendTaskOtherPlatformsRepository;
            _channelConfigurationManager = channelConfigurationManager;
            _fwClient = fwClient;
            _sharingConfigurationManager = sharingConfigurationManager;
        }

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

            ConfigurationSmartCitySystem config = _sharingConfigurationManager.GetZiGongConfig().SmartCitySystem;

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

            HotlineClientResponse result = new();
            string error = "";
            _logger.LogInformation("智慧城市请求参数------------------" + dto.Request);
            try
            {
                result = await _fwClient.RequestNoTokenOtherAsync<HotlineClientResponse>(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.code == 0 && string.IsNullOrEmpty(error))
                {
                    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.code == 0 && string.IsNullOrEmpty(error))
                        data.IsSuccess = ESendTaskState.PushSuccess;
                    else
                        data.IsSuccess = ESendTaskState.PushFail;
                    await _sendTaskOtherPlatformsRepository.UpdateAsync(data, cancellationToken);
                }
                #endregion

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

    }
}
