using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.AddressHelper;
using XYY.Service.Standard.ChannelApi.Base;

namespace XYY.Service.Standard.ChannelApi.LaoChen_ACI
{
    public partial class Api : IBaseApi
    {
        ILogger<Api> _logger;

        public Api(ILogger<Api> logger)
        {
            _logger = logger;
        }

        public string ServiceName => "LaoChenACI";

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

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

        public async Task<List<string>> Confims(List<OrderConfimRequest> order, Logistics_Channel channel)
        {
            string manifest = "https://api.tracktrace360.com/v1/ac/manifest";
            string manifestedOn = DateTime.Now.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
            BagRequest breq = new BagRequest
            {
                manifestedOn = manifestedOn,
                parcels = order.Select(x => new BagParcels { refNbr = x.OrderNo }).ToList()
            };
            //31bf23440b1e0a252d3bc66ea83c5df5
            String key = channel.ApiKey;
            string api = manifest;
            RestSharp.RestClient client = new RestSharp.RestClient(api);
            RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
            request.AddHeader("apikey", key);
            request.AddJsonBody(breq);
            var response = await client.ExecuteAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var content = response.Content;
                var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<BagResult>(response.Content);
                if (resp.code == 10000)
                {
                    if (resp.data.errors != null && resp.data.errors.Length > 0)
                    {
                        List<string> erros = new List<string>();
                        foreach (var item in resp.data.errors)
                        {
                            erros.Add(item.Split(':')[0]);
                        }
                        return erros;
                    }
                    else
                    {
                        //全部成功
                        return new List<string>();
                    }
                }
                else
                {
                    _logger.LogError(ServiceName + "预报失败 {@error}", response.ErrorMessage ?? response.Content);

                    //全部出错
                    return order.Select(x => x.OrderNo).ToList();
                }
            }
            else
            {
                _logger.LogError(ServiceName + "预报失败 {@error}", response.ErrorMessage ?? response.Content);
                //全部出错
                return order.Select(x => x.OrderNo).ToList();
            }
        }

        public async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        {
            USAddressCheck addressCheck = new USAddressCheck();
            addressCheck.CheckUSOrder(order);
            string serviceChannelCode = channel.ServiceChannelCode.Split(';')[0];
            string poa = channel.ServiceChannelCode.Split(';')[1];
            Request req = new Request
            {
                serviceCode = serviceChannelCode,
            };

            req.parcel = new Parcel();
            string pid = order.SystemNo;

            req.parcel.orderNbr = pid;
            req.parcel.consignee = new ConsigneeInfo();
            req.parcel.consignee.name = order.ReceiverName;
            req.parcel.consignee.phone = order.ReceiverPhone;
            req.parcel.consignee.street1 = order.ReceiverStreet;
            req.parcel.consignee.city = order.ReceiverCity;
            req.parcel.consignee.province = order.ReceiverState;
            req.parcel.consignee.postalCode = order.ReceiverZipCode;
            req.parcel.consignee.countryCode = order.ReceiverCountryCode;


            req.parcel.poa = poa;
            req.parcel.weight = new Weight
            {
                value = order.CustomerWeight,
                unit = "G"
            };

            string api = channel.ApiHost;
            RestSharp.RestClient client = new RestSharp.RestClient(api);
            RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
            request.AddHeader("apikey", channel.ApiKey);
            request.AddJsonBody(req);
            var response = await client.ExecuteAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    var content = response.Content;
                    var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseInfo>(response.Content);
                    string msg = resp.msg;
                    if (resp.code == 10000)
                    {
                        string downloadUrl = string.Empty;
                        string trackingNum = string.Empty;
                        string destinationCode = string.Empty;
                        if (resp.data != null)
                        {
                            var data = resp.data;
                            downloadUrl = data.pdf;
                            trackingNum = data.barcode;
                            destinationCode = data.poa;
                        }
                        else
                        {
                            throw new Exception("无法解释渠道返回信息");
                        }
                        return new UploadResult
                        {
                            DownloadUrl = downloadUrl,
                            TrackingNumber = trackingNum,
                            ServiceOrderNumber = resp.data.code,
                            IsSuccess = true,
                            destinationCode = destinationCode
                        };
                    }
                    else if (resp.code == 30001)
                    {
                        throw new Exception($"下单失败：认证错误(30001) {msg}");
                    }
                    else if (resp.code == 40001)
                    {
                        throw new Exception($"下单失败：包裹地址检验失败(40001) {msg}：" + resp.data.ToString());
                    }
                    else if (resp.code == 40002)
                    {
                        throw new Exception($"下单失败：包裹地址检验失败(40002) {msg}：收件人街道或邮编有误不匹配");
                    }
                    else if (resp.code == 40003)
                    {
                        throw new Exception($"下单失败：参考单号重量(40003) {msg}");
                    }
                    else if (resp.code == 50001)
                    {
                        if (msg != null && msg.Contains("Insufficient Balance"))
                            msg = "Insufficient Balance";

                        throw new Exception($"下单失败：系统错误(50001) {msg}");
                    }
                    else
                    {
                        throw new Exception($"未知错误 {msg}");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("解析json失败" + response.Content);
                }
            }
            else
            {
                throw new Exception(response.ErrorMessage ?? response.Content);
            }


        }

        public async Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            byte[] data = null;
            for (int i = 0; i < 3; i++)
            {
                System.Net.WebClient client = new System.Net.WebClient();
                try
                {
                    string src = result.DownloadUrl.Replace("\\", "");
                    data = await client.DownloadDataTaskAsync(src);
                }
                catch (Exception ex)
                {
                }
                if (data != null && data.Length > 3000)
                {
                    break;
                }
                else
                {
                    //超过10KB为有效文件，否则线程等待2s
                    System.Threading.Thread.Sleep(4000);
                }
            }
            if (data.Length < 3000)
            {
                throw new Exception("面单下载失败，请稍候重试," + result.DownloadUrl);
            }
            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();
        }
    }
}
