using DevExpress.XtraPrinting.Native.WebClientUIControl;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;

namespace VIZ.Package.Module
{
    public class MediaResourceFileService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(MediaResourceFileService));

        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="json">发送的参数字符串，只能用json</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> PostAsyncJson(string url, string json)
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpContent content = new StringContent(json);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
            }

            catch (Exception ex)
            {
                log.Error(string.Format("{0}_{1}", "获取媒体资源文件夹", ex.ToString()));
                return "";
            }

        }

        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="data">发送的参数字符串</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> PostAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
        {
            HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            HttpContent content = new StringContent(data);
            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            string responseBody = "";
            responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }

        /// <summary>
        /// 使用get方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> GetAsync(string url, Dictionary<string, string> header = null, bool Gzip = false)
        {

            HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();//用来抛异常的
            string responseBody = "";
            responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }

        /// <summary>
        /// 使用post返回异步请求直接返回对象
        /// </summary>
        /// <typeparam name="T">返回对象类型</typeparam>
        /// <typeparam name="T2">请求对象类型</typeparam>
        /// <param name="url">请求链接</param>
        /// <param name="obj">请求对象数据</param>
        /// <returns>请求返回的目标对象</returns>
        public static async Task<T> PostObjectAsync<T, T2>(string url, T2 obj)
        {
            try
            {
                String json = JsonConvert.SerializeObject(obj);
                string responseBody = await PostAsyncJson(url, json); //请求当前账户的信息
                return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
            }

            catch (Exception ex)
            {
                log.Error(ex.Message);
                return default(T);
            }

        }

        /// <summary>
        /// 使用Get返回异步请求直接返回对象
        /// </summary>
        /// <typeparam name="T">请求对象类型</typeparam>
        /// <param name="url">请求链接</param>
        /// <returns>返回请求的对象</returns>
        public static async Task<T> GetObjectAsync<T>(string url)
        {
            string responseBody = await GetAsync(url); //请求当前账户的信息
            return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
        }



        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<MemoryStream> GetImage(string url)
        {
            try
            {
                HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();//用来抛异常的

                using (Stream stream = response.Content.ReadAsStreamAsync().Result)
                {
                    MemoryStream ms = new MemoryStream();
                    stream.CopyTo(ms);
                    return ms;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return null;
            }


        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestUri"></param>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task<T> PostImage<T>(string requestUri, string path, string fileName)
        {
            try
            {
                HttpClient client = new HttpClient();
                var content = new MultipartFormDataContent();
                content.Headers.Add("ContentType", $"multipart/form-data");
                var b = new ByteArrayContent(System.IO.File.ReadAllBytes(path));
                content.Add(b, "image", fileName);
                var response = await client.PostAsync(requestUri, content);

                var result = response.Content.ReadAsStringAsync().Result;
                return JsonConvert.DeserializeObject<T>(result);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return default(T);
            }

        }

        /// <summary>
        /// 上传截图图片
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestUri"></param>
        /// <param name="bitmap"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task<T> PostCutImage<T>(string requestUri, Bitmap bitmap, string fileName)
        {
            try
            {
                HttpClient client = new HttpClient();
                var content = new MultipartFormDataContent();
                content.Headers.Add("ContentType", $"multipart/form-data");
                var b = ThumbnailHelper.BitmapToGrayByte(bitmap);
                content.Add(new ByteArrayContent(b), "image", fileName);
                var response = await client.PostAsync(requestUri, content);

                var result = response.Content.ReadAsStringAsync().Result;
                return JsonConvert.DeserializeObject<T>(result);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return default(T);
            }




        }
    }
}
