using Dapper;
using IoC;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Data.Model.Standard.Tracking;
using XYY.Service.Standard.First.ESB;
using XYY.TaskTrack.Standard;
using XYY.TaskTrack.Standard.TaskModel;

namespace XYY.Service.Standard.First.JobSubscribe
{



    public interface ISendFirstNoteSubscribe : IBaseConsumer<Frist_Log>
    {

    }
    public class SendFirstNoteSubscribe : BaseConsumer<Frist_Log>, ISendFirstNoteSubscribe
    {
        private IUnitOfWork _unitOfWork;
        private ILogger<JobSubscribe> _jobLogger;

        public SendFirstNoteSubscribe(IMQManager mq, IUnitOfWork unitOfWork, ILogger<JobSubscribe> jobLogger) : base(mq)
        {
            _unitOfWork = unitOfWork;
            _jobLogger = jobLogger;
        }

        public override async Task Consume(Frist_Log log)
        {
            string time = null;
            var ft = (log.Groups.FirstOrDefault()?.List.FirstOrDefault()?.TriggerTime);
            if (ft.HasValue)
                time = ft.Value.ToString_yyyyMMddHHmmss();
            _jobLogger.LogWarning("接收到称重信息发送请求，" + log.Groups.Count + "条信息，第一条触发时间" + time);
            List<dynamic> firstTrackings = new List<dynamic>();
            if (log.Groups.Count > 0)
            {
                try
                {
                    XiKeApi xiKeApi = new XiKeApi();
                    var erros = await xiKeApi.Send(log.Groups);
                    if (erros.Count > 0)
                    {
                        erros = await xiKeApi.Send(erros);
                        if (erros.Count > 0)
                        {
                            erros = await xiKeApi.Send(erros);
                            if (erros.Count > 0)
                            {
                                await AddErrors(erros, "称重");
                            }
                        }
                    }
                    _jobLogger.LogWarning("处理称重信息发送请求结束,不过有" + erros.Count + "条失败了");
                }
                catch (Exception ex)
                {
                    _jobLogger.LogWarning("处理称重信息发送请求失败" + ex.Message);
                }
            }
        }



        public async Task AddErrors(List<XYY.Data.Model.Standard.Tracking.Logistics_TraceGroup> erros, string target)
        {
            if (erros.Count > 0)
            {
                Frist_Log log = new Frist_Log();
                log.Groups = erros;
                //持久化
                await _unitOfWork.InsertAsync<ErroJobLog>(new ErroJobLog
                {
                    ActionUrl = "http://120.24.149.148:9520/api/BatchTracking/TestSendLog",
                    IsExecute = false,
                    Request = Newtonsoft.Json.JsonConvert.SerializeObject(log),
                    Target = target,
                    CreateTime = DateTime.Now
                });
            }
        }
    }

    public interface ISendFirstSubscribe : IBaseConsumer<Job_Customer_FristLog>
    {

    }
    public class SendFirstSubscribe : BaseConsumer<Job_Customer_FristLog>, ISendFirstSubscribe
    {
        private IUnitOfWork _unitOfWork;
        private ILogger<JobSubscribe> _jobLogger;
        private IESBService ESBService;
        public SendFirstSubscribe(IMQManager mq, IUnitOfWork unitOfWork, ILogger<JobSubscribe> jobLogger, IESBService eSBService) : base(mq)
        {
            _unitOfWork = unitOfWork;
            _jobLogger = jobLogger;
            ESBService = eSBService;
        }
        public static void SendXiKeLogsApi(dynamic dynamic)
        {
            RestSharp.RestClient rc = new RestSharp.RestClient("http://120.24.149.148:9520/");
            RestSharp.RestRequest rq = new RestSharp.RestRequest("/api/TrackingLog/AddLog", RestSharp.Method.POST);
            rq.AddHeader("Authorization", "token 132A7468DE079C6CEB59F383A661E612");

            if (dynamic.Count > 0)
            {
                rq.AddJsonBody(dynamic);
                //最长30秒超时
                rq.Timeout = 30 * 1000;
                var res = rc.Execute(rq);
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {

                }
                else
                {
                    throw new Exception(res.ErrorMessage ?? res.Content);
                }
            }
        }

        public override async Task Consume(Job_Customer_FristLog message)
        {
            try
            {
                _jobLogger.LogWarning("接收到提单信息发送请求，" + message.Jobs.Count + "条信息");
                List<dynamic> firstTrackings = new List<dynamic>();
                string sql = $@"select a.CustomerId, c.LadingBillNumber,a.TrackingNumber,a.Id,a.ReceiverCountryCode,d.DepartTime,d.ArrivalTime,d.ClearanceTime,a.CustomerOrderNo,a.ServiceOrderNumber4,a.TransferNumber from Order_Order(nolock) a join Logistics_Boxdetail(nolock) b on a.id = b.orderid join logistics_box(nolock) c on b.boxid=c.id
                              join Logistics_LadingBill(nolock) d on d.LadingBillNumber = c.LadingBillNumber
                           where d.LadingBillNumber in @ladingBillNumber  and d.IsDeleted=0
                            ";
                //string sql = $@"select top 1 'test111' as LadingBillNumber,'6A21640243138' TrackingNumber,212244518 Id,'US' ReceiverCountryCode,'BG-006621130-1623085262' as CustomerOrderNo from Order_Order(nolock) 
                //            ";
                var array = message.Jobs.Select(x => x.LadingBillNumber).ToArray();

                using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(_unitOfWork.ConnectionAddress))
                {
                    connection.Open();
                    firstTrackings = (await connection.QueryAsync<dynamic>(sql, new { ladingBillNumber = array }, null, 0)).ToList();
                }


                foreach (var ladingBillNumber in message.Jobs)
                {
                    try
                    {
                        _jobLogger.LogWarning("发送ESB信息:" + ladingBillNumber.LadingBillNumber);
                        var sendEsbList = firstTrackings.Where(x =>
                        x.LadingBillNumber == ladingBillNumber.LadingBillNumber
                        && (x.ServiceOrderNumber4 == "HNESB")).ToList();
                        if (sendEsbList.Count > 0)
                        {
                            var esblogs = JobSubscribe.GetLogs2(sendEsbList, ladingBillNumber);
                            for (int i = 0; i < Math.Ceiling(esblogs.Count() / 10.0); i++)
                            {
                                var logs3 = esblogs.Skip(10 * i).Take(10).ToList();
                                var logs4 = logs3.Select(x => new TrackingDto
                                {
                                    TrackingNumber = x.TrackingNumber,
                                    Logs = x.List.Select(y => new TrackingLogDto
                                    {
                                        Location = y.Location,
                                        TriggerTime = y.TriggerTime,
                                        Status = y.Status,
                                        StatusString = y.StatusString,
                                    }).ToList()
                                }).ToList();
                                await ESBService.Update(logs4, 1);
                            }
                        }

                        _jobLogger.LogWarning("发送提单头程信息:" + ladingBillNumber.LadingBillNumber);
                        var items = firstTrackings.Where(x =>
                        x.LadingBillNumber == ladingBillNumber.LadingBillNumber
                        && (x.CustomerId == 7 || x.CustomerId == 691)).ToList();
                        if (items.Count > 0)
                        {
                            var logs = JobSubscribe.GetLogs2(items, ladingBillNumber);

                            var logs2 = logs.SelectMany(x => x.List.Select(y => new
                            {
                                CustomerNo = x.CustomerOrderNo,
                                TrackingEventType = ToEventCode(y.Status),
                                Key = x.CustomerOrderNo + "_" + ToEventCode(y.Status),
                                EventLoaction = y.Location,
                                EventContent = y.StatusString,
                                EventTime = y.TriggerTime,
                                GetTime = DateTime.Now.ToString_yyyyMMddHHmmss()
                            }));

                            for (int i = 0; i < Math.Ceiling(logs2.Count() / 120.0); i++)
                            {
                                var logs3 = logs2.Skip(120 * i).Take(120).ToList();
                                SendXiKeLogsApi(logs3);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _jobLogger.LogWarning("发送提单头程信息失败:" + ladingBillNumber.LadingBillNumber + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                _jobLogger.LogError("处理消息失败" + ex.Message + message.Id);
            }

        }

        private TrackingEventType ToEventCode(int code)
        {
            switch (code)
            {
                case 5:
                    return TrackingEventType.Arrive;
                case 4:
                    return TrackingEventType.Departure;
                case 6:
                    return TrackingEventType.Clearance;
                default:
                    throw new Exception("转换失败");
            }
        }
        public async Task AddErrors(List<Logistics_TraceGroup> erros, string target)
        {
            if (erros.Count > 0)
            {
                Frist_Log log = new Frist_Log();
                log.Groups = erros;
                //持久化
                try
                {
                    await _unitOfWork.InsertAsync<ErroJobLog>(new ErroJobLog
                    {
                        ActionUrl = "http://120.24.149.148:9520/api/BatchTracking/TestSendLog",
                        IsExecute = true,
                        Request = Newtonsoft.Json.JsonConvert.SerializeObject(log),
                        Target = target,
                        CreateTime = DateTime.Now
                    });

                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }

            }
        }
    }
}
