using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Mall.Common.Plugin
{
    /// <summary>
    /// Http请求帮助类
    /// </summary>
    public class HttpHelper
    {


        /// <summary>
        /// Post提交数据
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="body">参数</param>
        /// <param name="contenttype">参数</param>
        /// <returns></returns>
        public static string HttpPost(string url, string body, string contenttype = "")
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json; charset=utf-8";
                if (contenttype != "")
                {
                    request.ContentType = contenttype;
                }
                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                var res = (HttpWebResponse)ex.Response;
                StringBuilder sb = new StringBuilder();
                StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                sb.Append(sr.ReadToEnd());
                throw new Exception(sb.ToString());
            }
        }

        /// <summary>
        /// Get获取数据
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="encode">编码方式</param>
        /// <param name="Source">来源</param>
        /// <returns></returns>
        public static string HttpGet(string url, Encoding encode, string Source, string cookie="")
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            if (!string.IsNullOrEmpty(Source))
            {
                myRequest.Referer = Source;
            }
            if (!string.IsNullOrEmpty(cookie))
            {
                myRequest.Headers.Add("cookie", cookie);
            }
            myRequest.Method = "GET";
            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), encode);
                string content = reader.ReadToEnd();
                return content;
            }
            //异常请求  
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();
                        return text;
                    }
                }
            }
        }

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>HTTP响应</returns>
        public static string HttpGet(string url)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.ContentType = "application/json";
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                return GetResponseAsString(rsp, Encoding.UTF8);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }


        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>HTTP响应</returns>
        public static string HttpPostStr(string url, string postDataStr)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/octet-stream";
            req.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = req.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                return GetResponseAsString(rsp, Encoding.UTF8);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>        
        /// <param name="postDataStr">请求地址</param>        
        /// <returns>HTTP响应</returns>
        public static string HttpPost(string url, string postDataStr)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/octet-stream";
            req.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = req.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                return GetResponseAsStringBase64(rsp, Encoding.UTF8);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsStringBase64(rsp, encoding);
            }
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }


        /// <summary>
        /// 根据地址获取经度纬度
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static string[] GetGeocoderLatitude(string address)
        {
            string apiKey = "7d9fbeb43e975cd1e9477a7e5d5e192a";
            var returnStr = new string[2] { "", "" };
            HttpClient client = new HttpClient();
            string url = "http://api.map.baidu.com/geocoder?address=" + address + "&output=json&key=" + apiKey;
            try
            {
                string apiResult = client.GetStringAsync(url).Result;
                var apiJson = JObject.Parse(apiResult);
                var resultJson = JObject.Parse(apiJson["result"].ToString());
                var locationJson = JObject.Parse(resultJson["location"].ToString());
                var lng = locationJson["lng"].ToString();//经度
                var lat = locationJson["lat"].ToString();//纬度
                returnStr[0] = lng;
                returnStr[1] = lat;
            }
            catch
            {

            }
            return returnStr;
        }

        /// <summary>
        /// 根据经纬度获取详细地址location
        /// </summary>
        /// <param name="latlng"></param>
        /// <returns></returns>
        public static string GetGeocoderAddress(string latlng) {
            string apiKey = "7d9fbeb43e975cd1e9477a7e5d5e192a";            
            HttpClient client = new HttpClient();
            string url = "http://api.map.baidu.com/geocoder?location=" + latlng + "&output=json&key=" + apiKey;
            try
            {
                string apiResult = client.GetStringAsync(url).Result;
                var apiJson = JObject.Parse(apiResult);
                var resultJson = JObject.Parse(apiJson["result"].ToString());
                var locationJson = JObject.Parse(resultJson["addressComponent"].ToString());
                var province = locationJson["province"].ToString();//省份                
                return province;
            }
            catch
            {

            }
            return "";
        }


        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>        
        /// <param name="postDataStr">请求地址</param>              
        /// <returns>HTTP响应</returns>
        public static string HttpPostForWXQRCode(string url, string postDataStr)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/octet-stream";
            req.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = req.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                return GetResponseAsStringBase64(rsp, Encoding.UTF8);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsStringBase64(rsp, encoding);
            }
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>        
        /// <param name="postDataStr">请求地址</param>              
        /// <returns>HTTP响应</returns>
        public static string HttpPostForGetWXQRCodePath(string url, string postDataStr,string path)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/octet-stream";
            req.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = req.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                return GetResponseAsStringBase64_V2(rsp, Encoding.UTF8, path);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsStringBase64_V2(rsp, encoding, path);
            }
        }


        /// <summary>
        /// 把响应流转换为文本
        /// </summary>
        /// <param name="rsp"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        private static string GetResponseAsStringBase64(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                return ReadImageForStream(stream);//转成base 64返回
            }
            catch
            {
                return "";
            }
            finally
            {
                // 释放资源                
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        /// <summary>
        /// 把响应流转换为文本
        /// </summary>
        /// <param name="rsp"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        private static string GetResponseAsStringBase64_V2(HttpWebResponse rsp, Encoding encoding, string path)
        {
            System.IO.Stream stream = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                return ReadImageForStream_V2(stream, path);
            }
            catch(Exception ex)
            {
                LogHelper.Write(ex, "GetResponseAsStringBase64_V2");
                return "";
            }
            finally
            {
                // 释放资源                
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="imgstream"></param>
        /// <returns></returns>
        public static string ReadImageForStream_V2(Stream imgstream,string path)
        {
            System.Drawing.Image result = System.Drawing.Image.FromStream(imgstream);
            System.Drawing.Bitmap bit = new System.Drawing.Bitmap(result);
            bit.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            return path;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="imgstream"></param>
        /// <returns></returns>
        public static string ReadImageForStream(Stream imgstream)
        {
            System.Drawing.Image result = System.Drawing.Image.FromStream(imgstream);
            System.Drawing.Bitmap bit = new System.Drawing.Bitmap(result);
            return bitmapToBase64(bit, System.Drawing.Imaging.ImageFormat.Png);
        }

        /// <summary>
        /// bitmap转 base64
        /// </summary>
        /// <param name="bmp1"></param>
        /// <param name="imageFormat"></param>
        /// <returns></returns>
        public static string bitmapToBase64(System.Drawing.Bitmap bmp1, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            string UserPhoto = "";
            try
            {
                using (MemoryStream ms1 = new MemoryStream())
                {
                    bmp1.Save(ms1, imageFormat);
                    byte[] arr1 = ms1.ToArray();
                    UserPhoto = Convert.ToBase64String(arr1);
                }
            }
            catch (Exception ex)
            {
                UserPhoto = "";
                LogHelper.Write(ex, string.Format("bitmapToBase64:"));
            }
            return UserPhoto;
        }
    }
}
