using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
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/x-www-form-urlencoded";
       
            //req.Headers.Add("Accept", "application/json");
            //req.Headers.Add("Content-Type", "application/json");
            byte[] data = Encoding.UTF8.GetBytes(postDataStr);

            req.ContentLength = data.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);

                reqStream.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="url"></param>
        /// <param name="postDataStr"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string HttpPostForGetWXQRCodePathSmallShops(string url, string postDataStr, string path,string ssPhoto)
        {
            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_V3(rsp, Encoding.UTF8, path, ssPhoto);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsStringBase64_V3(rsp, encoding, path, ssPhoto);
            }
        }


        /// <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="rsp"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        private static string GetResponseAsStringBase64_V3(HttpWebResponse rsp, Encoding encoding, string path,string ssPhoto)
        {
            System.IO.Stream stream = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                return ReadImageForStream_V3(stream, path, ssPhoto);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "GetResponseAsStringBase64_V3");
                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;
        }

        /// <summary>
        /// 获取小程序码  并且替换中间图标
        /// </summary>
        /// <param name="imgstream"></param>
        /// <returns></returns>
        public static string ReadImageForStream_V3(Stream imgstream, string path, string ssPhoto)
        {
            System.Drawing.Image result = System.Drawing.Image.FromStream(imgstream);
            if (!string.IsNullOrEmpty(ssPhoto)) {
                WebRequest wreq = WebRequest.Create(ssPhoto);
                HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
                Stream s = wresp.GetResponseStream();
                var img = System.Drawing.Image.FromStream(s);
                result = CombinImage(result, img);
            }

            System.Drawing.Bitmap bit = new System.Drawing.Bitmap(result);
            bit.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            return path;
        }

        /// <summary>
        /// 图片处理为圆形
        /// </summary>
        /// <param name="img"></param>
        /// <param name="rec"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static Image CutEllipse(Image img, Rectangle rec, Size size)
        {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            try
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
                    {
                        br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.FillEllipse(br, new Rectangle(Point.Empty, size));
                    }
                }
            }
            catch (Exception)
            {
                return img;
            }
            return bitmap;
        }

        /// <summary>
        /// 调用此函数后使此两种图片合并，类似相册，有个
        /// 背景图，中间贴自己的目标图片
        /// </summary>
        /// <param name="imgBack">粘贴的源图片</param>
        /// <param name="destImg">粘贴的目标图片</param>
        public static Image CombinImage(Image imgBack, Image img)
        {
            int Size = img.Width;
            if (img.Height < img.Width)
            {
                Size = img.Height;
            }
            if (Size > imgBack.Width) {
                Size = imgBack.Width;
            }
            img = CutEllipse(img, new Rectangle(0, 0, Size, Size), new Size(Size, Size));
            Graphics g = Graphics.FromImage(imgBack);
            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);   //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
                                                                         //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框
                                                                         //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
            g.DrawImage(img, imgBack.Width / 2 - Size / 2, imgBack.Width / 2 - Size / 2, Size, Size);
            GC.Collect();
            return imgBack;
        }


        public static string CombinImage2()
        {
            var imgBack = Image.FromFile("E:/LDWork/LiuDongWork/MallFB/upfile/temporary/123.jpg");
            //var img = Image.FromFile("https://wx.qlogo.cn/mmopen/vi_32/6d2FEzo0bpq8NcQ5sica1EictZLcaeCMboVnxdSqnaxuVPdp0GVuDDRJicfIUQnDibEJSEApbQ81icvBtSU80Pwkddw/132");    //微店图片
            WebRequest wreq = WebRequest.Create("https://wx.qlogo.cn/mmopen/vi_32/6d2FEzo0bpq8NcQ5sica1EictZLcaeCMboVnxdSqnaxuVPdp0GVuDDRJicfIUQnDibEJSEApbQ81icvBtSU80Pwkddw/132");
            HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
            Stream s = wresp.GetResponseStream();
            var img = System.Drawing.Image.FromStream(s);

            //img = CutEllipse(img, new Rectangle(120, 120, r, r), new Size(r, r));
            img = CutEllipse(img, new Rectangle(0, 0, img.Width, img.Height), new Size(img.Width, img.Height));
            Graphics g = Graphics.FromImage(imgBack);
            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);   //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
                                                                         //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框
                                                                         //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
            g.DrawImage(img, imgBack.Width / 2 - img.Width / 2, imgBack.Width / 2 - img.Width / 2, img.Width, img.Height);
            GC.Collect();

            System.Drawing.Bitmap bit = new System.Drawing.Bitmap(imgBack);
            bit.Save("E:/LDWork/LiuDongWork/MallFB/upfile/temporary/123333333.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            return "";
        }
    }
}
