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)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            if (!string.IsNullOrEmpty(Source))
            {
                myRequest.Referer = Source;
            }
            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 GetResponseAsStringBase64(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                //return Common.Plugin.QRCodeHelper.ReadImageForStream(stream);//转成base 64返回
                return "";
            }
            catch (Exception)
            {
                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 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 "";
        }
    }
}
