using Fedex;
using iTextSharp.awt.geom;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Nest;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using XYY.Common.Standard;
using XYY.Core.Standard.FiddlerClient;
using XYY.Data.Standard;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;
using static Fedex.ShipPortTypeClient;

namespace XYY.Service.Standard.ChannelApi.FedexAPI
{
    public partial class Api : IBaseApi
    {
        #region 构造
        public Api()
        {
        }
        #endregion
        #region 私有
        public string ServiceName => "Fedex";
        static string[] receiverCountryCode = new string[] {
            "AT",   "BE",   "BG",   "CY",   "DK",   "EE",   "FI",   "FR",   "DE",   "GR",   "HU",   "IE",   "IT",   "LV",   "LT",   "LU",   "MT",   "NL",   "PL",   "PT",   "RO",   "SK",   "SI",   "ES",   "SE",   "HR",   "CZ"
            };
        /// <summary>
        /// 实体判断操作
        /// </summary>
        /// <param name="order"></param>
        private void OrderModelJudge(Order_Order order)
        {
            if (!string.IsNullOrWhiteSpace(order.ReceiverName))
            {
                order.ReceiverName = order.ReceiverName.TrimEmpty();
            }

            if (!string.IsNullOrWhiteSpace(order.ReceiverPhone))
            {
                order.ReceiverPhone = order.ReceiverPhone.TrimEmpty();
            }

            if (!string.IsNullOrWhiteSpace(order.ReceiverZipCode))
            {
                order.ReceiverZipCode = order.ReceiverZipCode.TrimEmpty();
            }

            if (!string.IsNullOrWhiteSpace(order.ReceiverState))
            {
                order.ReceiverState = order.ReceiverState.TrimEmpty();
            }
            if (!string.IsNullOrWhiteSpace(order.ReceiverCity))
            {
                order.ReceiverCity = order.ReceiverCity.TrimEmpty();
            }
            if (!string.IsNullOrWhiteSpace(order.ReceiverStreet))
            {
                order.ReceiverStreet = order.ReceiverStreet.TrimEmpty();
            }
            if (order.ReceiverCountryCode == "US")
            {
                Dictionary<string, string> pairs = new Dictionary<string, string>
                {
                    { "Washington", "WA" },
                    { "Oregon", "OR" },
                    { "California", "CA" },
                    { "Nevada", "NV" },
                    { "Idaho", "ID" },
                    { "Utah", "UT" },
                    { "Arizona", "AZ" },
                    { "Montana", "MT" },
                    { "Wyoming", "WY" },
                    { "Colorado", "CO" },
                    { "New Mexico", "NM" },
                    { "Wisconsin", "WI" },
                    { "Illinois", "IL" },
                    { "Tennessee", "TN" },
                    { "Mississippi", "MS" },
                    { "Michigan", "MI" },
                    { "Indiana", "IN" },
                    { "Kentucky", "KY" },
                    { "Alabama", "AL" },
                    { "Ohio", "OH" },
                    { "West Virginia", "WV" },
                    { "Virginia", "VA" },
                    { "North Carolina", "NC" },
                    { "South Carolina", "SC" },
                    { "Georgia", "GA" },
                    { "North Dakota", "ND" },
                    { "South Dakota", "SD" },
                    { "Nebraska", "NE" },
                    { "Kansas", "KS" },
                    { "Oklahoma", "OK" },
                    { "Texas", "TX" },
                    { "Minnesota", "MN" },
                    { "Iowa", "IA" },
                    { "Missouri", "MO" },
                    { "Arkansas", "AR" },
                    { "Louisiana", "LA" },
                    { "Florida", "FL" },
                    { "Pennsylvania", "PA" },
                    { "New York", "NY" },
                    { "Washington D. C.", "DC" },
                    { "Maryland", "MD" },
                    { "Delaware", "DE" },
                    { "New Jersey", "NJ" },
                    { "Connecticut", "CT" },
                    { "Rhode Island", "RI" },
                    { "Massachusetts", "MA" },
                    { "Maine", "ME" },
                    { "New Hampshire", "NH" },
                    { "Vermont", "VT" },
                    {"Alaska","AK" },
                    {"Hawaii","HI" },
                    {"PR","PR" },
                    {"Guam","GU" },
                    {"Virgin Islands","VI" },
                };

                if (!pairs.Keys.Any(x => x.Equals(order.ReceiverState, StringComparison.CurrentCultureIgnoreCase))
                    && !pairs.Values.Any(x => x.Equals(order.ReceiverState, StringComparison.CurrentCultureIgnoreCase))
                    )
                {
                    if (pairs.Keys.Any(x => x.Equals(order.ReceiverCity, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        string state = order.ReceiverState;
                        order.ReceiverState = pairs.Where(x => x.Key.Equals(order.ReceiverCity, StringComparison.CurrentCultureIgnoreCase)).First().Value;
                        order.ReceiverCity = state;
                    }
                    else if (pairs.Values.Any(x => x.Equals(order.ReceiverCity, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        string state = order.ReceiverState;
                        order.ReceiverState = order.ReceiverCity;
                        order.ReceiverCity = order.ReceiverState;
                    }
                    else
                    {
                        throw new Exception("美国专线必须传入标准的州名或州简写");
                    }
                }
                else
                    if (pairs.Keys.Any(x => x.Equals(order.ReceiverState, StringComparison.CurrentCultureIgnoreCase)))
                {
                    order.ReceiverState = pairs.Where(x => x.Key.Equals(order.ReceiverState, StringComparison.CurrentCultureIgnoreCase)).First().Value;
                }
            }
        }
        private static void SetSender(ProcessShipmentRequest request, Logistics_Channel channel, Order_Order order,ExtendArg arg)
        {
            request.RequestedShipment.Shipper = new Party();
            request.RequestedShipment.Shipper.Contact = new Contact();
            request.RequestedShipment.Shipper.Contact.PersonName = channel.SenderName;
            request.RequestedShipment.Shipper.Contact.CompanyName = channel.SenderCompany;
            request.RequestedShipment.Shipper.Contact.PhoneNumber = channel.SenderPhone;
            request.RequestedShipment.Shipper.Address = new Address();
            request.RequestedShipment.Shipper.Address.StreetLines = channel.SenderStreet.ToArray(35);
            request.RequestedShipment.Shipper.Address.City = channel.SenderCity;
            request.RequestedShipment.Shipper.Address.StateOrProvinceCode = channel.SenderState;
            request.RequestedShipment.Shipper.Address.PostalCode = channel.SenderZipCode;
            request.RequestedShipment.Shipper.Address.CountryCode = channel.SenderCountryCode;
            //ioss 相关

            if (receiverCountryCode.Contains(order.ReceiverCountryCode))
            {
                //设置ioss号码
                if (!string.IsNullOrEmpty(order.ioss))
                    request.RequestedShipment.Shipper.Tins = new TaxpayerIdentification[] { new TaxpayerIdentification { TinType = TinType.BUSINESS_NATIONAL, Number = order.ioss } };
                else
                {
                    string[] receiverCountryCode = new string[] {
            "AT",   "BE",   "BG",   "CY",   "DK",   "EE",   "FI",   "FR",   "DE",   "GR",   "HU",   "IE",   "IT",   "LV",   "LT",   "LU",   "MT",   "NL",   "PL",   "PT",   "RO",   "SK",   "SI",   "ES",   "SE",   "HR",   "CZ"
            };
                    if (arg.AgentIOSS && order.CustomerId != 146
                        )
                    {
                        request.RequestedShipment.Shipper.Tins = new TaxpayerIdentification[] { new TaxpayerIdentification { TinType = TinType.BUSINESS_NATIONAL, Number = "IM2500000320" } };
                    }

                }

            }
        }
        private static void SetETD(ProcessShipmentRequest request, string etd)
        {

            request.RequestedShipment.SpecialServicesRequested = new ShipmentSpecialServicesRequested
            {
                SpecialServiceTypes = new string[] { "ELECTRONIC_TRADE_DOCUMENTS" },
                EtdDetail = new EtdDetail
                {
                    DocumentReferences =
                        new UploadDocumentReferenceDetail[] { new UploadDocumentReferenceDetail {
                            DocumentId = etd ,
                            DocumentType = UploadDocumentType.COMMERCIAL_INVOICE
                        } }
                }
            };
        }
        private static void SetRecipient(ProcessShipmentRequest request, Order_Order order)
        {
            request.RequestedShipment.Recipient = new Party();
            // TINS is optional(Tax Payer Identification)

            //
            request.RequestedShipment.Recipient.Contact = new Contact();
            request.RequestedShipment.Recipient.Contact.PersonName = order.ReceiverName;
            request.RequestedShipment.Recipient.Contact.CompanyName = order.ReceiverName;
            request.RequestedShipment.Recipient.Contact.PhoneNumber = order.ReceiverPhone;
            //
            request.RequestedShipment.Recipient.Address = new Address();
            request.RequestedShipment.Recipient.Address.StreetLines = order.ReceiverStreet.ToArray(35);
            request.RequestedShipment.Recipient.Address.City = order.ReceiverCity;
            request.RequestedShipment.Recipient.Address.StateOrProvinceCode = order.ReceiverState;
            request.RequestedShipment.Recipient.Address.PostalCode = order.ReceiverZipCode;
            request.RequestedShipment.Recipient.Address.CountryCode = order.ReceiverCountryCode;
            request.RequestedShipment.Recipient.Address.Residential = false;
        }
        private static void SetPayment(ProcessShipmentRequest request, Logistics_Channel channel)
        {
            request.RequestedShipment.ShippingChargesPayment = new Payment();
            request.RequestedShipment.ShippingChargesPayment.PaymentType = PaymentType.SENDER;
            request.RequestedShipment.ShippingChargesPayment.Payor = new Payor();
            request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty = new Party();
            request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.AccountNumber = channel.ApiSecret.Split(';')[0]; // Replace "XXX" with client's account number

            request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Contact = new Contact();
            request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address = new Address();
            request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address.CountryCode = "CN";
        }
        private static void SetLabelDetails(ProcessShipmentRequest request)
        {
            request.RequestedShipment.LabelSpecification = new LabelSpecification();
            request.RequestedShipment.LabelSpecification.ImageType = ShippingDocumentImageType.PDF; // Image types PDF, PNG, DPL, ...
            request.RequestedShipment.LabelSpecification.ImageTypeSpecified = true;
            request.RequestedShipment.LabelSpecification.LabelFormatType = LabelFormatType.COMMON2D;
        }
        private static void SetPackageLineItems(ProcessShipmentRequest request, Order_Order order, bool isPak)
        {
            request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[1];
            request.RequestedShipment.RequestedPackageLineItems[0] = new RequestedPackageLineItem();
            request.RequestedShipment.RequestedPackageLineItems[0].SequenceNumber = "1";
            // Package weight information
            request.RequestedShipment.RequestedPackageLineItems[0].Weight = new Weight
            {
                Value = (decimal)(Math.Floor(order.CustomerWeight / 100.0) / 10.0),
                Units = WeightUnits.KG
            };


            request.RequestedShipment.RequestedPackageLineItems[0].SpecialServicesRequested = new PackageSpecialServicesRequested
            {
                SignatureOptionDetail = new SignatureOptionDetail
                {
                    OptionType = SignatureOptionType.SERVICE_DEFAULT
                }
            };
            // package dimensions
            if (!isPak && order.Length > 0 && order.Width > 0 && order.Height > 0)
            {
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions = new Dimensions();
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Length = ((int)order.Length).ToString();
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Width = ((int)order.Width).ToString();
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Height = ((int)order.Height).ToString();
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Units = LinearUnits.CM;
            }
            // insured value
            //request.RequestedShipment.
            //request.RequestedShipment.RequestedPackageLineItems[0].InsuredValue = new Money();
            //request.RequestedShipment.RequestedPackageLineItems[0].InsuredValue.Amount = 0;
            //request.RequestedShipment.RequestedPackageLineItems[0].InsuredValue.Currency = request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency;
            // Reference details
            request.RequestedShipment.RequestedPackageLineItems[0].CustomerReferences = new CustomerReference[1] { new CustomerReference() };
            request.RequestedShipment.RequestedPackageLineItems[0].CustomerReferences[0].CustomerReferenceType = CustomerReferenceType.CUSTOMER_REFERENCE;
            request.RequestedShipment.RequestedPackageLineItems[0].CustomerReferences[0].Value = order.SystemNo;
        }
        private static void SetCustomsClearanceDetails(ProcessShipmentRequest request, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> goods)
        {
            request.RequestedShipment.CustomsClearanceDetail = new CustomsClearanceDetail();
            if (receiverCountryCode.Contains(order.ReceiverCountryCode) && !string.IsNullOrEmpty(order.ioss))
            {
                request.RequestedShipment.CustomsClearanceDetail.DutiesPayment = new Payment();
                request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.PaymentType = PaymentType.RECIPIENT;
            }
            else
            {
                request.RequestedShipment.CustomsClearanceDetail.DutiesPayment = new Payment();
                request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.PaymentType = PaymentType.RECIPIENT;
            }


            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor = new Payor();            
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty = new Party();            
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.AccountNumber = string.Empty;
            //// Replace "XXX" with the payor account number

            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Contact = new Contact();
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Contact.CompanyName = order.ReceiverName;
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Contact.PersonName = order.ReceiverName;
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Contact.PhoneNumber = order.ReceiverPhone;


            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Address = new Address();
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Address.CountryCode = order.ReceiverCountryCode;
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Address.City = order.ReceiverCity;
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Address.StateOrProvinceCode = order.ReceiverState;
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Address.StreetLines = new string[] { order.ReceiverStreet };
            //request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.Address.PostalCode = order.ReceiverZipCode;
            request.RequestedShipment.CustomsClearanceDetail.DocumentContent = InternationalDocumentContentType.NON_DOCUMENTS;
            //
            request.RequestedShipment.CustomsClearanceDetail.CustomsValue = new Money();
            request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Amount = goods.Sum(x => x.DeclareFee * x.Quantity);

            request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency = goods.First().DeclareCurrency;

            if (request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency == "GBP")
            {
                request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency = "USD";
                goods.ForEach(x =>
                {
                    if (x.DeclareCurrency == "GBP")
                    {
                        x.DeclareCurrency = "USD";
                        x.DeclareFee = Math.Round(x.DeclareFee * 1.3896m);
                    }
                });
            }

            if (receiverCountryCode.Contains(order.ReceiverCountryCode) && request.RequestedShipment.Shipper.Tins != null)
            {
                request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency = "EUR";
            }
            //
            SetCommodityDetails(request, goods);
        }
        private static void SetCommodityDetails(ProcessShipmentRequest request, List<Order_OrderGoods> goods)
        {
            var list = goods.GroupBy(x => new { x.CnName, x.EnName, x.DeclareFee, x.Weight, x.DeclareCurrency }).Select(x => new
            {
                x.Key.CnName,
                x.Key.EnName,
                x.Key.DeclareFee,
                x.Key.Weight,
                x.Key.DeclareCurrency,
                Qty = x.Count()
            });
            var dlist = new List<Commodity>();

            foreach (var item in list)
            {
                dlist.Add(new Commodity
                {
                    NumberOfPieces = item.Qty.ToString(),
                    Description = item.EnName,
                    CountryOfManufacture = "CN",

                    Weight = new Weight()
                    {
                        Units = WeightUnits.KG,
                        Value = (decimal)(Math.Floor(item.Weight / 100.0) / 10.0),
                    },

                    Quantity = 1.0m,
                    QuantitySpecified = true,
                    QuantityUnits = "Piece",

                    UnitPrice = new Money
                    {
                        Amount = item.DeclareFee,
                        Currency = request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency
                    },

                    CustomsValue = new Money
                    {
                        Amount = item.DeclareFee,
                        Currency = request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency
                    }
                }); ;
            }
            request.RequestedShipment.CustomsClearanceDetail.Commodities = dlist.ToArray();
        }
        private static WebAuthenticationDetail SetWebAuthenticationDetail(string ApiKey)
        {
            WebAuthenticationDetail wad = new WebAuthenticationDetail();
            wad.UserCredential = new WebAuthenticationCredential();
            wad.UserCredential.Key = ApiKey.Split(';')[0]; // Replace "XXX" with the Key
            wad.UserCredential.Password = ApiKey.Split(';')[1]; // Replace "XXX" with the Password 

            return wad;
        }
        private static void SetShipmentDetails(ProcessShipmentRequest request, bool isPak, bool IsENVELOPE)
        {
            request.RequestedShipment = new RequestedShipment();
            request.RequestedShipment.ShipTimestamp = DateTime.Now; // Ship date and time
            //
            request.RequestedShipment.DropoffType = DropoffType.REGULAR_PICKUP;
            request.RequestedShipment.ServiceType = "INTERNATIONAL_PRIORITY";

            string packType = isPak ? "FEDEX_PAK" : "YOUR_PACKAGING";
            if (IsENVELOPE)
            {
                packType = "FEDEX_ENVELOPE";
            }
            request.RequestedShipment.PackagingType = packType;


            //
            request.RequestedShipment.PackageCount = "1";
        }
        private static ProcessShipmentRequest CreateShipmentRequest(Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods,ExtendArg arg)
        {
            //小于100g 以100g计费
            if (order.CustomerWeight < 100)
                order.CustomerWeight = 100;
            ///重量平分
            if (orderGoods.Any(x => x.Weight == 0) || orderGoods.Sum(x => x.Weight * x.Quantity) != order.CustomerWeight)
            {
                orderGoods.ForEach(x => x.Weight = (int)Math.Round((order.CustomerWeight) / (decimal)orderGoods.Count));
                if (order.CustomerWeight != orderGoods.Sum(x => x.Weight))
                {
                    orderGoods.Last().Weight += order.CustomerWeight - orderGoods.Sum(x => x.Weight);
                }
            }

            // Build the ShipmentRequest
            ProcessShipmentRequest request = new ProcessShipmentRequest();
            //
            request.WebAuthenticationDetail = SetWebAuthenticationDetail(channel.ApiKey);
            //
            request.ClientDetail = new ClientDetail();
            request.ClientDetail.AccountNumber = channel.ApiSecret.Split(';')[0]; // Replace "XXX" with the client's account number
            request.ClientDetail.MeterNumber = channel.ApiSecret.Split(';')[1]; // Replace "XXX" with the client's meter number 
            //
            request.TransactionDetail = new TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "***Express International Shipment Request using VC#***"; // The client will get the same value back in the response
            //
            request.Version = new VersionId();
            //
            bool isPak = channel.PublicCode.Contains("PAK") && !channel.PublicCode.Contains("非PAK");
            bool isEnvelope = channel.PublicName.Contains("ENVELOPE");
            SetShipmentDetails(request, isPak, isEnvelope);
            //
            SetSender(request, channel, order,arg);
            //
            SetRecipient(request, order);
            //
            SetPayment(request, channel);
            //
            SetLabelDetails(request);
            SetCustomsClearanceDetails(request, channel, order, orderGoods);
            //
            SetPackageLineItems(request, order, isPak);
            //
            if (!string.IsNullOrEmpty(arg.etd))
            {
                SetETD(request, arg.etd);
            }

            //
            return request;
        }
        public static byte[] SetPdfSize(byte[] data, double x, double y, float width, float height, double angle = 0, int qty = 0, double scale = 1.0)
        {
            var ms = new MemoryStream();
            PdfReader reader = new PdfReader(data);
            Document doc = new Document();
            doc.SetPageSize(new iTextSharp.text.Rectangle(width, height));


            PdfWriter writer = PdfWriter.GetInstance(doc, ms);
            doc.Open();

            PdfContentByte cb = writer.DirectContent;

            AffineTransform transform = new AffineTransform();
            transform.Translate(x, y);
            transform.Scale(scale, scale);
            if (angle > 0)
                transform.SetToRotation(angle);
            if (qty == 0)
                qty = reader.NumberOfPages;
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                doc.NewPage();
                PdfImportedPage page = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page, transform);
            }
            doc.Close();
            return ms.ToArray();
        }
        #endregion
        #region 实现接口

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

        public void CannelOrders(List<string> systemNO)
        {
            throw new NotImplementedException();
        }
        public void CannelOrdersByModel(logistics_ChannelCancel model)
        {
            DeleteShipmentRequest deleteShipmentRequest = new DeleteShipmentRequest();
            deleteShipmentRequest.DeletionControl = DeletionControlType.DELETE_ONE_PACKAGE;
            deleteShipmentRequest.ClientDetail = new ClientDetail { AccountNumber = model.ApiSecret.Split(';')[0], MeterNumber = model.ApiSecret.Split(';')[1] };
            deleteShipmentRequest.WebAuthenticationDetail = SetWebAuthenticationDetail(model.ApiKey);
            deleteShipmentRequest.TrackingId = new TrackingId { TrackingIdTypeSpecified = false, TrackingNumber = model.TrackingNumber };
            deleteShipmentRequest.Version = new VersionId();
            deleteShipmentRequest.ShipTimestamp = DateTime.Now;
            deleteShipmentRequest.ClientDetail.Localization = new Localization { LanguageCode = "EN", LocaleCode = "EM" };
            //ShipService service = new ShipService();
            string Url = "https://ws.fedex.com:443/web-services";
            ShipPortTypeClient shipPortTypeClient = new ShipPortTypeClient(EndpointConfiguration.ShipServicePort, Url);
            //代理设置
            var b = shipPortTypeClient.Endpoint.Binding as System.ServiceModel.BasicHttpBinding;
            FiddlerClient.SetProxy(b);
            try
            {
                var reply = shipPortTypeClient.deleteShipmentAsync(deleteShipmentRequest).Result.ShipmentReply;
                if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
                {
                    model.ResultState = ResultStateEnum.成功.GetValue(); model.ResultMessage ="";
                }
                else
                {
                    throw new Exception(reply.Notifications[0].Severity + reply.Notifications[0].Message);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        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)
        {
            OrderModelJudge(order);
            ServicePointManager.SecurityProtocol
               = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            ProcessShipmentRequest request = CreateShipmentRequest(channel, order, goods, arg);
            //ShipService service = new ShipService();
            string Url = "https://ws.fedex.com:443/web-services";
            ShipPortTypeClient shipPortTypeClient = new ShipPortTypeClient(EndpointConfiguration.ShipServicePort, Url);
            //代理设置
            //var b = shipPortTypeClient.Endpoint.Binding as System.ServiceModel.BasicHttpBinding;
            //FiddlerClient.SetProxy(b);

            ProcessShipmentReply reply = shipPortTypeClient.processShipmentAsync(request).Result.ProcessShipmentReply;
            if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
            {
                var data = reply.CompletedShipmentDetail.CompletedPackageDetails[0];
                return new UploadResult
                {
                    LabelData = data.Label.Parts[0].Image,
                    TrackingNumber = data.TrackingIds[0].TrackingNumber,
                    IsSuccess = true
                };
            }
            else
            {
                throw new Exception(reply.Notifications[0].Severity + reply.Notifications[0].Message);
            }
        }

        public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            byte[] d = SetPdfSize(result.LabelData, -30, -140, 293, 440, 0, 3);
            return d;
        }

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