using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;

namespace Siger.Middlelayer.Common.Helpers
{
    public class HttpHelper
    {
        private static readonly HttpClient HttpClient;
        static HttpHelper()
        {
            var handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.None,
            };
            HttpClient = new HttpClient(handler) {Timeout = TimeSpan.FromSeconds(60)};
        }
       
        public static string HttpPost(string url, string ContenType, string postData = "", Encoding encode = null,Dictionary<string,string> heads=null)
        {
            try
            {
                var webClient = new WebClient { Encoding = Encoding.UTF8 };
                if (encode != null)
                {
                    webClient.Encoding = encode;
                }
                if (heads != null && heads.Count > 0)
                {
                    foreach (var pair in heads)
                    {
                        webClient.Headers.Add(pair.Key, pair.Value);
                    }
                    
                }
                var sendData = webClient.Encoding.GetBytes(postData);
                webClient.Headers.Add(HttpRequestHeader.ContentType, ContenType);
                webClient.Headers.Add(HttpRequestHeader.ContentLength, sendData.Length.ToString());
                var data = webClient.UploadData("http://"+url, sendData);
                return webClient.Encoding.GetString(data);
            }
            catch (Exception e)
            {
                throw new Exception("post error:" + e.Message);
            }
        }
        /// <summary>
        /// 长江润发
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ContenType"></param>
        /// <param name="postData"></param>
        /// <param name="encode"></param>
        /// <param name="heads"></param>
        /// <returns></returns>
        public static (bool,string) HttpPosts(string url, string ContenType, string postData = "", Encoding encode = null, Dictionary<string, string> heads = null)
        {
            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            try
            {
                
                if (encode != null)
                {
                    webClient.Encoding = encode;
                }
                if (heads != null && heads.Count > 0)
                {
                    foreach (var pair in heads)
                    {
                        webClient.Headers.Add(pair.Key, pair.Value);
                    }

                }
                var sendData = webClient.Encoding.GetBytes(postData);
                webClient.Headers.Add(HttpRequestHeader.ContentType, ContenType);
                webClient.Headers.Add(HttpRequestHeader.ContentLength, sendData.Length.ToString());
                var data = webClient.UploadData("https://" + url, sendData);
                return (true, webClient.Encoding.GetString(data));
            }
            catch (WebException e)
            {
                using (HttpWebResponse hr = (HttpWebResponse)e.Response)
                {
                    int statusCode = (int)hr.StatusCode;
                    StringBuilder sb = new StringBuilder();
                    StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8);
                    sb.Append(sr.ReadToEnd());
                    return (false, sb.ToString());
                }
                
            }
        }

        public static string HttpPostFile(string url,string postData, Encoding encode = null)
        {
            try
            {
                var webClient = new WebClient { Encoding = Encoding.UTF8 };
                if (encode != null)
                {
                    webClient.Encoding = encode;
                }
                webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                var data = webClient.UploadFile("http://" + url, postData);
                return webClient.Encoding.GetString(data);
            }
            catch (Exception e)
            {
                throw new Exception("post error:" + e.Message);
            }
        }

        public static string Get( string url, List<KeyValuePair<string, string>> paramArray)
        {
            try
            {
                var result = "";
                url ="http://"+ url + "?" + BuildParam(paramArray);
                var response = HttpClient.GetAsync(url);
                response.Wait();
                var content = response.Result;
                if (content.IsSuccessStatusCode)
                {
                    var res = content.Content.ReadAsStreamAsync();
                    res.Wait();
                    var resu = res.Result;
                    if (resu != null)
                    {
                        var streamReader = new StreamReader(resu, Encoding.GetEncoding("utf-8"));
                        result = streamReader.ReadToEnd();
                        streamReader.Close();
                    }
                    else
                    {
                        throw new Exception("content is empty, " + content.ReasonPhrase);
                    }
                }
                else
                {
                    throw new Exception("get error:" + content.ReasonPhrase);
                }
                return result;
            }
            catch (Exception e)
            {
                throw new Exception($"get {url} failed, error:"  + e);
            }
            
        }
        /// <summary>
        /// 长江润发
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramArray"></param>
        /// <returns></returns>
        public static (bool, string) Gets(string url, string ContenType, List<KeyValuePair<string, string>> paramArray, Dictionary<string, string> heads = null)
        {
            try
            {
                var webClient = new WebClient { Encoding = Encoding.UTF8 };
                if (heads != null && heads.Count > 0)
                {
                    foreach (var pair in heads)
                    {
                        webClient.Headers.Add(pair.Key, pair.Value);
                    }
                }
                webClient.Headers.Add(HttpRequestHeader.ContentType, ContenType);
                if (paramArray.Count>0)
                {
                    url = "https://" + url + "?" + BuildParam(paramArray);
                }
                else
                {
                    url = "https://" + url ;
                }
                var content = webClient.DownloadString(url);
                return (true, content);
            }
            catch (WebException e)
            {
                using (HttpWebResponse hr = (HttpWebResponse)e.Response)
                {
                    int statusCode = (int)hr.StatusCode;
                    StringBuilder sb = new StringBuilder();
                    StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8);
                    sb.Append(sr.ReadToEnd());
                    return (false, sb.ToString());
                }
            }

        }
        private static string Encode(string content, Encoding encode = null)
        {
            if (encode == null) return content;

            return System.Web.HttpUtility.UrlEncode(content, Encoding.UTF8);

        }
        private static string BuildParam(List<KeyValuePair<string, string>> paramArray, Encoding encode = null)
        {
            string url = "";
            if (encode == null) encode = Encoding.UTF8;
            if (paramArray != null && paramArray.Count > 0)
            {
                var parms = "";
                foreach (var item in paramArray)
                {
                    parms += string.Format("{0}={1}&", Encode(item.Key, encode), Encode(item.Value, encode));
                }
                if (parms != "")
                {
                    parms = parms.TrimEnd('&');
                }
                url += parms;

            }
            return url;
        }
    }
    public class HttpPostResult
    {
        public int ret { get; set; }
        public string data { get; set; }
    }

}
