using iTextSharp.text;
using NPOI.OpenXmlFormats.Dml.Chart;
using NPOI.SS.Formula.Functions;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using XYY.Common.Standard;
using XYY.Data.Model.Standard.Tracking.TrackingTraces;
using XYY.Data.Standard.Order;
using XYY.Model.Standard.Order;
using static XYY.Data.Standard.Order.OrderRepository;

namespace XYY.Service.Standard.Order
{
    public interface ICustomerLazyService
    {
        Task<bool> AsyncFirstESBTracking();
        Task<bool> AsyncLastTrackingNumber();
    }

    public class CustomerLazyService : ICustomerLazyService
    {
        IOrderRepository orderRepository;

        public CustomerLazyService(IOrderRepository orderRepository)
        {
            this.orderRepository = orderRepository;
        }

        public async Task<bool> AsyncFirstESBTracking()
        {
            var data = await orderRepository.GetWaitAsyncESBDate(30);
            if (data.Count() > 0)
            {
                SendESB(data);
                await orderRepository.UpdateEnd(data.Select(x => x.Id).ToList());
            }
            return data.Count() > 0;
        }
        public class Req
        {
            public List<TrackingDto> dtos { get; set; }
        }
        public class TrackingLog
        {

            /// <summary>
            /// 跟踪信息触发时间
            /// </summary>
            public DateTime TriggerTime
            {
                get;
                set;
            }

            /// <summary>
            /// 位置
            /// </summary>
            public string Location
            {
                get;
                set;
            }

            /// <summary>
            ///   状态  1.无物流信息 2.在国内揽收出库完成 3.头程供应商已收件 4.已离岸 5.已到岸 6.尾程派送中 7.已签收 10.被尾程退回
            /// </summary>
            public int Status
            {
                get;
                set;
            }

            public string StatusString
            {
                get;
                set;
            }
        }
        public class TrackingDto
        {
            public string TrackingNumber
            {
                get; set;
            }

            public List<TrackingLog> Logs
            {
                get; set;
            }
        }

        public void SendESB(List<Order_CustomerAsyncTracking> dtos)
        {
            Req req = new Req
            {
                dtos = dtos.GroupBy(x => x.TransferNumber).Select(y => new TrackingDto
                {
                    TrackingNumber = y.Key,
                    Logs = y.Select(z => new TrackingLog
                    {
                        Location = z.Loaction,
                        Status = 5,
                        StatusString = z.Event,
                        TriggerTime = z.OperTime
                    }).ToList()
                }).ToList()
            };



            RestSharp.RestClient rc = new RestSharp.RestClient("http://120.24.149.148:9520/");
            RestSharp.RestRequest rq = new RestSharp.RestRequest("/api/ESB/Update", RestSharp.Method.POST);
            rq.AddHeader("Authorization", "token 132A7468DE079C6CEB59F383A661E612");

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

                }
                else
                {
                    throw new Exception("ESB客户头程消息发送失败" + string.Join("\n", dtos.Select(x => x.TransferNumber)));
                }
            }
        }


        public async Task<bool> AsyncLastTrackingNumber()
        {
            var orders = await orderRepository.GetWaitSyncCustomerTracking(30);
            string url = $@"http://124.220.133.174:8082/selectTrack.htm?documentCode={string.Join(",", orders.Select(x => x.CustomerOrderNo))}";
            var restClient = new RestClient(url);
            var restRequest = new RestRequest(Method.GET);
            restClient.Proxy = new WebProxy("localhost:8888");
            var response = restClient.Execute(restRequest);
            RestSharpHelper.SetResponseEncoding(response, "gb2312");
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                List<TrackingResult> TrackingResults = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TrackingResult>>(response.Content);
                if (TrackingResults.Count == 0)
                    throw new Exception("接口异常" + response.Content ?? response.ErrorMessage);
                else
                {
                    var f = TrackingResults.First();

                    var data = TrackingResults.First().data;
                    List<UpdateDataDto> list = new List<UpdateDataDto>();
                    if(data != null)
                    {
                        foreach (var item in data.Where(x => x.trackDetails.Any(x => x.track_content.Equals("到达收货点"))))
                        {
                            var db = orders.FirstOrDefault(x => x.CustomerOrderNo == item.referenceNumber);
                            if (db == null)
                                throw new Exception("回写订单信息失败，找不到相关订单");
                            else
                            {
                                list.Add(new UpdateDataDto
                                {
                                    Id = db.Id,
                                    TrackingNumber = item.trackingNumber,
                                    CustomerOrderNo = item.referenceNumber,
                                    ReceiveTime = DateTime.Parse(item.trackDetails.First(x => x.track_content.Equals("到达收货点")).track_date),
                                    SystemNo = db.SystemNo,
                                    TransferNumber = db.TransferNumber

                                });
                            }
                        }

                    }
                    
                    if (list.Count > 0)
                        await UpdateData(list);
                    var noUpdateData = orders.Where(x => !list.Any(y => y.Id == x.Id)).ToList();
                    await orderRepository.SetNextUpdate(noUpdateData);
                }

            }
            else
            {
                throw new Exception(response.Content ?? response.ErrorMessage);
            }
            return orders.Count() > 0;
        }



        public async Task UpdateData(List<UpdateDataDto> list)
        {
            await orderRepository.UpdateTrackingNumber(list);
        }
    }



    //如果好用，请收藏地址，帮忙分享。
    public class TrackDetailsItem
    {
        /// <summary>
        /// 
        /// </summary>
        public string business_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string country_code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string flight_number { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string is_weic { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string system_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string time_zone { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_city { get; set; }
        /// <summary>
        /// 到达收货点
        /// </summary>
        public string track_content { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_createdate { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_date { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_kind { get; set; }
        /// <summary>
        /// 深圳
        /// </summary>
        public string track_location { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_signdate { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_signperson { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_state { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_substate { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_zippost { get; set; }
    }

    public class DataItem
    {
        /// <summary>
        /// 
        /// </summary>
        public string businessId { get; set; }
        /// <summary>
        /// 转运中
        /// </summary>
        public string businessStatus { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string business_channeltransfercode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string business_customerweightf { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string business_grossweight { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string business_pieces { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string business_seqinvoicecode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string business_serveweightf { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string childrenTrackDetails { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string consigneeCountry { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string consignee_address { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string consignee_name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string customer_code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string file_path { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string flight_number { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string order_customnote { get; set; }
        /// <summary>
        /// 叁仟跨境特货专线
        /// </summary>
        public string productKindName { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string product_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string referenceNumber { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string shipper_name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string time_zone { get; set; }
        /// <summary>
        /// 转运中到达收货点
        /// </summary>
        public string trackContent { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string trackDate { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<TrackDetailsItem> trackDetails { get; set; }
        /// <summary>
        /// 深圳
        /// </summary>
        public string trackLocation { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string trackSignperson { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string track_cid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string trackingNumber { get; set; }
    }

    public class TrackingResult
    {
        /// <summary>
        /// 
        /// </summary>
        public List<DataItem> data { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string ack { get; set; }
    }

}
