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.Standard.Order;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;

namespace XYY.Service.Standard.ChannelApi.YanWen
{
    public partial class Api : IBaseApi
    {

        IOrder_OrderPrintQtyRepository _orderPrintQtyRepository;
        public Api(IOrder_OrderPrintQtyRepository orderPrintQtyRepository)
        {
            _orderPrintQtyRepository = orderPrintQtyRepository;
        }

        public string ServiceName => "YW";

        public Task<List<BagDeclareErrosResult>> BagDeclare(BagDeclareRequest bagDeclareRequest)
        {
            throw new NotImplementedException();
        }

        public void CannelOrders(List<string> systemNO)
        {
            throw new NotImplementedException();
        }

        public void CannelOrdersByModel(logistics_ChannelCancel logistics_ChannelCancel)
        {
            throw new NotImplementedException();
        }

        public Task<List<string>> Confims(List<OrderConfimRequest> order, Logistics_Channel channel)
        {
            throw new NotImplementedException();
        }

        public async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        {

            //品名处理
            List<NanJingGoods> goodsList = new List<NanJingGoods>();
            foreach (var item in goods)
            {

                NanJingGoods sendGoods = new NanJingGoods
                {
                    Userid = channel.ApiKey,
                    NameEn = item.EnName.Replace("&", " "),
                    NameCh = item.CnName.Replace("&", " "),
                    DeclaredCurrency = item.DeclareCurrency,
                    DeclaredValue = goods.Sum(x=>x.DeclareFee * x.Quantity),
                    Weight = order.CustomerWeight,
                    HsCode = item.HsCode
                };
                goodsList.Add(sendGoods);
            }

            Receiver receiver = new Receiver
            {
                Address1 = order.ReceiverStreet,
                City = order.ReceiverCity,
                //Company = package.CompanyName,
                Country = order.ReceiverCountryCode,
                Mobile = order.ReceiverPhone,
                Name = order.ReceiverName,
                Phone = order.ReceiverPhone,
                Postcode = order.ReceiverZipCode,
                State = order.ReceiverState,
                Userid = channel.ApiKey,
                Email = string.Empty
            };

            NanJingPackage_Entity entity = new NanJingPackage_Entity
            {
                Channel = channel.ServiceChannelCode,
                Quantity = goods.Sum(x => x.Quantity),
                SendDate = DateTime.Now,
                Userid = channel.ApiKey,
                Receiver = receiver,
                Goods = goodsList
            };

            int qty = _orderPrintQtyRepository.GetPackagePrintQty(order.SystemNo);
            string number = order.SystemNo.Replace("XYYEX", "LT").Replace("YQ", "") + "-" + qty.ToString();

            entity.UserOrderNumber = number;
            entity.PackageNo = number;

            string body = XmlHelper.XmlSerialize(entity, Encoding.UTF8);
            RestClient restClient = new RestClient(channel.ApiHost + "/Users/" + channel.ApiKey + "/Expresses");

            RestRequest request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "basic " + channel.ApiSecret);
            request.AddHeader("Accept", "application/xml;");
            request.AddHeader("ContentType", "text/xml; charset=utf-8;");
            request.AddParameter("text/xml", body, ParameterType.RequestBody);
            var apiResult = restClient.Execute(request);
            if (apiResult.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("下载失败：" + apiResult.ErrorMessage ?? apiResult.Content);
            }

            NanJingResponse result = XmlHelper.XmlDeserialize<NanJingResponse>(apiResult.Content, Encoding.UTF8);
            if (!result.CallSuccess)
            {
                throw new Exception(result.Response.ReasonMessage);
            }

            return new UploadResult
            {
                IsSuccess = true,
                LazyDownloadLabel = false,
                TrackingNumber = result.Response.Epcode
            };

            //
        }

        public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            //throw new Exception("中性面单");
            string pdfUrl = channel.ApiHost + "/Users/" + channel.ApiKey + "/Expresses/" + result.TrackingNumber + "/A10x10LLabel";
            var restClient = new RestClient(pdfUrl);
            var request = new RestRequest(Method.GET);
            request.AddHeader("Authorization", "basic " + channel.ApiSecret);
            request.AddHeader("Accept", "application/xml;");
            request.AddHeader("ContentType", "text/xml; charset=utf-8;");
            string errorMessage = "";
            bool isSuccess = false;
            IRestResponse restResponse = null;
            int nums = 1;
            do
            {
                restResponse = restClient.Execute(request);
                if (restResponse.StatusCode != System.Net.HttpStatusCode.OK || restResponse.RawBytes.Length < 2000)
                {
                    errorMessage = "下单失败，数据已提交--->error:{0};contnet:{1}".Formater(restResponse.ErrorMessage, restResponse.Content);
                }
                else
                {
                    isSuccess = true;
                }
                nums++;
            } while (!isSuccess && nums < 3);

            if (!isSuccess)
            {
                throw new Exception(errorMessage);
            }
            return restResponse.RawBytes;
        }

        public async Task<string> GetTrackingNumber(string SystemNo, string TrackingNumber, string ServiceOrderNo, Logistics_Channel channel)
        {
            string trackingUrl = $"http://trackapi.yanwentech.com/api/tracking?nums={ServiceOrderNo}";
            var restClient = new RestClient(trackingUrl);
            var request = new RestRequest(Method.GET);
            request.AddHeader("Authorization", channel.ApiKey);
            var response = restClient.Execute(request);
            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception($"获取末端单号失败{response.ErrorMessage ?? response.Content}");

            TrackingResult result = Newtonsoft.Json.JsonConvert.DeserializeObject<TrackingResult>(response.Content);
            if (result.message != "success")
            {
                throw new Exception($"获取末端单号失败{result.message}");
            }

            if (result.result != null && result.result.Count > 0)
                return result.result[0].exchange_number;
            else
                throw new Exception("获取末端单号失败，result为空");
        }

        public class TrackingResult
        {
            public int code
            {
                get; set;
            }

            public string message
            {
                get; set;
            }

            public List<TrackingResultItem> result
            {
                get; set;
            }
        }

        public class TrackingResultItem
        {
            public string tracking_number
            {
                get; set;
            }

            public string exchange_number
            {
                get; set;
            }
        }
    }
}
