namespace CrazyStudio.Core.Common
{
    public class HttpRequestHelper
    {/// <summary>
     /// GET
     /// </summary>
     /// <param name="url">发送请求的URL</param>
     /// <param name="param">请求参数，请求参数应该是 name1=value1&name2=value2 的形式。（不用带问号）</param>
     /// <returns>所代表远程资源的响应结果</returns>
        public static async Task<string> Get(string url, string param)
        {
            string result = string.Empty;
            try
            {
                string urlNameString = url + "?" + param;
                using (var httpClient = new HttpClient())
                {
                    //request.Method = "GET";
                    //request.ContentType = "text/html;charset=UTF-8";
                    //request.Accept = "*/*";
                    //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                    //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/html;charset=UTF-8");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

                    var response = await httpClient.GetAsync(url);//response.GetResponseStream();
                    response.EnsureSuccessStatusCode();
                    var responseStream = await response.Content.ReadAsStreamAsync();

                    var reader = new StreamReader(responseStream, Encoding.UTF8);
                    result = reader.ReadToEnd();

                    reader.Close();
                    responseStream.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常：" + ex.Message);
            }
            finally
            {
            }
            return result;
        }


        /// <summary>
        /// GET
        /// </summary>
        /// <param name="url">发送请求的URL</param>
        /// <param name="param">请求参数，请求参数应该是 name1=value1&name2=value2 的形式。</param>
        /// <param name="encoding">设置响应信息的编码格式，如utf-8</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static async Task<string> Get(string url, string param, string encoding)
        {
            string result = string.Empty;
            try
            {
                string urlNameString = url + "?" + param;
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/html;charset=UTF-8");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

                    var response = await httpClient.GetAsync(url);//response.GetResponseStream();
                    response.EnsureSuccessStatusCode();
                    var responseStream = await response.Content.ReadAsStreamAsync();

                    var reader = new StreamReader(responseStream, Encoding.UTF8);
                    result = reader.ReadToEnd();

                    reader.Close();
                    responseStream.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常：" + ex.Message);
            }
            finally
            {
            }
            return result;
        }


        /// <summary>
        /// 向指定 URL 发送POST方法的请求
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="jsonData">请求参数，请求参数应该是Json格式字符串的形式。</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static async Task<string> Post(string url, string jsonData)
        {
            var content = await Post(url, jsonData, "UTF-8");
            return content;
        }

        /// <summary>
        /// 向指定 URL 发送POST方法的请求
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="jsonData">请求参数，请求参数应该是Json格式字符串的形式。</param>
        /// <param name="encoding">设置响应信息的编码格式，如utf-8</param>
        /// <returns>所代表远程资源的响应结果</returns>
        public static async Task<string> Post(string url, string jsonData, string encoding)
        {

            string result = string.Empty;
            try
            {
                CookieContainer cookie = new CookieContainer();
                using (var handler = new HttpClientHandler() { CookieContainer = cookie })
                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.DefaultRequestHeaders.Add("x-requested-with", "XMLHttpRequest");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                    //httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

                    httpClient.DefaultRequestHeaders.ExpectContinue = false;

                    using (var request = new HttpRequestMessage())
                    {
                        request.Method = HttpMethod.Post;
                        request.RequestUri = new Uri(url);
                        request.Content = new StringContent(jsonData, Encoding.GetEncoding(encoding));
                        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        var response = await httpClient.SendAsync(request);
                        response.EnsureSuccessStatusCode();
                        return await response.Content.ReadAsStringAsync();
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("发送GET请求出现异常：" + ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 上传媒体文件
        /// </summary>
        /// <param name="url">上传媒体文件的微信公众平台接口地址</param>
        /// <param name="file">要上传的媒体文件对象</param>
        /// <returns>返回上传的响应结果，详情参看微信公众平台开发者接口文档</returns>
        public static async Task<string> UploadFile(string url, string file)
        {
            string result = string.Empty;
            try
            {
                byte[] bytes = File.ReadAllBytes(file);
                using (var content = new ByteArrayContent(bytes))
                using (var handler = new HttpClientHandler { Credentials = CredentialCache.DefaultCredentials })
                using (var client = new HttpClient(handler))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
                    //Send it
                    var response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();
                    Stream responseStream = await response.Content.ReadAsStreamAsync();
                    StreamReader reader = new StreamReader(responseStream);
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                result = "Error:" + ex.Message;
                Console.WriteLine("发送GET请求出现异常：" + ex.Message);
            }
            finally
            {
                Console.WriteLine("上传MediaId:" + result);
            }
            return result;
        }

        public static async Task<bool> DownloadFile(string url, string param, string outFileName)
        {
            bool result = false;
            FileStream? fs = null;
            try
            {
                //string urlNameString = url + "?" + param;
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString);
                //request.Method = "GET";
                //request.ContentType = "text/html;charset=UTF-8";
                //request.Accept = "*/*";
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //Stream responseStream = response.GetResponseStream();
                //fs = new FileStream(outFileName, FileMode.Create);
                //int bufferSize = 2048;
                //byte[] data = new byte[bufferSize];
                //int length = 0;
                //while ((length = responseStream.Read(data, 0, bufferSize)) > 0)
                //{
                //    fs.Write(data, 0, length);
                //}
                //fs.Close();
                //responseStream.Close();
                //response.Close();


                string urlNameString = url + "?" + param;
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "text/html;charset=UTF-8");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

                    var response = await httpClient.GetAsync(url);//response.GetResponseStream();
                    response.EnsureSuccessStatusCode();
                    var responseStream = await response.Content.ReadAsStreamAsync();

                    fs = new FileStream(outFileName, FileMode.Create);
                    int bufferSize = 2048;
                    byte[] data = new byte[bufferSize];
                    int length = 0;
                    while ((length = responseStream.Read(data, 0, bufferSize)) > 0)
                    {
                        fs.Write(data, 0, length);
                    }

                    fs.Close();
                    responseStream.Close();
                }

                result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("下载媒体文件时出现异常：" + ex.Message);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return result;
        }
        ///// <summary>
        ///// 向指定 URL 发送POST方法的请求
        ///// </summary>
        ///// <param name="posturl">发送请求的 URL</param>
        ///// <param name="postData">请求参数，请求参数应该是Json格式字符串的形式。</param>
        ///// <returns>所代表远程资源的响应结果</returns>
        //public static string HttpPost(string posturl, string postData = "")
        //{
        //    string content = String.Empty;
        //    Encoding encoding = Encoding.UTF8;
        //    byte[] data = encoding.GetBytes(postData);
        //    try
        //    {
        //        // 设置参数
        //        HttpWebRequest request = WebRequest.Create(posturl) as HttpWebRequest;
        //        CookieContainer cookieContainer = new CookieContainer();
        //        request.CookieContainer = cookieContainer;
        //        request.AllowAutoRedirect = true;
        //        request.Method = "POST";
        //        request.ContentType = "application/json;charset=utf-8";
        //        request.ContentLength = data.Length;
        //        using (Stream outstream = request.GetRequestStream())
        //        {
        //            outstream.Write(data, 0, data.Length);
        //            outstream.Close();
        //        }
        //        //发送请求并获取相应回应数据
        //        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //        //直到request.GetResponse()程序才开始向目标网页发送Post请求
        //        using (Stream instream = response.GetResponseStream())
        //        {
        //            using (StreamReader reader = new StreamReader(instream, encoding))
        //            {
        //                //返回结果
        //                content = reader.ReadToEnd();
        //                reader.Close();
        //            }
        //            instream.Close();
        //        }
        //        response.Close();
        //        return content;
        //    }
        //    catch (Exception ex)
        //    {
        //        string err = ex.Message;
        //        return string.Empty;
        //    }
        //}
    }
}
