using System;
using System.Collections.Generic;
using System.Text;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;
using System.Linq;
using Newtonsoft.Json;
using System.Threading.Tasks;
using RestSharp;
using Microsoft.Extensions.Logging;
using XYY.Service.Standard.ChannelApi;
using XYY.Service.Standard.ChannelApi.ChinaPost;

namespace XYY.Service.Standard.ChinaPost
{
    public partial class Api : IBaseApi
    {
        ILogger<Api> _logger;
        public Api(ILogger<Api> logger)
        {
            _logger = logger;
        }

        public Task<List<BagDeclareErrosResult>> BagDeclare(BagDeclareRequest bagDeclareRequest)
        {
            throw new NotImplementedException();
        }
        public string ServiceName { get => "ChinaPost"; }
        #region 平台旧代码

        //public async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        //{
        //    //string sign = "zrnoji5puvwgjw5d";
        //    string sign = channel.ApiKey;
        //    string orderHost = channel.ApiHost;
        //    var post = ConvertOrder(order, goods, channel);
        //    string json = JsonConvert.SerializeObject(post);
        //    RestClient client = new RestClient(orderHost);
        //    RestRequest request = new RestRequest(Method.POST);
        //    request.AddParameter("logistics_interface", json);
        //    string digest = await GetDigest(json, sign);
        //    if (string.IsNullOrEmpty(digest))
        //    {
        //        return new UploadResult { Error = "获取签名失败" };
        //    }
        //    //request.AddParameter("ecCompanyId", "91100109145248");
        //    request.AddParameter("ecCompanyId", channel.ApiSecret.Split(';')[0]);
        //    request.AddParameter("data_digest", digest);
        //    request.AddParameter("msg_type", "B2C_TRADE");
        //    request.AddParameter("data_type", "JSON");

        //    var response = client.Execute(request);
        //    if (response.StatusCode == System.Net.HttpStatusCode.OK)
        //    {
        //        var result = JsonConvert.DeserializeObject<ApiResult>(response.Content);
        //        if (!result.success)
        //        {
        //            _logger.LogError("中国邮政API下单失败:{@Request},{@Response}", request.Parameters, result);
        //            return new UploadResult { Error = "中国邮政API下单失败:" + result.reason + " " + result.msg };
        //        }
        //        else
        //        {
        //            _logger.LogError("中国邮政API下单成功:{@Response}", result);
        //            var forecastResult = Forecast(order.CustomerOrderNo, result.waybillNo);
        //            if (forecastResult.IsSuccess == true)
        //            {
        //                return new UploadResult
        //                {
        //                    IsSuccess = true,
        //                    TrackingNumber = result.waybillNo
        //                };
        //            }
        //            else
        //            {
        //                return forecastResult;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        return new UploadResult { Error = "中国邮政API下单失败:" + response.Content ?? response.ErrorMessage };
        //    }
        //}
        //private ChinaPostOrder ConvertOrder(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel)
        //{
        //    ChinaPostOrder post = new ChinaPostOrder
        //    {
        //        created_time = DateTime.Now.ToString_yyyyMMddHHmmss(),
        //        sender_no = channel.ApiSecret.Split(';')[0],
        //        wh_code = channel.ApiSecret.Split(';')[1],
        //        mailType = "xyy",
        //        logistics_order_no = order.SystemNo,
        //        batch_no = string.Empty,
        //        biz_product_no = channel.ServiceChannelCode,
        //        weight = order.CustomerWeight.ToString(),
        //        contents_total_weight = order.CustomerWeight.ToString(),
        //        contents_total_value = goods.Sum(x => x.DeclareFee * x.Quantity).ToString("0.00"),
        //        battery_flag = "0",
        //        barcode = order.SystemNo,
        //        forecastshut = "0",
        //        mail_sign = "2",
        //        declare_source = "2",
        //        declare_type = "1",
        //        declare_curr_code = "USD"

        //    };
        //    post.sender = new Sender
        //    {
        //        name = channel.SenderName,
        //        post_code = channel.SenderZipCode,
        //        phone = channel.SenderPhone,
        //        mobile = channel.SenderPhone,
        //        nation = channel.SenderCountryCode,
        //        province = channel.SenderState,
        //        city = channel.SenderCity,
        //        address = channel.SenderStreet,
        //        linker = channel.SenderName,
        //        company = channel.SenderCompany,
        //        county = channel.SenderCounty
        //    };

        //    post.receiver = new Receiver
        //    {
        //        name = order.ReceiverName,
        //        post_code = order.ReceiverZipCode,
        //        phone = order.ReceiverPhone,
        //        mobile = order.ReceiverPhone,
        //        nation = order.ReceiverCountryCode,
        //        province = order.ReceiverState,
        //        city = order.ReceiverCity,
        //        address = order.ReceiverStreet,
        //        county = order.Area,
        //        linker = order.ReceiverName

        //    };

        //    post.items = new List<ItemsItem>();

        //    foreach (var item in goods)
        //    {
        //        post.items.Add(new ItemsItem
        //        {
        //            unit = "件",
        //            cargo_no = item.HsCode,
        //            cargo_name = item.CnName,
        //            cargo_name_en = item.EnName,
        //            cargo_type_name = item.CnName,
        //            cargo_currency = item.DeclareCurrency,
        //            cargo_quantity = item.Quantity,
        //            cargo_value = item.DeclareFee,
        //            cost = item.DeclareFee,
        //            carogo_weight = item.Weight,
        //            cargo_description = item.CnName
        //        });
        //    }

        //    post.items.ForEach(x => x.carogo_weight = (int)(order.CustomerWeight / (decimal)post.items.Sum(y => y.cargo_quantity)));
        //    if (post.items.Sum(x => x.carogo_weight * x.cargo_quantity) != order.CustomerWeight)
        //    {
        //        post.items.Last().carogo_weight += order.CustomerWeight - post.items.Sum(x => x.carogo_weight * x.cargo_quantity);
        //    }

        //    return post;
        //}
        //private async Task<string> GetDigest(string body, string sign)
        //{
        //    string url = "http://47.244.232.78:9519/MD5AndBase64/Get";
        //    RestClient client = new RestClient(url);
        //    RestRequest request = new RestRequest(Method.POST);
        //    request.AddParameter("Value", body + sign);
        //    var contetn = await client.ExecuteAsync(request);
        //    if (contetn.StatusCode == System.Net.HttpStatusCode.OK)
        //    {
        //        return contetn.Content.Trim();
        //    }
        //    else
        //    {
        //        _logger.LogError("中国邮政API-获取签名失败：{url},{body},{sign}" + contetn.ErrorMessage ?? contetn.Content, url, body, sign);
        //        return null;
        //    }

        //}

        //private byte[] HexStrTobyte(string hexString)
        //{
        //    hexString = hexString.Replace(" ", "");
        //    if ((hexString.Length % 2) != 0)
        //        hexString += " ";
        //    byte[] returnBytes = new byte[hexString.Length / 2];
        //    for (int i = 0; i < returnBytes.Length; i++)
        //        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
        //    return returnBytes;
        //}

        //public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        //{
        //    IRestClient client = new RestClient(channel.LabelUrl);
        //    IRestRequest request = new RestRequest(Method.POST);
        //    request.AddParameter("ecCompanyId", channel.ApiSecret.Split(';')[0]);
        //    request.AddParameter("barCode", result.TrackingNumber);
        //    request.AddParameter("version", "2.0");
        //    request.AddParameter("pageType", "RM");
        //    string dataDigest = await GetDigest(result.TrackingNumber, channel.ApiKey);
        //    request.AddParameter("dataDigest", dataDigest);
        //    var response = await client.ExecuteAsync(request);
        //    if (response.StatusCode == System.Net.HttpStatusCode.OK)
        //    {
        //        LabelResult labelResult = JsonConvert.DeserializeObject<LabelResult>(response.Content);
        //        if (labelResult.success)
        //        {
        //            return HexStrTobyte(labelResult.data);
        //        }
        //        else
        //        {
        //            throw new Exception("面单下载失败" + labelResult.err_code + " " + labelResult.msg);
        //        }
        //    }
        //    else
        //    {
        //        throw new Exception("面单下载失败" + response.ErrorMessage ?? response.Content);
        //    }
        //}
        #endregion
        #region 东莞EUB平台
        public async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        {
            //string sign = "zrnoji5puvwgjw5d";
            string sign = channel.ApiKey;
            string orderHost = channel.ApiHost;
            var post = ConvertOrder(order, goods, channel);
            string json = JsonConvert.SerializeObject(post);
            RestClient client = new RestClient(orderHost);
            RestRequest request = new RestRequest(Method.POST);
            request.AddHeader("token", "f036ca4abe6c0a1a6d29c2ce2f382df8");
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", json, ParameterType.RequestBody);
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject<DataUploadResult>(response.Content);
                if (result.code != "0")
                {
                    if (result.msg != null && result.msg.Contains("已申请单号"))
                    {
                        System.Text.RegularExpressions.Regex regex
                            = new System.Text.RegularExpressions.Regex($".*?已申请单号(.*?)，请不要重复申请");
                        var match = regex.Match(result.msg);
                        return new UploadResult
                        {
                            IsSuccess = true,
                            TrackingNumber = match.Groups[1].Value
                        };
                    }
                    _logger.LogError("中国邮政API下单失败:{@Request},{@Response}", request.Body, result);
                    return new UploadResult { Error = "中国邮政API下单失败:" + result.msg };
                }
                else
                {
                    _logger.LogError("中国邮政API下单成功:{@Response}", result);
                    return new UploadResult
                    {
                        IsSuccess = true,
                        TrackingNumber = result.data.trackingNo
                    };
                }
            }
            else
            {
                return new UploadResult { Error = "中国邮政API下单失败:" + response.Content ?? response.ErrorMessage };
            }
        }
        private DataUploadInput ConvertOrder(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel)
        {
            DataUploadInput post = new DataUploadInput
            {
                logisticsOrderNo = order.SystemNo,
                weight = order.CustomerWeight,
                bizProductNo = channel.ServiceChannelCode.Split(";")[0],
                batteryFlag = channel.ServiceChannelCode.Split(";")[1],
            };
            post.receiver = new ReceiverInput
            {
                receiverName = order.ReceiverName,
                receiverPostCode = order.ReceiverZipCode,
                receiverPhone = order.ReceiverPhone,
                receiverMobile = order.ReceiverPhone,
                receiverNation = order.ReceiverCountryCode,
                receiverProvince = order.ReceiverState,
                receiverCity = order.ReceiverCity,
                receiverAddress = order.ReceiverStreet,
                receiverEmail = order.ReceiverEmail,

            };

            post.items = new List<ItemsInput>();

            foreach (var item in goods)
            {
                post.items.Add(new ItemsInput
                {
                    cargoNo = item.HsCode,
                    cargoName = item.CnName,
                    cargoNameEn = item.EnName,
                    cargoCurrency = item.DeclareCurrency,
                    cargoQuantity = item.Quantity,
                    cargoValue = item.DeclareFee,
                    cargoWeight = item.Weight == 0 ? order.CustomerWeight / goods.Count : item.Weight,
                    cargoSeria = item.HsCode,
                });
            }
            return post;
        }
        public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            IRestClient client = new RestClient(channel.ServiceTrackingUrl);
            IRestRequest request = new RestRequest(Method.POST);
            request.AddHeader("token", "f036ca4abe6c0a1a6d29c2ce2f382df8");
            request.AddHeader("Content-Type", "application/json");
            DrawPdfLabelInput input = new DrawPdfLabelInput();
            input.logisticsOrderNoList.Add(new OrderNo() { logisticsOrderNo = order.SystemNo, });
            string json = JsonConvert.SerializeObject(input);
            request.AddParameter("application/json", json, ParameterType.RequestBody);
            var response = await client.ExecuteAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return response.RawBytes;
            }
            else
            {
                throw new Exception("面单下载失败" + response.ErrorMessage ?? response.Content);
            }
        }
        //可以不用
        private UploadResult Forecast(string logisticsOrderNo, string trackingNo)
        {
            ReportInput reportInput = new ReportInput() { logisticsOrderNo = logisticsOrderNo, trackingNo = trackingNo };
            var client = new RestClient("http://202.105.44.92/zeus-api/user/api/order/report?logisticsOrderNo");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("token", "f036ca4abe6c0a1a6d29c2ce2f382df8");
            request.AddHeader("Content-Type", "application/json");
            string body = JsonConvert.SerializeObject(reportInput);
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            var response = client.Execute<ReportResult>(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject<ReportResult>(response.Content);
                if (result.code != "0")
                {
                    _logger.LogError("东莞邮政API预报失败:{@Request},{@Response}", request.Body, result);
                    return new UploadResult { Error = "东莞邮政API预报失败:" + result.msg };
                }
                else
                {
                    _logger.LogError("东莞邮政API预报成功:{@Response}", result);
                    return new UploadResult
                    {
                        IsSuccess = true,
                    };
                }
            }
            else
            {
                return new UploadResult { Error = "中国邮政API下单失败:" + response.Content ?? response.ErrorMessage };
            }
        }
        #endregion






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

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

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