using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ICS.WCF.Base
{
    public class PostData
    {
        /// <summary>
        ///general a get http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public static string Get(string url, Dictionary<string, string> parameters)
        {
            return Get(url, DictionaryToString(parameters));
        }

        /// <summary>
        ///general a get http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public static string Get(string url, string parameters)
        {
            if (parameters != null && parameters != "")
            {
                if (url.Contains("?"))
                {
                    url += "&" + parameters;
                }
                else
                {
                    url += "?" + parameters;
                }
            }

            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();

            return content;
        }

        /// <summary>
        ///general a http request with add header type
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/26, 17:12:32</date>
        public static string HeaderRequest(string method, string url, string headerQuery)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;
                request.Headers.Add(headerQuery);
                request.Credentials = CredentialCache.DefaultCredentials;
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                stream.Close();

                return content;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public static string Post(string url, Dictionary<string, string> parameters)
        {
            return Post(url, DictionaryToString(parameters));
        }

        /// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public static string Post(string url, string parameters)
        {
            byte[] postData = System.Text.Encoding.ASCII.GetBytes(parameters);
            System.Net.ServicePointManager.Expect100Continue = false;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            return content;
        }

        public static string APT(string URL, string JsonData, string token)
        {
            try
            {
                //调用接口获取返回信息
                //string ContentType = "application/json;charset=UTF-8;";//application/json
                string ContentType = "application/json";

                WebRequest request = WebRequest.Create(URL);
                request.Method = "POST";
                request.Headers.Add("token", token);

                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(JsonData);
                request.ContentType = ContentType;
                request.ContentLength = bytes.Length;
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(bytes, 0, bytes.Length);
                }
                request.Credentials = CredentialCache.DefaultCredentials;
                string str = string.Empty;
                WebResponse response = null;
                try
                {
                    response = request.GetResponse();
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                        response = (WebResponse)ex.Response;
                }
                if (response != null)
                {
                    using (StreamReader st = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        str = System.Web.HttpUtility.UrlDecode(st.ReadToEnd());
                    }
                }

                //将返回的string类型转换成model
                //BaseModel obj = (BaseModel)Newtonsoft.Json.JsonConvert.DeserializeObject(str, typeof(BaseModel));
                return str;
            }
            catch (Exception ex)
            {
                throw new Exception("调用MES接口错误:" + ex.Message);
            }
        }


        public static string Post(string url, string parameters, string token)
        {
            byte[] postData = System.Text.Encoding.ASCII.GetBytes(parameters);
            System.Net.ServicePointManager.Expect100Continue = false;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            //request.Headers.Add("Authorization", token);
            request.Headers.Add("token", token);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            return content;
        }


        /// <summary>
        ///general the result string to dictionary
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:23:25</date>
        public static string DictionaryToString(Dictionary<string, string> parameters)
        {
            string queryParameter = "";
            foreach (string key in parameters.Keys)
            {
                if (queryParameter != "") queryParameter = "&";
                queryParameter += key + "=" + parameters[key];
            }

            return queryParameter;
        }

        /// <summary>
        ///general the result dictionary to string
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:23:25</date>
        public static Dictionary<string, string> StringToDictionary(string queryParameter)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            foreach (string keyvalue in queryParameter.Split(new char[] { '&' }))
            {
                string[] values = keyvalue.Split(new char[] { '=' });
                parameters.Add(values[0], values[1]);
            }

            return parameters;
        }

        /// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public static string PostByToken(string url, string parameters, string token)
        {

            //if (url.ToLower().StartsWith("https"))
            //{
            //    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
            //               | SecurityProtocolType.Tls
            //               ;
            //}

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;


            byte[] postData = System.Text.Encoding.ASCII.GetBytes(parameters);
            //System.Net.ServicePointManager.Expect100Continue = false;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            request.Headers.Add("Authorization", token);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            return content;
        }

        /// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public static string PostByToken(string url, Dictionary<string, string> parameters, string token)
        {
            return PostByToken(url, DictionaryToString(parameters), token);
        }

        public static string HttpPost(string url, string body, string token, string MethodType)
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = MethodType;
                request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json; charset=utf-8";
                request.Headers.Add("Authorization", token);
                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());
                //string ssb = sb.ToString();
                throw new Exception(sb.ToString());
            }
        }



        public static string PostByTokenGet(string url, Dictionary<string, string> parameters, string token)
        {
            //return PostByTokenGet(url, DictionaryToString(parameters), token);
            return GetInfo("", url, token);
        }


        public static string PostByTokenGet(string url, string parameters, string token)
        {

            if (url.ToLower().StartsWith("https"))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                           | SecurityProtocolType.Tls
                           ;
            }

            byte[] postData = System.Text.Encoding.ASCII.GetBytes(parameters);
            System.Net.ServicePointManager.Expect100Continue = false;
            WebRequest request = WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            request.Headers.Add("Authorization", token);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            return content;
        }



        public static string GetInfo(string postData, string Url)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(Url);
                objWebRequest.Method = "Get";
                objWebRequest.ContentType = "application/json;charset=UTF-8";
                objWebRequest.ContentLength = byteArray.Length;
                //objWebRequest.Headers.Add("Authorization", token);
                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string textResponse = sr.ReadToEnd(); // 返回的数据
                return textResponse;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string GetInfo(string postData, string Url, string token)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(Url);
                objWebRequest.Method = "Get";
                objWebRequest.ContentType = "application/json;charset=UTF-8";
                objWebRequest.ContentLength = byteArray.Length;
                objWebRequest.Headers.Add("Authorization", token);
                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string textResponse = sr.ReadToEnd(); // 返回的数据
                return textResponse;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }



        public static string PostInfo(string postData, string Url, string token)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(Url);
                objWebRequest.Method = "Post";
                objWebRequest.ContentType = "application/json;charset=UTF-8";
                objWebRequest.ContentLength = byteArray.Length;
                //objWebRequest.Headers.Add("Authorization", token);
                objWebRequest.Headers.Add("token", token);

                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string textResponse = sr.ReadToEnd(); // 返回的数据
                return textResponse;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string HttpPatch(string url, string body, string token)
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "PATCH";
                request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json; charset=utf-8";
                request.Headers.Add("Authorization", token);
                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());
                //string ssb = sb.ToString();
                throw new Exception(sb.ToString());
            }
        }

        public static string HttpDelete(string url, string body, string token)
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "DELETE";
                request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json; charset=utf-8";
                request.Headers.Add("Authorization", token);
                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());
                //string ssb = sb.ToString();
                throw new Exception(sb.ToString());
            }
        }
    }
}
