using iTextSharp.text.pdf.parser;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Core.Standard.ExtendMethods;
//using XYY.Common.Standard;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;

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

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

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

        public void CannelOrdersByModel(Model.Standard.Channel.logistics_ChannelCancel logistics_ChannelCancel)
        {
            throw new NotImplementedException();
        }

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



        public async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Model.Standard.Channel.Logistics_Channel channel, Model.Standard.Channel.ExtendArg arg)
        {
            if (order.Width < 1)
                order.Width = 1;
            if (order.Height < 1)
                order.Height = 1;
            if (order.Length < 1)
                order.Length = 1;
            string url = channel.ApiHost;
            RestClient client = new RestClient(url);
            RestRequest request = new RestRequest("/api/v1/ordering", Method.POST);
            request.AddHeader("API_KEY", channel.ApiKey);
            request.AddHeader("API_SECRET", channel.ApiSecret);
            string[] addresList = channel.SenderStreet.ToArray(50);
            string[] receiverList = order.ReceiverStreet.ToArray(50);
            if (addresList.Length > 2)
            {
                return new UploadResult
                {
                    IsSuccess = false,
                    Error = "地址超长"
                };
            }
            string refrno = order.SystemNo.Replace("XYYEX", "A");
            decimal orderWeight = order.OPWeight <= 0 ? order.CustomerWeight : order.OPWeight;
            CreateOrderReq req = new CreateOrderReq
            {
                refer_no = refrno,
                service_code = channel.ServiceChannelCode,
                sender = new Sender
                {
                    state = "IN",
                    address = new List<string> { "7114 W 200 N, Greenfield" },//addresList.ToList(),
                    city = "Indianapolis",
                    country ="US",
                    name = "Shipping Center ",
                    zipcode = "46140",
                    phone = "",

                },
                receiver = new Receiver
                {
                    address = receiverList.ToList(),
                    city = order.ReceiverCity,
                    country = order.ReceiverCountryCode,
                    name = order.ReceiverName,
                    state = order.ReceiverState,
                    zipcode = order.ReceiverZipCode,
                    phone = order.ReceiverPhone
                },
                products = new List<ProductsItem> { new ProductsItem {
                    description_en ="T",
                    description_cn="T",
                    hs_code="00000000",
                    price = 1,
                    weight = orderWeight/1000
                } },
                package = new Package
                {
                    dimension = new Dimension
                    {
                        width = 1,
                        height =1,
                        length =1,
                        unit = "cm"
                    },
                    weight = new Weight
                    {
                        unit = "kg",
                        value = orderWeight / 1000
                    },
                    amount = 1
                },
                region_code = order.ReceiverCountryCode
            };
            request.AddJsonBody(req);
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {

                CreateOrderReult result = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateOrderReult>(response.Content);

                string getOrderInfoUrl = channel.ApiHost;
                string action = $"/api/v1/order/label?refer_no=&label_no={result.label_no}&logistics_code=";

                RestRequest orderInfoRequest = new RestRequest(action, Method.GET);
                string fullUrl = getOrderInfoUrl + action;
                orderInfoRequest.AddHeader("API_KEY", channel.ApiKey);
                orderInfoRequest.AddHeader("API_SECRET", channel.ApiSecret);
                var orderInfoResponse = client.Execute<LabelResult>(orderInfoRequest);
                if (orderInfoResponse.IsSuccessful)
                {
                    string labelUrl = orderInfoResponse.Data.label_url;
                    return new UploadResult
                    {
                        IsSuccess = true,
                        TrackingNumber = orderInfoResponse.Data.logistics_code,
                        DownloadUrl = labelUrl,
                        ServiceOrderNumber = orderInfoResponse.Data.label_no
                    };
                }
                else
                {
                    return new UploadResult { Error = "Ship Api订单查询失败" + (orderInfoResponse.ErrorMessage ?? orderInfoResponse.Content) };
                }
            }
            else
            {
                return new UploadResult { Error = "Ship Api下单失败" + (response.Content ?? response.ErrorMessage) };
            }
        }



        public Task<byte[]> DrawPdfLabel(UploadResult result, Model.Standard.Channel.Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            string labelUrl = result.DownloadUrl;
            if (!string.IsNullOrEmpty(labelUrl))
            {
                var Data = new System.Net.WebClient().DownloadData(labelUrl);
                return Task.FromResult(Data);
            }
            else
            {
                throw new Exception("Ship Api面单下载失败");
            }
        }

        public Task<string> GetTrackingNumber(string SystemNo, string TrackingNumber, string ServiceOrderNo, Model.Standard.Channel.Logistics_Channel channel)
        {
            throw new NotImplementedException();
        }
    }

    public class LabelResult
    {
        /// <summary>
        /// 
        /// </summary>
        public string refer_no { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string label_no { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string logistics_code_readable { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string logistics_code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string logistics_company { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string label_url { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public double charge { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string charge_currency { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string zone { get; set; }
    }

    public class CreateOrderReult
    {
        /// <summary>
        /// 
        /// </summary>
        public string refer_no { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string label_no { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public double charge { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string charge_currency { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string zone { get; set; }
    }

    //如果好用，请收藏地址，帮忙分享。
    public class Sender
    {
        /// <summary>
        /// 
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string country { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string state { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string city { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<string> address { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string zipcode { get; set; }
        public string phone { get; set; }
    }

    public class Receiver
    {
        /// <summary>
        /// 
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string country { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string state { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string city { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<string> address { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string zipcode { get; set; }
        public string phone { get; set; }
    }

    public class Dimension
    {
        /// <summary>
        /// 
        /// </summary>
        public int width { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int height { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int length { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string unit { get; set; }
    }

    public class Weight
    {
        /// <summary>
        /// 
        /// </summary>
        public decimal value { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string unit { get; set; }
    }

    public class Package
    {
        /// <summary>
        /// 
        /// </summary>
        public Dimension dimension { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public Weight weight { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int amount { get; set; }
    }

    public class ProductsItem
    {
        /// <summary>
        /// 衣服
        /// </summary>
        public string description_cn { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string description_en { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string hs_code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public decimal price { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public decimal weight { get; set; }
    }

    public class CreateOrderReq
    {
        /// <summary>
        /// 
        /// </summary>
        public string refer_no { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string service_code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string region_code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public Sender sender { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public Receiver receiver { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public Package package { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<ProductsItem> products { get; set; }
    }

}
