using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.ExtendMethods;
using XYY.Core.Standard.PDF;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;

namespace XYY.Service.Standard.ChannelApi.Gori
{
    public class Api : IBaseApi
    {
        public string ServiceName => "GoriUSPS";

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

        public void CannelOrders(List<string> systemNO)
        {
            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)
        {
            string url = channel.ApiHost; //"https://api.goricompany.com/v1/shipments";
            string token = channel.ApiSecret;
            var client = new RestClient(url);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", $"Bearer {token}");

            CreateShipmentParam param = CreateShipmentParam(order, channel);

            string body = Newtonsoft.Json.JsonConvert.SerializeObject(param);
            request.AddParameter("text/plain", body, ParameterType.RequestBody);

            var response = await client.ExecuteAsync<CreateShipmentResp>(request);
            if (response.IsSuccessful)
            {
                var result = response.Data;
                if (result == null || string.IsNullOrWhiteSpace( result.tracking_code) || string.IsNullOrWhiteSpace(result.label?.image_url))
                {
                    string msg = "下单API返回响应无效";
                    if (!string.IsNullOrWhiteSpace(response.Content) && response.Content.Contains("Error", StringComparison.OrdinalIgnoreCase))
                    {
                        msg = response.Content;
                    }

                    
                    return new UploadResult { Error = msg };
                }
                else
                {
                    string pdfUrl = result.label?.image_url;
                    string trackingNumber = result.tracking_code;
                    if (string.IsNullOrWhiteSpace(trackingNumber))
                    {
                        string msg = "渠道返回跟踪号为空";
                        return new UploadResult { Error = msg };
                    }
                    if (string.IsNullOrWhiteSpace(pdfUrl))
                    {
                        string msg = "渠道返回面单为空";
                        return new UploadResult { Error = msg };
                    }
                    return new UploadResult
                    {
                        IsSuccess = true,
                        ServiceOrderNumber = result.tracking_code,
                        DownloadUrl = result.label.image_url,
                        TrackingNumber = result.tracking_code
                    };
                }
            }
            else
            {
                string msg = string.IsNullOrEmpty(response.ErrorMessage) ? response.Content : response.ErrorMessage;
                return new UploadResult { Error = "API下单失败:" + msg };
            }
        }

        private CreateShipmentParam CreateShipmentParam(Order_Order order, Logistics_Channel channel)
        {


            var names = order.ReceiverName.Split(' ');
            string firstName = names.Length >= 1 ? names[0] : order.ReceiverName;
            string lastName = names.Length >= 2 ? names[1] : string.Join(' ', names.Skip(1));

            var streets = order.ReceiverStreet.ToArray(35);
            var street1 = streets[0];
            var street2 = streets.Length > 1 ? streets[1] : null;
            To_address to = new To_address
            {
                city = order.ReceiverCity,
                country = order.ReceiverCountryCode,
                email = order.ReceiverEmail,
                first_name = firstName,
                last_name = lastName,
                phone = order.ReceiverPhone,
                street1 = street1,
                street2 = street2,
                state = order.ReceiverState,
                zip = order.ReceiverZipCode
            };

            From_address from = new From_address
            {
                city = "LOS ANGELES",
                country = "US",
                first_name = "angel",
                street1 = "7001 S CENTRAL AVE",
                zip = "90052-9998",
                state = "CA"
            };


            var weight = order.OPWeight == 0 ? order.CustomerWeight : order.OPWeight;

            decimal ounceRate = 0.03527396m;
            decimal inchRate = 0.0328084m;

            var weightOunce = weight * ounceRate;
            var height = (int)(order.Height * inchRate);
            var length = (int)(order.Length * inchRate);
            var width = (int)(order.Width * inchRate);
            Parcel parcel = new Parcel
            {
                height = height <= 0 ? 1 : height,
                length = length <= 0 ? 1 : length,
                width = width <= 0 ? 1 : width,
                weight = Math.Round(weightOunce, 2)
            };


            string serviceCode = channel.ServiceChannelCode;
            Shipment shipment = new Shipment
            {
                from_address = from,
                to_address = to,
                service = serviceCode,
                parcel = parcel,
                options = new CreateShipmentOptions { verify_address = false }

            };
            CreateShipmentParam param = new CreateShipmentParam
            {
                shipment = shipment
            };
            return param;
        }



        public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            string pdfURL = result.DownloadUrl;
            if (string.IsNullOrEmpty(pdfURL))
            {
                throw new Exception("返回的面单地址为空");
            }

            byte[] data = null;
            System.Net.WebClient client = new System.Net.WebClient();
            for (int i = 0; i < 3; i++)
            {
                data = await client.DownloadDataTaskAsync(new Uri(pdfURL));
                if (data.Length > 5 * 1024)
                {
                    //面单大于5k时返回
                    break;
                }
                //3秒后重试一次
                System.Threading.Thread.Sleep(3 * 1000);
            }
            if (data == null || data.Length < 5 * 1024)
            {
                throw new Exception("面单获取失败，请稍候重试");
            }

            data = PDFHelper.Watermark(data, "PYK", 1, 80, 15, 18, iTextSharp.text.BaseColor.BLACK);

            return data;
        }

        public Task<string> GetTrackingNumber(string SystemNo, string TrackingNumber, string ServiceOrderNo, Logistics_Channel channel)
        {
            throw new NotImplementedException();
        }
        public void CannelOrdersByModel(logistics_ChannelCancel logistics_ChannelCancel)
        {
            throw new NotImplementedException();
        }
    }
}
