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 Edu.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>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>        
        /// <param name="postDataStr">请求地址</param>           
        /// <param name="path">生成文件路径</param>   
        /// <param name="resultType">返回类型(0-图片路径，1-base64图片)</param>  
        /// <returns>HTTP响应</returns>
        public static string HttpPostImageToBase64(string url, string postDataStr, string path="",int resultType=0)
        {
            string imgString = "";
            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);
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.UTF8;
            if (!string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                encoding = Encoding.GetEncoding(rsp.CharacterSet);
            }
            System.IO.Stream stream = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                System.Drawing.Image result = System.Drawing.Image.FromStream(stream);
                System.Drawing.Bitmap bit = new System.Drawing.Bitmap(result);
                //图片地址
                if (resultType == 0)
                {
                    bit.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
                    imgString= path;
                }
                //base64
                else if (resultType == 1)
                {
                    MemoryStream memoryStream = new MemoryStream();
                    using MemoryStream ms1 = memoryStream;
                    bit.Save(ms1, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] arr1 = ms1.ToArray();
                    imgString = Convert.ToBase64String(arr1);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "HttpPostImageToBase64");
                imgString = "";
            }
            finally
            {
                // 释放资源                
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
            return imgString;
        }


        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>HTTP响应</returns>
        public static string HttpGet(string url)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.ContentType = "application/json";
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

            Encoding encoding = Encoding.UTF8;
            if (!string.IsNullOrWhiteSpace(rsp.CharacterSet))
            {
                encoding = Encoding.GetEncoding(rsp.CharacterSet);
            }
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                result = reader.ReadToEnd();
            }
            catch(Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, string.Format("HttpGet:url=={0}", url));
                result = "";
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
            return result;
        }
    }
}