using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Wicture.DbRESTFul;

namespace JiaZhiQuan.Common.KDNiao
{
    /// <summary>
    /// 快递鸟帮助类
    /// </summary>
    public static class KDNiaoHelper
    {
        /// <summary>
        /// 轨迹订阅地址
        /// </summary>
        private static string trackApiUrl = "https://api.kdniao.com/api/dist";

        private static string trackInfoApiUrl = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

        /// <summary>
        /// 轨迹订阅接口
        /// </summary>
        /// <param name="request"></param>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static async Task<KDNiaoTrackResponse> SubscribeTrack(KDNiaoRequest request, IHttpClientFactory httpClientFactory)
        {
            var res = new KDNiaoTrackResponse();
            try
            {
                using (var httpClient = httpClientFactory.CreateClient())
                {
                    var content = new StringContent($"RequestData={request.RequestData}&RequestType={(int)request.RequestType}&EBusinessID={request.EBusinessID}&DataSign={request.DataSign}&DataType={request.DataType}", Encoding.UTF8, "application/x-www-form-urlencoded");
                    var response = await httpClient.PostAsync(trackApiUrl, content);
                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        res = JsonConvert.DeserializeObject<KDNiaoTrackResponse>(responseContent);
                    }
                    else
                    {
                        LoggerManager.Logger.Error($"调用快递鸟轨迹订阅失败: {response}");
                    }
                }
                return res;
            }
            catch (System.Exception ex)
            {
                LoggerManager.Logger.Error($"调用快递鸟轨迹订阅失败: {ex.Message}");
                return res;
            }
        }

        /// <summary>
        /// 即时查询、快递查询接口 RequestType不同
        /// </summary>
        /// <param name="request"></param>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static async Task<KDNiaoTrackDataItem> QueryTrackingInfo(KDNiaoRequest request, IHttpClientFactory httpClientFactory)
        {
            var res = new KDNiaoTrackDataItem();
            try
            {
                using (var httpClient = httpClientFactory.CreateClient())
                {
                    var content = new StringContent($"RequestData={request.RequestData}&RequestType={(int)request.RequestType}&EBusinessID={request.EBusinessID}&DataSign={request.DataSign}&DataType={request.DataType}", Encoding.UTF8, "application/x-www-form-urlencoded");
                    var response = await httpClient.PostAsync(trackInfoApiUrl, content);
                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        res = JsonConvert.DeserializeObject<KDNiaoTrackDataItem>(responseContent);
                    }
                    else
                    {
                        LoggerManager.Logger.Error($"调用快递鸟即时查询接口失败: {response}");
                    }
                }
                return res;
            }
            catch (System.Exception ex)
            {
                LoggerManager.Logger.Error($"调用快递鸟即时查询接口失败: {ex.Message}");
                return res;
            }
        }


        /// <summary>
        /// 快递在途查询
        /// </summary>
        /// <param name="LogisticCode">快递单号</param>
        /// <param name="ShipperCode">快递公司编码，需维护进系统</param>
        /// <param name="receivePhone">收货人手机号码，会自动截取为后4位</param>
        /// <returns></returns>
        public static async Task<KDNiaoTrackDataItem> QueryLogistics(string LogisticCode, 
            string ShipperCode,string receivePhone, string EBusinessID, string ApiKey,
            IHttpClientFactory httpClientFactory) {
            var resp = new KDNiaoTrackDataItem();
            string CustomerName = null;
            try {
                if ("SF".Equals(ShipperCode)) {
                    if (receivePhone == null || receivePhone.Length < 4) {
                        throw new System.Exception("当ShipperCode为顺风时，需提供收货人手机号后4位");
                    }
                    CustomerName = receivePhone[^4..];
                }
                var requestData = new {
                    LogisticCode,
                    ShipperCode,
                    CustomerName
                };
                var data = JsonConvert.SerializeObject(requestData);
                KDNiaoRequest request = new KDNiaoRequest(EBusinessID, ApiKey,
                    data, KDNiaoRequestType.即时查询_增值版);
                resp = await QueryTrackingInfo(request, httpClientFactory);
            } catch(Exception ex) {
                LoggerManager.Logger.Error("快递查询失败：" + ex.Message);
            }            
            if (null == resp.Traces) { resp.Traces = new System.Collections.Generic.List<KDNiaoTrace>(); }
            return resp;
        }
    }
}
