using DataSharing.SendTask;
using DataSharing.Share.Dtos.LuZhou;
using DataSharing.Share.Enums;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using XF.Domain.Repository;
using static Lucene.Net.Util.Fst.Util;

namespace DataSharing.LuZhou.LuZhou110
{
    public class TaskSendTaskLuZhou110Job : IJob, IDisposable
    {
        private readonly IMapper _mapper;
        private readonly ILogger<TaskOtherPlatformsJob> _logger;
        private readonly IRepository<SendTaskLuzhou110> _sendTaskLuZhou110Repository;
        private readonly IRepository<WaitSendTaskLuzhou110> _waitSendTaskLuZhou110Repository;
        private readonly LZ110Invoker _lz110Invoker;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IRepository<DsSendTaskDetailInfo> _sendTaskDetailInfoRepository;
        private readonly ILZ110RegisterManager _registerManager;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="sendTaskLuZhou110Repository"></param>
        /// <param name="waitSendTaskLuZhou110Repository"></param>
        /// <param name="lz110Invoker"></param>
        public TaskSendTaskLuZhou110Job(IMapper mapper,
            ILogger<TaskOtherPlatformsJob> logger,
            IRepository<SendTaskLuzhou110> sendTaskLuZhou110Repository,
            IRepository<WaitSendTaskLuzhou110> waitSendTaskLuZhou110Repository,
            LZ110Invoker lz110Invoker,
            ISharingConfigurationManager sharingConfigurationManager,
            IRepository<DsSendTaskDetailInfo> sendTaskDetailInfoRepository,
            ILZ110RegisterManager registerManager)
        {
            _mapper = mapper;
            _logger = logger;
            _sendTaskLuZhou110Repository = sendTaskLuZhou110Repository;
            _waitSendTaskLuZhou110Repository = waitSendTaskLuZhou110Repository;
            _lz110Invoker = lz110Invoker;
            _sharingConfigurationManager = sharingConfigurationManager;
            _sendTaskDetailInfoRepository = sendTaskDetailInfoRepository;
            _registerManager = registerManager;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            if (_sharingConfigurationManager.GetCityCode() != ConfigurationConsts.LuZhou)
                return;

            var tasks = await _waitSendTaskLuZhou110Repository.Queryable()
              .Where(d => d.State == EWaitSendTaskState.WaitPush && d.SendTimes <= 3)
               .OrderBy(d => d.CreationTime)
               .Take(10)
               .ToListAsync(context.CancellationToken);

            _logger.LogInformation("泸州110平台读取数据条数--------------------------------------" + tasks.Count);

            if (tasks.Count != 0)
            {
                List<WaitSendTaskLuzhou110> list = new List<WaitSendTaskLuzhou110>();
                //处理推送数据
                foreach (var sendTask in tasks)
                {
                    //状态更改为推送中
                    sendTask.State = EWaitSendTaskState.Pushing;
                    //使用乐观锁，控制数据
                    if (await _waitSendTaskLuZhou110Repository.Updateable(sendTask).ExecuteCommandWithOptLockAsync() > 0)
                    {
                        list.Add(sendTask);
                    }
                }
                _logger.LogInformation("泸州110平台锁定条数--------------------------------------" + list.Count);

                //执行推送
                if (list != null && list.Count > 0)
                {
                    await SendData(list, context.CancellationToken);
                }
            }
        }

        /// <summary>
        /// 推送数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task SendData(List<WaitSendTaskLuzhou110> list, CancellationToken cancellationToken)
        {
            var url = _sharingConfigurationManager.GetLuZhouConfig().LuZhou110.SendDataAddress;
            foreach (var item in list)
            {
                string error = "";
                LZ110ApiResponse<LZ110BaseResponse> response = new();
                try
                {
                    response = await _lz110Invoker.RequestStringContentAsync<LZ110BaseResponse>(item.Path, item.Request, cancellationToken);
                    if (!response.IsSuccess && response?.Data?.ResponseStatusObject.StatusCode == "1")// ==1：未注册，==4：已注册
                    {
                        await _registerManager.RefreshRegisterAsync(cancellationToken);
                        response = await _lz110Invoker.RequestStringContentAsync<LZ110BaseResponse>(item.Path, item.Request, cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"发起请求LZ110返回333333：{ex.Message}");
                    error = ex.Message;
                }

                //写入明细表
                DsSendTaskDetailInfo dsSendTaskInfo = new()
                {
                    TaskId = item.Id,
                    Result = System.Text.RegularExpressions.Regex.Unescape(System.Text.Json.JsonSerializer.Serialize(response)),
                    ResultErrorData = error,
                    ProcessingServices = ""
                };

                if (response is not null)
                {
                    #region 处理待同步表数据
                    //移除待同步表数据
                    if (response.IsSuccess)
                        await _waitSendTaskLuZhou110Repository.RemoveAsync(item, cancellationToken: cancellationToken);
                    else
                    {
                        //修改待同步表数据状态
                        item.LastTime = DateTime.Now;
                        item.SendTimes = item.SendTimes + 1;

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

                        if (item.SendTimes >= 3)
                            item.State = EWaitSendTaskState.PushFail;
                        else
                            item.State = EWaitSendTaskState.WaitPush;

                        await _waitSendTaskLuZhou110Repository.UpdateAsync(item, cancellationToken);
                    }
                    #endregion

                    #region 处理推送任务表
                    var sendTaskData = await _sendTaskLuZhou110Repository.GetAsync(p => p.Id == item.Id, cancellationToken);
                    if (sendTaskData != null)
                    {
                        //处理推送时间
                        sendTaskData.LastTime = DateTime.Now;
                        sendTaskData.SendTimes = sendTaskData.SendTimes + 1;

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

                        if (response.IsSuccess)
                        {
                            sendTaskData.IsSuccess = ESendTaskState.PushSuccess;
                            dsSendTaskInfo.IsSuccess = true;
                        }
                        else
                            sendTaskData.IsSuccess = ESendTaskState.PushFail;

                        await _sendTaskLuZhou110Repository.UpdateAsync(sendTaskData, cancellationToken);

                    }
                    #endregion
                }
                await _sendTaskDetailInfoRepository.AddAsync(dsSendTaskInfo, cancellationToken);
            }
        }

        public void Dispose()
        {

        }
    }
}
