using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;
using XYY.Core.Standard.ExtendMethods;
using XYY.Core.Standard.PDF;
using XYY.Core.Standard.ExtendMethods;
namespace XYY.Service.Standard.ChannelApi.YiHaiTong
{
    public class Api : IBaseApi
    {
        //此dataDigest，非user token
        const string dataDigest = "cXdlcnJ0eXVpb3Bhc2RmZ2hqa2x6eGN2Ym5tMTIzNDU2Nzg5MA==";
        public string ServiceName => "YIHAITONG";

        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;
            string token = channel.ApiSecret;
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);

            CreateOrderRoot param = CreateShipmentParam(order, goods, channel);
            request.AddJsonBody(param);

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


                    throw new Exception(msg);
                }
                else
                {
                    if (result.success != true)
                    {
                        string msg = string.IsNullOrWhiteSpace(result.message) ? "渠道商API返回失败" : result.message;
                        return new UploadResult { Error = msg };
                    }
                    else if (result.data == null || result.data.Count == 0)
                    {
                        string msg = "渠道商API返回订单数据为空";
                        throw new Exception(msg);
                    }

                    var item = result.data[0];
                    if (item.success != true)
                    {
                        string msg = string.IsNullOrWhiteSpace(item.message) ? "渠道商API返回失败" : item.message;
                        throw new Exception(msg);
                    }

                    string pdfUrl = item.labelUrl;
                    string trackingNumber = item.yodelNumber;
                    string serviceOrderNumber = item.orderNo;
                    if (string.IsNullOrWhiteSpace(trackingNumber))
                    {
                        string msg = "渠道返回跟踪号为空";
                        throw new Exception(msg);
                    }
                    if (string.IsNullOrWhiteSpace(pdfUrl))
                    {
                        string msg = "渠道返回面单为空";
                        throw new Exception(msg);
                    }
                    return new UploadResult
                    {
                        IsSuccess = true,
                        ServiceOrderNumber = serviceOrderNumber,
                        DownloadUrl = pdfUrl,
                        TrackingNumber = trackingNumber
                    };
                }
            }
            else
            {
                string msg = string.IsNullOrEmpty(response.ErrorMessage) ? response.Content : response.ErrorMessage;
                throw new Exception("API下单失败:" + msg);
                //return new UploadResult { Error = "API下单失败:" + msg };
            }
        }

        private CreateOrderRoot CreateShipmentParam(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel)
        {

            string userId = channel.ApiKey;
            string token = channel.ApiSecret;


            List<CreateOrderData> data = new List<CreateOrderData>();

            var totalValue = goods.Sum(g => g.DeclareFee * g.Quantity);
            var weight = order.OPWeight <= 0 ? order.CustomerWeight : order.OPWeight;
            var weight_kg = weight / 1000m;

            OtherInformationDto otherInfo = new OtherInformationDto
            {
                arrivalPlace = null,
                companyId = "OTHER",
                deliveryWay = "中英专线Hermes（普货）",//channel.ServiceChannelCode,
                domesticMailNo = null,
                hasPickUpService = false,
                refNo = order.TransferNumber

            };

            List<ProductItemDtos> productItemDtos = CreateItemDtos(goods).ToList();
            ReceiveContact receiveContact = CreateReceiveContact(order);
            SendContact sendContact = CreateSendContact(channel);

            CreateOrderData orderData = new CreateOrderData
            {
                customerOrderId = order.TransferNumber,
                hasBattery = false,
                height = (int)order.Height,
                length = (int)order.Length,
                width = (int)order.Width,
                otherInformationDto = otherInfo,
                paymentMethod = null,
                productItemDtos = productItemDtos,
                receiveContact = receiveContact,
                sendContact = sendContact,
                totalCargoValue = totalValue,
                totalWeight = weight_kg,

            };
            data.Add(orderData);

            CreateOrderRoot root = new CreateOrderRoot
            {
                userToKen = token,
                userId = userId,
                dataDigest = dataDigest,
                data = data
            };
            return root;
        }

        private SendContact CreateSendContact(Logistics_Channel channel)
        {
            SendContact c = new SendContact
            {
                address = channel.SenderStreet,
                cityName = channel.SenderCity,
                company = channel.SenderCompany,
                countryName = channel.SenderCountryCode,
                name = channel.SenderName,
                phone = channel.SenderPhone,
                postCode = channel.SenderZipCode,
                provinceName = channel.SenderState,

            };
            return c;
        }

        private ReceiveContact CreateReceiveContact(Order_Order order)
        {
            var arr = order.ReceiverStreet.ToArray(30);
            string street1 = (arr?.Any() == true) ? arr[0] : order.ReceiverStreet;
            string street2 = (arr?.Any() == true && arr.Length > 1) ? arr[1] : null;
            ReceiveContact c = new ReceiveContact
            {
                address = arr[0],
                cityName = order.ReceiverCity,
                company = order.ReceiverCompany,
                countryName = order.ReceiverCountryCode,
                name = order.ReceiverName,
                phone = order.ReceiverPhone,
                postCode = order.ReceiverZipCode,
                provinceName = order.ReceiverState,
            };
            return c;
        }

        private IEnumerable<ProductItemDtos> CreateItemDtos(List<Order_OrderGoods> goods)
        {
            foreach (var g in goods)
            {
                ProductItemDtos item = new ProductItemDtos
                {
                    cargoValue = g.DeclareFee,
                    hsCode = g.HsCode,
                    nameCn = g.CnName,
                    nameEn = g.EnName,
                    quantity = g.Quantity
                };
                yield return item;
            }
        }

        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("面单获取失败，请稍候重试");
            }
            //遮住YHT字眼
            data = PDFHelper.Watermark(data, "▅", 1, 69, 101, 15, iTextSharp.text.BaseColor.WHITE);

            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();
        }
    }
}
