using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using XYY.Data.Standard.Order;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;
using XYY.Service.Standard.ChannelApi.JiTu;
using XYY.Service.Standard.UserService;

namespace XYY.Service.Standard.ChannelApi.HuaLei
{
    public partial class Api : IBaseApi
    {
        public Api()
        {
        }

        public string ServiceName => "HuaLei";

        public async Task<List<BagDeclareErrosResult>> BagDeclare(BagDeclareRequest bagDeclareRequest)
        {
            var restclient = new RestClient();
            var channel = bagDeclareRequest.Channel;
            var userInfo = Login(channel.ApiKey, channel.ApiSecret, channel.ApiHost);
            List<BagDeclareErrosResult> results = new List<BagDeclareErrosResult>();
            foreach (var order in bagDeclareRequest.BatchDeclare.SelectMany(x => x.Value))
            {
                string url = $"{bagDeclareRequest.Channel.ApiHost}/updateOrderWeightByApi.htm?customerId={userInfo.customer_id}&orderNo={order.TrackingNumber}&weight={order.OPWeight / 1000.0}";
                var restRequest = new RestRequest(url, Method.GET);
                var restResult = restclient.Execute(restRequest);
                if (restResult.StatusCode == HttpStatusCode.OK)
                {
                    if (restResult.Content != "true")
                    {
                        results.Add(new BagDeclareErrosResult { TrackingNumber = order.TrackingNumber, ErrorMessage = "服务商接口更新重量失败" });
                    }
                    else
                    {
                        //订单确认
                        url = $"{bagDeclareRequest.Channel.ApiHost}/postOrderApi.htm?customerId={userInfo.customer_id}&order_customerinvoicecode={order.ServiceNo}";
                        restRequest = new RestRequest(url, Method.GET);
                        restResult = restclient.Execute(restRequest);
                        if (restResult.StatusCode == HttpStatusCode.OK)
                        {
                            if (restResult.Content != "true")
                            {
                                results.Add(new BagDeclareErrosResult { TrackingNumber = order.TrackingNumber, ErrorMessage = "服务商接口标记发货失败" });
                            }
                        }
                    }
                }
                else
                {
                    results.Add(new BagDeclareErrosResult { TrackingNumber = order.TrackingNumber, ErrorMessage = "服务商接口更新重量失败" });
                }
            }
            return results;
        }
        private async Task<string> PostMoths(string strUrl, string strParam, int channelId = 0)
        {
            try
            {
                strParam = strParam.Replace('&', ',').Replace('/', ' ').Replace('+', ' ').Replace('#', ' ');
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strUrl);
                request.Method = "POST";

                request.ContentType = "application/x-www-form-urlencoded";
                string paraUrlCoded = strParam;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                if (channelId != 134)
                    request.Timeout = 10 * 1000;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;

                response = (System.Net.HttpWebResponse)await request.GetResponseAsync();
                System.IO.Stream s;
                s = response.GetResponseStream();
                string StrDate = "";
                string strValue = "";
                Encoding code = Encoding.GetEncoding("UTF-8");
                if (strParam == "")
                {
                    code = Encoding.GetEncoding("GB2312");
                }

                StreamReader Reader = new StreamReader(s, code);
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate + "\r\n";
                }
                if (strValue.Substring(8, 1) == "\"" && strParam != "")
                {
                    Reader.Close();
                    strValue = "";
                }
                else
                {
                    Reader.Close();
                }
                return strValue;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        private string GetStateCode(string receiverStateCode)
        {

            Dictionary<string, string> pairs = new Dictionary<string, string>
                {
                   { "Andorra", "AD"},
                    { "United Arab emirates", "AE"},
                    { "Afghanistan", "AF"},
                    { "Antigua", "AG"},
                    { "Anguilla", "AI"},
                    { "Albania", "AL"},
                    { "Armenia", "AM"},
                    { "Netherlands Antilles", "AN"},
                    { "Angola", "AO"},
                    { "Antarctica", "AQ"},
                    { "Argentina", "AR"},
                    { "American Samoa", "AS"},
                    { "Austria", "AT"},
                    { "Australia", "AU"},
                    { "Aruba", "AW"},
                    { "Azerbaijan", "AZ"},
                    { "Bosnia-Herzegovina", "BA"},
                    { "Barbados", "BB"},
                    { "Bangladesh", "BD"},
                    { "Belgium", "BE"},
                    { "Burkina Faso", "BF"},
                    { "Bulgaria", "BG"},
                    { "Bahrain", "BH"},
                    { "Burundi", "BI"},
                    { "Benin", "BJ"},
                    { "Bermuda", "BM"},
                    { "Brunei", "BN"},
                    { "Bolivia", "BO"},
                    { "Bonaire, Saint-Eustatius and Saba", "BQ"},
                    { "Brazil", "BR"},
                    { "Bahamas", "BS"},
                    { "Bhutan", "BT"},
                    { "Bouvet Islands", "BV"},
                    { "Botswana", "BW"},
                    { "Belarus", "BY"},
                    { "Belize", "BZ"},
                    { "Canada", "CA"},
                    { "Cocos Islands", "CC"},
                    { "Congo Democratic, Republic Of", "CD"},
                    { "Central African Republic", "CF"},
                    { "Congo", "CG"},
                    { "Switzerland", "CH"},
                    { "Ivory coast", "CI"},
                    { "Cook islands", "CK"},
                    { "Chile", "CL"},
                    { "Cameroon", "CM"},
                    { "China", "CN"},
                    { "Colombia", "CO"},
                    { "Costa Rica", "CR"},
                    { "Cuba", "CU"},
                    { "Cape Verde", "CV"},
                    { "Curacao", "CW"},
                    { "Cyprus", "CY"},
                    { "Czech republic", "CZ"},
                    { "Germany", "DE"},
                    { "Djibouti", "DJ"},
                    { "Denmark", "DK"},
                    { "Dominica", "DM"},
                    { "Dominican republic", "DO"},
                    { "Algeria", "DZ"},
                    { "Ecuador", "EC"},
                    { "Estonia", "EE"},
                    { "Egypt", "EG"},
                    { "Eritrea", "ER"},
                    { "Spain", "ES"},
                    { "Ethiopia", "ET"},
                    { "Finland", "FI"},
                    { "Fiji", "FJ"},
                    { "Micronesia", "FM"},
                    { "Faeroe islands", "FO"},
                    { "France", "FR"},
                    { "Gabon", "GA"},
                    { "United kingdom", "GB"},
                    { "Grenada", "GD"},
                    { "Georgia", "GA"},
                    { "French Guiana", "GF"},
                    { "Ghana", "GH"},
                    { "Gibraltar", "GI"},
                    { "Greenland", "GL"},
                    { "Gambia", "GM"},
                    { "Guinea", "GN"},
                    { "Guadeloupe", "GP"},
                    { "Greece", "GR"},
                    { "Guatemala", "GT"},
                    { "Guam", "GU"},
                    { "Guyana", "GY"},
                    { "Hong kong", "HK"},
                    { "Honduras", "HN"},
                    { "Croatia", "HR"},
                    { "Haiti", "HT"},
                    { "Hungary", "HU"},
                    { "Indonesia", "ID"},
                    { "Ireland", "IE"},
                    { "Israel", "IL"},
                    { "India", "IN"},
                    { "Iraq", "IQ"},
                    { "Iceland", "IS"},
                    { "Italy", "IT"},
                    { "Jamaica", "JM"},
                    { "Jordan", "JO"},
                    { "Japan", "JP"},
                    { "Kenya", "KE"},
                    { "Kyrgyzstan", "KG"},
                    { "Cambodia", "KH"},
                    { "St. Kitts and Nevis", "KN"},
                    { "South Korea", "KR"},
                    { "Kuwait", "KW"},
                    { "Cayman islands", "KY"},
                    { "Kazakhstan", "KZ"},
                    { "Laos", "LA"},
                    { "Lebanon", "LB"},
                    { "St. Lucia", "LC"},
                    { "Liechtenstein", "LI"},
                    { "Sri lanka", "LK"},
                    { "Liberia", "LR"},
                    { "Lesotho", "LS"},
                    { "Lithuania", "LT"},
                    { "Luxembourg", "LU"},
                    { "Latvia", "LV"},
                    { "Libya", "LY"},
                    { "Morocco", "MA"},
                    { "Monaco", "MC"},
                    { "Moldova", "MD"},
                    { "Montenegro", "ME"},
                    { "Madagascar", "MG"},
                    { "Marshall islands", "MH"},
                    { "Macedonia", "MK"},
                    { "Mali", "ML"},
                    { "Mongolia", "MN"},
                    { "Macau", "MO"},
                    { "Northern Mariana islands", "MP"},
                    { "Martinique", "MQ"},
                    { "Mauritania", "MR"},
                    { "Montserrat", "MS"},
                    { "Malta", "MT"},
                    { "Mauritius", "MU"},
                    { "Maldives", "MV"},
                    { "Malawi", "MW"},
                    { "Mexico", "MX"},
                    { "Malaysia", "MY"},
                    { "Mozambique", "MZ"},
                    { "Namibia", "NA"},
                    { "New Caledonia", "NC"},
                    { "Niger", "NE"},
                    { "Nigeria", "NG"},
                    { "Nicaragua", "NI"},
                    { "Netherlands", "NL"},
                    { "Norway", "NO"},
                    { "Nepal", "NP"},
                    { "New zealand", "NZ"},
                    { "Oman", "OM"},
                    { "Panama", "PA"},
                    { "Peru", "PE"},
                    { "French Polynesia", "PF"},
                    { "Papua new guinea", "PG"},
                    { "Philippines", "PH"},
                    { "Pakistan", "PK"},
                    { "Poland", "PL"},
                    { "Palestine", "PS"},
                    { "Portugal", "PT"},
                    { "Palau", "PW"},
                    { "Paraguay", "PY"},
                    { "Qatar", "QA"},
                    { "Reunion", "RE"},
                    { "Romania", "RO"},
                    { "Serbia", "RS"},
                    { "Russia", "RU"},
                    { "Rwanda", "RW"},
                    { "Saudi Arabia", "SA"},
                    { "Seychelles", "SC"},
                    { "Sweden", "SE"},
                    { "Singapore", "SG"},
                    { "Slovenia", "SI"},
                    { "Slovak republic", "SK"},
                    { "Senegal", "SN"},
                    { "Suriname", "SR"},
                    { "El Salvador", "SV"},
                    { "Syria", "SY"},
                    { "Swaziland", "SZ"},
                    { "Turks and Caicos islands", "TC"},
                    { "Chad", "TD "},
                    { "Togo", "TG"},
                    { "Thailand", "TH"},
                    { "East Timor", "TL"},
                    { "Tunisia", "TN"},
                    { "Tonga", "TO"},
                    { "Turkey", "TR"},
                    { "Trinidad and Tobago", "TT"},
                    { "Taiwan", "TW"},
                    { "Tanzania", "TZ"},
                    { "Ukraine", "UA"},
                    { "Uganda", "UG"},
                    { "United states", "US"},
                    { "Uruguay", "UY"},
                    { "Uzbekistan", "UZ"},
                    { "St. Vincent", "VC"},
                    { "Venezuela", "VE"},
                    { "British virgin islands", "VG"},
                    { "U s virgin islands", "VI"},
                    { "Vietnam", "VN"},
                    { "Vanuatu", "VU"},
                    { "Wallis and Futuna islands", "WF"},
                    { "Samoa", "WS"},
                    { "Yemen", "YE"},
                    { "South Africa", "ZA"},
                    { "Zambia", "ZM"},
                    { "Zimbabwe", "ZW"},
                    { "Alaska", "AK"},
                    { "Alabama", "AL"},
                    { "Arkansas", "AR"},
                    { "Arizona", "AZ"},
                    { "California", "CA"},
                    { "Colorado", "CO"},
                    { "Connecticut", "CT"},
                    { "Delaware", "DE"},
                    { "Florida", "FL"},
                    { "Hawaii", "HI"},
                    { "Iowa", "IA"},
                    { "Maine", "ME"},
                    { "Michigan", "MI"},
                    { "Minnesota", "MN"},
                    { "Missouri", "MO"},
                    { "Mississippi", "MS"},
                    { "Montana", "MT"},
                    { "North Carolina", "NC"},
                    { "North Dakota", "ND"},
                    { "Nebraska", "NE"},
                    { "New Hampshire", "NH"},
                    { "New Jersey", "NJ"},
                    { "New Mexico", "NM"},
                    { "Nevada", "NV"},
                    { "Idaho", "ID"},
                    { "Illinois", "IL"},
                    { "Indiana", "IN"},
                    { "Kansas", "KS"},
                    { "Kentucky", "KY"},
                    { "Louisiana", "LA"},
                    { "Massachusetts", "MA"},
                    { "Maryland", "MD"},
                    { "South Dakota", "SD"},
                    { "Tennessee", "TN"},
                    { "Texas", "TX"},
                    { "Utah", "UT"},
                    { "Virginia", "VA"},
                    { "New York", "NY"},
                    { "Ohio", "OH"},
                    { "Oklahoma", "OK"},
                    { "Oregon", "OR"},
                    { "Pennsylvania", "PA"},
                    { "Puerto Rico", "PR"},
                    { "Rhode Island", "RI"},
                    { "South Carolina", "SC"},
                    { "Vermont", "VT"},
                    { "Washington", "WA"},
                    { "Wisconsin", "WI"},
                    { "West Virginia", "WV"},
                    { "Wyoming", "WY"},
                    { "Alberta", "AB"},
                    { "Manitoba", "MB"},
                    { "New Brunswick", "NB"},
                    { "Newfoundland", "NF"},
                    { "Nova Scotia", "NS"},
                    { "Northwest Territories", "NT"},
                    { "Nunavut", "NU"},
                    { "Ontario", "ON"},
                    { "Prince Edward Island", "PE"},
                    { "Saskatchewan", "SK"},
                    { "Yukon", "YT"},
                    { "Andaman & Nicobar (U.T)", "AN"},
                    { "Andhra Pradesh", " AP"},
                    { "Bihar", " BR"},
                    { "Chhattisgarh", " CG"},
                    { "Chandigarh (U.T.)", " CH"},
                    { "Daman & Diu (U.T.)", " DD"},
                    { "Delhi (U.T.)", " DL"},
                    { "Dadra and Nagar Haveli (U.T.)", " DN"},
                    { "Goa", " GA"},
                    { "Gujarat", " GJ"},
                    { "Himachal Pradesh", " HP"},
                    { "Haryana", " HR"},
                    { "Jharkhand", " JH"},
                    { "Jammu & Kashmir", " JK"},
                    { "Karnataka", " KA"},
                    { "Kerala", " KL"},
                    { "Lakshadweep (U.T)", " LD"},
                    { "Maharashtra", " MH"},
                    { "Assam", " AS"},
                    { "Meghalaya", " ML"},
                    { "Manipur", " MN"},
                    { "Madhya Pradesh", " MP"},
                    { "Mizoram", " MZ"},
                    { "Nagaland", " NL"},
                    { "Orissa", " OR"},
                    { "Punjab", " PB"},
                    { "Puducherry (U.T.)", " PY"},
                    { "Rajasthan", " RJ"},
                    { "Sikkim", "SK"},
                    { "Tamil Nadu", "TN"},
                    { "Tripura", " TR"},
                    { "Uttaranchal", " UA"},
                    { "Uttar Pradesh", " UP"},
                    { "West Bengal", " WB"},
                    { "Antilles Guilder", "ANG"},
                    { "Argentina Peso", "ARN"},
                    { "Barbados Dollars", "BBD"},
                    { "Bulgarian Lev", "BGN"},
                    { "Bahraini Dinars", "BHD"},
                    { "Bermuda Dollars", "BMD"},
                    { "Brunei Dollar", "BND"},
                    { "Brazilian Real", "BRL"},
                    { "Bahamian Dollar", "BSD"},
                    { "Botswana Pula", "BWP"},
                    { "Canadian Dollars", "CAD"},
                    { "Chilean Peso", "CHP"},
                    { "Cayman Dollars", "CID"},
                    { "Chinese Renminbi", "CNY"},
                    { "Colombia Peso", "COP"},
                    { "Costa Rican Colon", "CRC"},
                    { "Czech Krone", "CZK"},
                    { "UAE Dirhams", "DHS"},
                    { "Danish Krone", "DKK"},
                    { "E. Caribbean Dollars", "ECD"},
                    { "Estonia Kroon", "EEK"},
                    { "Australian Dollars", "AUD"},
                    { "Aruban Florins", "AWG"},
                    { "Hong Kong Dollars", "HKD"},
                    { "Croatian Kuna", "HRK"},
                    { "Hungarian Forint", "HUF"},
                    { "Israeli Shekel", "ILS"},
                    { "Indian Rupee", "INR"},
                    { "Jamaican Dollars", "JAD"},
                    { "Japanese Yen", "JYE"},
                    { "Kenyan Schilling", "KES"},
                    { "Kuwaiti Dinars", "KUD"},
                    { "Kazakhstan Tenge", "KZT"},
                    { "Lithuanian Litas", "LTL"},
                    { "Latvian Lats", "LVL"},
                    { "Libyan Dinar", "LYD"},
                    { "Macau Pataca", "MOP"},
                    { "Malawian Kwacha", "MWK"},
                    { "Malaysian Ringgits", "MYR"},
                    { "Mozambican Metical", "MZN"},
                    { "Namibia Dollar", "NAD"},
                    { "New Mexican Peso", "NMP"},
                    { "Egyptian Pound", "EGP"},
                    { "Euro", "EUR"},
                    { "Guatemalan Quetzal", "GTQ"},
                    { "Panama Balboa", "PAB"},
                    { "Philippine Pesos", "PHP"},
                    { "Pakistan Rupee", "PKR"},
                    { "Poland Zloty", "PLN"},
                    { "Dominican Pesos", "RDD"},
                    { "Romanian Leu", "RON"},
                    { "Indonesian Rupiah", "RPA"},
                    { "Russian Ruble", "RUB"},
                    { "Saudi Arabian Riyals", "SAR"},
                    { "Solomon Island Dollar", "SBD"},
                    { "Swedish Krona", "SEK"},
                    { "Swiss Francs", "SFR"},
                    { "Singapore Dollars", "SID"},
                    { "Slovak Koruna", "SKK"},
                    { "Swazi Lilangeni", "SZL"},
                    { "Norwegian Krone", "NOK"},
                    { "New Taiwan Dollars", "NTD"},
                    { "New Zealand Dollars", "NZD"},
                    { "Thailand Baht’s", "THB"},
                    { "Tonga Pa'anga", "TOP"},
                    { "Turkish New Lira", "TRY"},
                    { "Trinidad and Tobago Dollars", "TTD"},
                    { "Uganda Schilling", "UGX"},
                    { "UK Pounds Sterling", "GBP"},
                    { "US Dollars", "USD"},
                    { "Uruguay New Peso", "UYP"},
                    { "Venezuela Bolivar Fuerte", "VEF"},
                    { "Vietnamese Dong", "VND"},
                    { "South Korea Won", "WON"},
                    { "Western Samoa Tala", "WST"},
                    { "South-African Rand", "ZAR"},
                    { "Zambian Kwacha", "ZAR"},
                    { "Quebec", "QC"},
                    { "British Columbia", "BC"},
                    { "District of Columbia", "DC"}

                };
            if (!pairs.Keys.Any(x => x.Equals(receiverStateCode, StringComparison.CurrentCultureIgnoreCase))
                  && !pairs.Values.Any(x => x.Equals(receiverStateCode, StringComparison.CurrentCultureIgnoreCase))
                  )
            {
                return receiverStateCode.ToUpper();
            }
            else if (pairs.Keys.Any(x => x.Equals(receiverStateCode, StringComparison.CurrentCultureIgnoreCase)))
            {

                return pairs.Where(x => x.Key.Equals(receiverStateCode, StringComparison.CurrentCultureIgnoreCase)).First().Value;
            }
            else
            {
                return receiverStateCode.ToUpper();
            }
        }


        private UserInfoResult Login(string name, string password, string apiUrl)
        {
            RestClient client = new RestClient(apiUrl);
            string url = $"selectAuth.htm?username={name}&password={password}";
            RestRequest request = new RestRequest(url, Method.GET);
            IRestResponse<dynamic> result = client.Execute<dynamic>(request);
            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return null;
            }
            else
            {
                UserInfoResult data = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoResult>(result.Content);
                if (data.ack)
                {
                    return data;
                }
                else
                {
                    return null;
                }

            }
        }

        public Task<List<string>> Confims(List<OrderConfimRequest> order, Logistics_Channel channel)
        {
            throw new Exception("未实现");
        }
        // DateTime时间格式转换为Unix时间戳格式
        private int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        public async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> orderGoods, Logistics_Channel channel, ExtendArg arg)
        {
            if (channel.Id == 134)
            {
                if (order.CustomerWeight > 500)
                    order.CustomerWeight -= 500;
            }


            if (channel.PublicChanneId == 26 || channel.PublicChanneId == 126)
            {
                //e邮宝，特货e邮宝币种统一为USD
                orderGoods.ForEach(x =>
                {
                    if (x.DeclareCurrency == "EUR")
                    {
                        x.DeclareCurrency = "USD";
                    }
                }
                );
            }

            if (
                channel.Id == 512 ||
                 channel.Id == 511 ||
                channel.Id == 510 ||
                channel.Id == 227
                )
            {
                order.CustomerWeight = 100;
                orderGoods.ForEach(x =>
                {
                    if (x.HsCode != null && x.HsCode.Length < 10)
                    {
                        x.HsCode = x.HsCode.PadRight(10, '0');
                    }
                });
            }
            string streeLower = order.ReceiverStreet.ToLower().Replace(" ", "");

            UserInfoResult resultUser = Login(channel.ApiKey, channel.ApiSecret, channel.ApiHost);
            if (resultUser == null)
                throw new Exception("帐号读取失败");

            if (resultUser.ack)
            {

                decimal val = orderGoods.Sum(x => x.DeclareFee * x.Quantity);
                if (val < 15 && (order.ChannelId == 14 || order.ChannelId == 15))
                {
                    val = 15;
                }
                //华运亚通相同客单号检验
                string bgNumber = order.SystemNo;
                if (channel.Id == 199)
                {
                    bgNumber = order.SystemNo;
                }

                if (channel.Id == 164)
                {
                    bgNumber = order.SystemNo + "-" + DateTimeToStamp(DateTime.Now);
                }
                List<OrderInvoiceParamItem> items = new List<OrderInvoiceParamItem>();
                OrderData orderData = new OrderData
                {
                    buyerid = "",
                    consignee_address = order.ReceiverStreet,
                    consignee_city = order.ReceiverCity,
                    consignee_companyname = order.ReceiverName,
                    consignee_email = order.ReceiverEmail,
                    consignee_name = order.ReceiverName,
                    consignee_postcode = order.ReceiverZipCode,
                    consignee_state = order.ReceiverState,
                    consignee_telephone = order.ReceiverPhone,
                    consignee_mobile = order.ReceiverPhone,
                    country = order.ReceiverCountryCode,
                    customer_id = resultUser.customer_id,
                    customer_userid = resultUser.customer_userid,
                    order_cargoamount = val.ToString(),
                    order_customerinvoicecode = bgNumber,
                    order_returnsign = "N",
                    product_id = channel.ServiceChannelCode,
                    province = order.ReceiverState,
                    orderInvoiceParam = items,
                    consignee_taxno = order.TaxNo,
                    weight = (order.CustomerWeight / 1000.0).ToString()
                };
                //写死 南昌E速宝才有发件人信息
                if (channel.Id == 384)
                {
                    orderData.shipper_name = channel.SenderName;
                    orderData.shipper_companyname = channel.SenderCompany;
                    orderData.shipper_address1 = channel.SenderStreet;
                    orderData.shipper_city = channel.SenderCity;
                    orderData.shipper_state = channel.SenderState;
                    orderData.shipper_postcode = channel.SenderZipCode;
                    orderData.shipper_country = channel.SenderCountryCode;
                    orderData.shipper_telephone = channel.SenderPhone;
                }
                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 (receiverCountryCode.Any(x => x == order.ReceiverCountryCode)
                    && channel.Id != 300 && channel.Id != 199
                     && channel.Id != 412
                    && channel.Id != 285 && channel.Id != 286
                    && channel.Id != 379 && channel.Id != 512 && channel.Id != 511 && channel.Id != 510 && channel.Id != 227 && channel.Id != 531)
                {
                    orderData.shipper_taxnotype = "IOSS";
                    if (string.IsNullOrEmpty(order.ioss))
                    {
                        throw new Exception("未提供税号");
                    }
                    orderData.shipper_taxno = order.ioss;
                    orderData.shipper_taxnocountry = order.ReceiverCountryCode;
                }
                else if (channel.Id == 510 || channel.Id == 512 || channel.Id == 511 || channel.Id == 227 || channel.Id == 531)
                {
                    orderGoods.ForEach(x =>
                    {
                        x.DeclareCurrency = "USD";
                    });
                    if (string.IsNullOrEmpty(order.ReceiverState))
                    {
                        order.ReceiverState = order.ReceiverCity;
                    }
                    orderData.shipper_taxnotype = "IOSS";
                    orderData.consignee_taxno = string.Empty;
                    orderData.shipper_taxno = "IM2500000320";
                }
                if (order.CreateOrderChannelId == 26 || order.CreateOrderChannelId == 126)
                {
                    //e邮宝，特货e邮宝币种统一为USD
                    orderGoods.ForEach(x =>
                    {
                        if (x.DeclareCurrency == "EUR")
                        {
                            x.DeclareCurrency = "USD";
                        }
                    }
                    );
                }
                int qty = orderGoods.Sum(x => x.Quantity);
                orderGoods.ForEach(x =>
                {
                    x.Weight = order.CustomerWeight / qty;
                });
                foreach (Order_OrderGoods p in orderGoods)
                {
                    if (items.Any(x => x.hs_code == p.HsCode))
                    {
                        OrderInvoiceParamItem item = items.FirstOrDefault(x => x.hs_code == p.HsCode);
                        item.invoice_amount = (decimal.Parse(item.invoice_amount) + Math.Round(p.DeclareFee * p.Quantity, 2)).ToString("0.0");
                        item.invoice_pcs = (int.Parse(item.invoice_pcs) + p.Quantity).ToString();
                    }
                    else
                    {
                        items.Add(new OrderInvoiceParamItem
                        {
                            hs_code = p.HsCode,
                            invoice_amount = Math.Round(p.DeclareFee * p.Quantity, 2).ToString("0.0"),
                            invoice_pcs = p.Quantity.ToString(),
                            invoice_title = p.EnName,
                            invoice_weight = (p.Weight / 1000m).ToString(),
                            invoice_currency = p.DeclareCurrency?.ToUpper(),
                            sku = p.CnName
                        });
                    }
                }
                orderData.order_cargoamount = items.Sum(x => decimal.Parse(x.invoice_amount)).ToString("0.0");


                string jsonp = JsonConvert.SerializeObject(orderData);

                OrderResult orderResult = null;
                for (int i = 0; i < 3; i++)
                {
                    orderResult = await updateData(channel.ApiHost, jsonp, channel.Id);
                    if (orderResult.ack || (Uri.UnescapeDataString(orderResult.message)) != "异常:DHL未返回面单")
                    {
                        break;
                    }
                }
                if (orderResult.ack)
                {
                    return new UploadResult
                    {
                        TrackingNumber = orderResult.tracking_number,
                        ServiceOrderNumber = orderResult.order_id,
                        IsSuccess = true,

                    };
                }
                else
                {
                    throw new Exception(Uri.UnescapeDataString(orderResult.message));
                }
            }
            else
            {
                throw new Exception("帐号读取失败");
            }
        }
        public async Task<OrderResult> updateData(string apiHost, string jsonp, int channelId)
        {
            string strOrderResult = await PostMoths(apiHost + "/createOrderApi.htm?", "param=" + jsonp, channelId);
            OrderResult orderResult = JsonConvert.DeserializeObject<OrderResult>(strOrderResult);
            return orderResult;
        }



        public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            string pdfURL = channel.ServiceTrackingUrl + "/order/FastRpt/PDF_NEW.aspx?PrintType=lab10_10&Format=" + "&order_id=" + result.ServiceOrderNumber;

            if (string.IsNullOrEmpty((result.TrackingNumber)))
            {
                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 > 1 * 1024)
                {
                    //面单大于5k时返回
                    break;
                }
                //3秒后重试一次
                System.Threading.Thread.Sleep(3 * 1000);
            }
            if (data == null || data.Length < 1 * 1024)
            {
                throw new Exception("面单获取失败，请稍候重试");
            }
            return data;
        }

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

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