using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.ChannelApi.Base;

namespace XYY.Service.Standard.ChannelApi.eccangtms
{
    public class Api : IBaseApi
    {
        public string ServiceName => "eccangtms";

        public Task<List<BagDeclareErrosResult>> BagDeclare(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 Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        {
            var request = ConvertOrder(order, goods, channel);
            string action = "order/create/v2";
            string resultJson = Send(channel, action, request);
            var resultData = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateOrderResult>(resultJson);
            if (resultData.success)
            {
                return Task.FromResult(new UploadResult
                {
                    TrackingNumber = resultData.result.serverNo,
                    IsSuccess = true,
                    ServiceOrderNumber = resultData.result.thirdNo
                });
            }
            else
            {
                throw new Exception("下单失败" + resultData.message);
            }

        }



        public string Send(Logistics_Channel channel, string action, object sendData)
        {
            string baseUrl = channel.ApiHost;
            string requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(sendData);
            RestSharp.RestClient client = new RestSharp.RestClient(baseUrl);
            RestSharp.RestRequest request = new RestSharp.RestRequest(action, RestSharp.Method.POST);
            request.AddJsonBody(sendData);
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return response.Content;
            }
            else
            {
                throw new Exception(string.IsNullOrEmpty(response.ErrorMessage) ? response.Content : response.ErrorMessage);
            }
        }

        private static Root ConvertOrder(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel)
        {
            Root root = new Root();
            root.apiToken = channel.ApiKey;
            root.productCode = channel.ServiceChannelCode;
            root.customerNo = order.SystemNo;
            root.goodsType = 3;
            root.currencyCode = goods.FirstOrDefault().DeclareCurrency;
            root.async = 0;
            root.consigneeShipper = new ConsigneeShipper
            {
                consigneeName = order.ReceiverName,
                consigneeCompanyName = order.ReceiverName,
                consigneeCountryCode = order.ReceiverCountryCode,
                consigneeStateOrProvince = order.ReceiverState,
                consigneeCity = order.ReceiverCity,
                consigneeAddress1 = order.ReceiverStreet,
                consigneePostCode = order.ReceiverZipCode,
                consigneePhone = order.ReceiverPhone,
                shipperAddress1 = channel.SenderStreet,
                shipperArea = channel.SenderCounty,
                shipperCity = channel.SenderCity,
                shipperCompanyName = channel.SerivceCompanName,
                shipperCountryCode = channel.SenderCountryCode,
                shipperName = channel.SenderName,
                shipperPhone = channel.SenderPhone,
                shipperPostCode = channel.SenderZipCode,
                shipperStateOrProvince = channel.SenderState,
            };

            var fristGoods = goods.FirstOrDefault();
            root.boxList = new List<BoxListItem>
            {
                new BoxListItem
                {
                    boxHeight = 1,
                    boxWeight = order.CustomerWeight/1000.0,
                    boxLength = 1,
                    boxWidth=1,
                    boxQuantity = 1,
                    goodsName = fristGoods.CnName,
                    goodsNameEn = fristGoods.EnName,
                    hsCode = fristGoods.HsCode,
                    weight =order.CustomerWeight/1000.0,
                    declareUnit="件",
                    value = goods.Sum(x=>x.Quantity*x.DeclareFee),
                    quantity =1,
                    sku =fristGoods.GoodsNumber
                }
            };
            return root;
        }

        public Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            string resultData = Send(channel, "order/label", new
            {
                apiToken = channel.ApiKey,
                orderNo = result.TrackingNumber
            });
            GetLabelResult labelResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetLabelResult>(resultData);
            if (labelResult.success)
            {
                byte[] data = new System.Net.WebClient().DownloadData(labelResult.result.url);
                return Task.FromResult(data);
            }
            else
            {
                throw new Exception(labelResult.message);
            }
        }

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