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.HuoDou
{
    public class Api : IBaseApi
    {
        public string ServiceName => "HuoDou";

        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 async Task<UploadResult> DataUpload(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel, ExtendArg arg)
        {
            var req = createOrderRequestData(order, goods, channel);
            var response = await Send<dynamic>(req, "api/erp/createOrder.json", channel);
            if (response.success == "true")
            {
                return new UploadResult
                {
                    IsSuccess = true,
                    TrackingNumber = response.trackingNo
                };
            }
            else
            {
                throw new Exception("下单失败" + response.message);
            }
        }

        public Dictionary<string, string> createOrderRequestData(Order_Order order, List<Order_OrderGoods> goods, Logistics_Channel channel)
        {
            string[] codes = channel.ServiceChannelCode.Split(';');
            if (codes.Length != 3)
                throw new Exception("服务商代码由fromType;shipType;schemeId组成，请联系技术处理");
            int fromType = 0;
            int shipType = 0;
            if (!int.TryParse(codes[0], out fromType)
                || !int.TryParse(codes[1], out shipType)
                || string.IsNullOrEmpty(codes[2]))
            {
                throw new Exception("服务商代码由fromType;shipType;schemeId组成，请联系技术处理");
            }
            string schemeId = codes[2];

            dynamic reqBody = new
            {
                sender = new
                {
                    contract = channel.SenderName,
                    comName = channel.SenderCompany,
                    provinceName = channel.SenderState,
                    cityName = channel.SenderCity,
                    countyName = string.Empty,
                    addr = channel.SenderStreet,
                    tel = channel.SenderPhone,
                    mobile = channel.SenderPhone,
                    zip = channel.SenderZipCode
                },
                contract = new
                {
                    contract = order.ReceiverName,
                    regionShortnameEn = order.ReceiverCountryCode,
                    provinceName = order.ReceiverState ?? order.ReceiverCity,
                    cityName = order.ReceiverCity,
                    addr = order.ReceiverStreet,
                    tel = order.ReceiverPhone,
                    zip = order.ReceiverZipCode,
                },
                custOrderNo = order.SystemNo,
                schemeId = schemeId,
                expand = new
                {
                    goodsTypeId = 1
                },
                details = goods.Select(x =>
                {
                    return new
                    {
                        goodsNameEn = x.EnName,
                        hsc = x.HsCode,
                        length = 1.0,
                        width = 1.0,
                        height = 1.0,
                        weight = order.CustomerWeight / 1000.0,
                        numberOfEach = 1,
                        singleValue = 1.0,
                        goodsName = x.CnName
                    };
                }).Take(1)
            };

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(reqBody);

            var req = new Dictionary<string, string>()
            {
                {"fromType" , fromType.ToString() },
                {"shipType" , shipType.ToString() },
                {"param" , json }
            };
            return req;
        }

        public async Task<string> AuthResult(Logistics_Channel channel)
        {
            var result = await Send<SelectAuthResult>(new Dictionary<string, string>
            {
                { "username" ,channel.ApiKey },
                { "userpassword" ,channel.ApiSecret}
            }, "api/erp/selectAuth.json", channel);

            if (result.success)
            {
                return result.tokenCode + "|" + result.userId;
            }
            else
            {
                throw new Exception($"获取授权信息失败{GetAuthError(result.code)}");
            }

        }

        public string GetAuthError(int code)
        {
            switch (code)
            {
                case 1001011:
                    return "信息未填写完整";
                case 1002011:
                    return "账号或密码错误";
                default:
                    return "未知";
            }
        }


        public async Task<T> Send<T>(Dictionary<string, string> dict, string action, Logistics_Channel channel)
        {
            RestSharp.RestClient client = new RestSharp.RestClient(channel.ApiHost);
            RestSharp.RestRequest request = new RestSharp.RestRequest(action, method: RestSharp.Method.POST);
            foreach (var k in dict)
            {
                request.AddParameter(k.Key, k.Value);
            }
            //request.AddJsonBody(obj);
            //添加请求头
            if (action != "api/erp/selectAuth.json")
            {
                var token = await AuthResult(channel);
                request.AddHeader("thirdParty", token);
            }
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response.Content);
            }
            else
            {
                throw new Exception("请求失败：" + (response.ErrorMessage ?? response.Content));
            }
        }

        public Task<byte[]> DrawPdfLabel(UploadResult result, Logistics_Channel channel, Order_Order order, List<Order_OrderGoods> orderGoods)
        {
            throw new NotImplementedException();
        }

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