using MES.Utility.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace 常用工具集.Utility.Network
{
    public class HttpUtils
    {
        public static bool DoGetFile(string url, string filePath, int? timeout)
        {
            var task = DoGetFileAsync(url, filePath);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return false;
                }
            }
            return task.Result;
        }

        public static byte[] DoGetFile(string url, int? timeout)
        {
            var task = DoGetFileAsync(url);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return null;
                }
            }
            return task.Result;
        }

        public static async Task<bool> DoGetFileAsync(string url, string filePath)
        {
            try
            {
                var httpClient = new HttpClient();
                var response = await httpClient.GetAsync(url);
                var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                await response.Content.CopyToAsync(fileStream);
                fileStream.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static async Task<byte[]> DoGetFileAsync(string url)
        {
            try
            {
                var httpClient = new HttpClient();
                var response = await httpClient.GetAsync(url);
                MemoryStream memoryStream = new MemoryStream();
                return await response.Content.ReadAsByteArrayAsync();
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 通过Get请求数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parametersDict"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string DoGet(string url, Dictionary<string, string> parametersDict, int? timeout)
        {
            var task = DoGetAsync(url, parametersDict);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return null;
                }
            }
            return task.Result;
        }

        /// <summary>
        /// 通过Get请求数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parametersDict"></param>
        /// <returns></returns>
        public static async Task<string> DoGetAsync(string url, Dictionary<string, string> parametersDict)
        {
            try
            {
                if (!url.Contains("?"))
                    url = url + "?";
                foreach (string key in parametersDict.Keys)
                {
                    url = url + key + "=" + parametersDict[key] + "&";
                }
                url = url.Substring(0, url.Length - 1);
                var httpClient = new HttpClient();
                var response = await httpClient.GetAsync(url);
                string str= await response.Content.ReadAsStringAsync();
                return str;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 通过Post上传文件：multipart/form-data
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parms"></param>
        /// <param name="fileParms"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string DoPostFile(string url, Dictionary<string, string> parms, Dictionary<string, string> fileParms, int? timeout)
        {
            var task = DoPostFileAsync(url, parms, fileParms);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return null;
                }
            }
            return task.Result;
        }

        /// <summary>
        /// 通过Post上传文件：multipart/form-data
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parms"></param>
        /// <param name="fileParms"></param>
        /// <returns></returns>
        public static async Task<string> DoPostFileAsync(string url, Dictionary<string, string> parms, Dictionary<string, string> fileParms)
        {
            try
            {
                var httpClient = new HttpClient();
                var content = new MultipartFormDataContent();
                if (parms != null)
                {
                    foreach (KeyValuePair<string, string> keyValue in parms)
                    {
                        content.Add(new StringContent(keyValue.Value), keyValue.Key);
                    }
                }
                if (fileParms != null)
                {
                    foreach (KeyValuePair<string, string> keyValue in fileParms)
                    {
                        string filePath = keyValue.Value;
                        string fileName = Path.GetFileName(filePath);
                        if (!File.Exists(filePath))
                        {
                            continue;
                        }
                        content.Add(new ByteArrayContent(File.ReadAllBytes(filePath)), keyValue.Key, fileName);
                    }
                }
                var response = await httpClient.PostAsync(url, content);
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        /// <summary>
        ///  通过Post请求数据： application/x-www-form-urlencoded
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parms"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string DoPostForm(string url, Dictionary<string, string> parms, int? timeout)
        {
            var task = DoPostFormAsync(url, parms);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return null;
                }
            }
            return task.Result;
        }

        /// <summary>
        ///  通过Post请求数据： application/x-www-form-urlencoded
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static async Task<string> DoPostFormAsync(string url, Dictionary<string, string> parms)
        {
            try
            {
                var httpClient = new HttpClient();
                FormUrlEncodedContent formData;
                if (parms != null)
                {
                    formData = new FormUrlEncodedContent(parms);
                }
                else
                {
                    formData = new FormUrlEncodedContent(new Dictionary<string, string>());
                }
                var response = await httpClient.PostAsync(url, formData);
                return await response.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }


        /// <summary>
        ///  通过Post请求数据： application/x-www-form-urlencoded
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string DoPostJson(string url, string json, int? timeout)
        {
            var task = DoPostJsonAsync(url, json);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return null;
                }
            }
            return task.Result;
        }

        /// <summary>
        ///  通过Post请求数据： application/x-www-form-urlencoded
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static async Task<string> DoPostJsonAsync(string url, string json)
        {
            try
            {
                var httpClient = new HttpClient();
                StringContent jsonContent = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, jsonContent);
                return await response.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }


        /// <summary>
        ///  通过Post请求数据： application/x-www-form-urlencoded
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string DoPostData(string url, object data, int? timeout)
        {
            var task = DoPostDataAsync(url, data);
            if (timeout != null)
            {
                if (!task.Wait(timeout.Value))
                {
                    return null;
                }
            }
            return task.Result;
        }

        /// <summary>
        ///  通过Post请求数据： application/x-www-form-urlencoded
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static async Task<string> DoPostDataAsync(string url, object obj)
        {
            try
            {
                var httpClient = new HttpClient();
                StringContent jsonContent = new StringContent(obj.ToJson(), Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, jsonContent);
                return await response.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }
}