using AspectCore.DynamicProxy;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Crmf;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.PDF;
using XYY.Data.Standard.Order;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.MpsOrder;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;

namespace XYY.Service.Standard.ChannelApi.HuoYing
{
    public partial class Api : IBaseApi
    {
        public string ServiceName => "HuoYing";
        ILogger<Api> _logger;
        public Api(ILogger<Api> logger)
        {
            _logger = logger;
        }

        public Task<List<Base.BagDeclareErrosResult>> BagDeclare(Model.Standard.Order.BagDeclareRequest bagDeclareRequest)
        {
            throw new NotImplementedException();
        }

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

        public void CannelOrdersByModel(logistics_ChannelCancel logistics_ChannelCancel)
        {
            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)
        {
            var post = await ConvertOrder(order, goods, channel, arg);
            string json = JsonConvert.SerializeObject(post);
            RestClient client = new RestClient(channel.ApiHost + "api/v1/common/createorder");
            RestRequest request = new RestRequest(Method.POST);
            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 == 1)
                {
                    _logger.LogError("HuoYing下单成功:{@Response}", result);
                    var uploadResult = new UploadResult
                    {
                        DownloadUrls = result.data.FirstOrDefault().packageResults.Select(x => x.graphicImage).ToList(),
                        IsSuccess = true,
                        MPSTrackings = new Dictionary<string, string>(),
                        TrackingNumber = result.data.FirstOrDefault().trackingNo,
                    };
                    for (int i = 0; i < result.data.FirstOrDefault().packageResults.Count; i++)
                    {
                        uploadResult.MPSTrackings.Add(arg.Order.Boxs[i].BoxServiceNumber, result.data.FirstOrDefault().packageResults[i].trackingNumber);
                    }
                    return uploadResult;
                }
                else
                {
                    throw new Exception($"HuoYing下单失败:{result.msg}");
                }
            }
            else
            {
                throw new Exception($"HuoYing下单失败:{response.Content ?? response.ErrorMessage}");
            }
        }

        public async Task<byte[]> DrawPdfLabel(Base.UploadResult result, Model.Standard.Channel.Logistics_Channel channel, Model.Standard.Order.Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            List<byte[]> Datas = new List<byte[]>();
            foreach (var item in result.DownloadUrls)
            {
                Datas.Add(Convert.FromBase64String(item));
            }
            if (Datas.Count == 1) { return Datas[0]; }
            else if (Datas.Count > 1)
            {
                string tempDict = System.IO.Path.Combine(System.AppContext.BaseDirectory, "temp");
                if (!System.IO.Directory.Exists(tempDict))
                    System.IO.Directory.CreateDirectory(tempDict);
                string tempFilePath = System.IO.Path.Combine(tempDict, result.TrackingNumber + ".pdf");
                PDFHelper.MergePDFFiles(tempFilePath, Datas, false);
                var margeDatas = System.IO.File.ReadAllBytes(tempFilePath);
                System.IO.File.Delete(tempFilePath);
                return margeDatas;
            }
            else
            {
                throw new Exception("面单获取失败，一张面单都未获取到");
            }
        }

        public Task<string> GetTrackingNumber(string SystemNo, string TrackingNumber, string ServiceOrderNo, Logistics_Channel channel)
        {
            throw new NotImplementedException();
        }
        private async Task<DataUploadRequest> ConvertOrder(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        {
            DataUploadRequest post = new DataUploadRequest();
            if (!string.IsNullOrEmpty(order.ReceiverStreet))
                order.ReceiverStreet = order.ReceiverStreet.Trim();
            string[] address = order.ReceiverStreet.Split(',');
            if (address.Length > 2)
            {
                throw new Exception("地址中仅可含一个逗号用于区分地址1/地址2");
            }
            RequestData requestData = new RequestData()
            {
                supno = channel.ApiKey.Split(";")[0],
                suppass = channel.ApiKey.Split(";")[1],
                appkey = channel.ApiSecret,
                organo = GetCommonData._getSTOCK().FirstOrDefault().valuecode,
                packno = order.CustomerOrderNo.Replace("/", "")+"R",
                channeltype = channel.ServiceChannelCode.Split(";")[0],
                channelprice = channel.ServiceChannelCode.Split(";")[1],
                delcompanynm = order.ReceiverCompany,
                contactsby = order.ReceiverName,
                dest = GetCommondData("DEST", order.ReceiverCountryCode, channel),
                city = order.ReceiverCity,
                address1 = address[0],
                address2 = address.Count() > 1 ? address[1] : "",
                phone = order.ReceiverPhone,
                postno = order.ReceiverZipCode,
                smatno = "",
                declaration = GetCommonData._getBAOGUAN(arg.Order.DeclarationMethod).valuecode,
                sdcompanynm = order.SenderCompany,
                sendby = order.SenderName,
                sendmobi = order.SenderPhone,
                sendbyaddress = order.SenderStreet,
            };
            post.data = requestData;
            //box 信息
            foreach (var item in arg.Order.Boxs)
            {
                OrderDetailListItem ordersmatlist = new OrderDetailListItem()
                {
                    mlength = item.OpLength,
                    mwidth = item.OpWidth,
                    mheight = item.OpHeight,
                    mweit = item.OpInputWeight,
                    jobno = item.BoxNumber,
                };
                foreach (var good in item.Goods)
                {
                    OrdersmatlistItem ordersmatlistItem = new OrdersmatlistItem()
                    {
                        jobid = item.BoxNumber,
                        qty = good.Quantity,
                        value = good.GoodsValue,
                        productch = good.CnName,
                        producten = good.EnName,
                        pinpai = good.Brand,
                        hscode = good.HsCode,
                        jingweit = good.Weight,
                        qgbibie = good.Currency,
                        zwmat = good.Meterial,
                        zwuse = good.Usage,
                        smatnos = "",
                    };
                    ordersmatlist.ordersmatlist.Add(ordersmatlistItem);
                }
                requestData.orderDetailList.Add(ordersmatlist);
            }
            return post;
        }
        private List<string> SubstringStreet(string ReceiverStreet)
        {
            List<string> address = new List<string>() { };
            string tempstring = string.Empty;
            if (ReceiverStreet.Length < 30) { address.Add(ReceiverStreet); return address; }

            if (ReceiverStreet.Length > 30) { address.Add(ReceiverStreet.Substring(0, 30)); tempstring = ReceiverStreet.Substring(30, ReceiverStreet.Length - 30); }
            if (tempstring.Length > 30) { address.Add(tempstring.Substring(0, 30)); tempstring = tempstring.Substring(30, tempstring.Length - 30); }
            if (tempstring.Length > 30) { address.Add(tempstring.Substring(0, 30)); tempstring = tempstring.Substring(30, tempstring.Length - 30); }
            if (tempstring.Length < 30) { address.Add(tempstring); }
            return address;
        }

        private string GetCommondData(string code, string matchString, Logistics_Channel channel)
        {

            var client = new RestClient(channel.ApiHost + "api/v1/common/getbasedata");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            CommonDataRequst body = new CommonDataRequst()
            {
                FACTNO = "003",
                SUPNO = channel.ApiKey.Split(";")[0],
                SUPPASS = channel.ApiKey.Split(";")[1],
                APPKEY = channel.ApiSecret,
                TYPENO = code,
            };
            request.AddJsonBody(body);
            IRestResponse response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject<CommonData>(response.Content);
                if (result.code == 1)
                {
                    var matchResult = result.data.details.Where(x => x.valueot == matchString)?.FirstOrDefault();
                    if (matchResult != null)
                    {
                        return matchResult.valuecode;
                    }
                    else
                    {
                        throw new Exception($"HuoYing匹配基础数据失败，[{code}]:{matchString}");
                    }
                }
                else
                {
                    throw new Exception($"HuoYing获取基础数据失败，[{code}]:{result.msg}");
                }
            }
            else
            {
                throw new Exception($"HuoYing获取基础数据失败，[{code}]:{response.Content ?? response.ErrorMessage}");
            }
        }
    }
}
