using ExternalDataSync;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WebApi
{
    public class Post
    {
        public static string Postring(string url, Dictionary<string, string> dic)
        {
            string result = "";
            //url = "http://172.16.22.15:8000/" + url;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Proxy = null;

            req.KeepAlive = false;

            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
        public static string Post_XK(string url, string content)
        {

            var WebapiPostHeader_Tenant = ConfigurationManager.AppSettings["WebapiPostHeader_Tenant"];
            var WebapiPostHeader_Language = ConfigurationManager.AppSettings["WebapiPostHeader_Language"];
            var WebapiPostHeader_Authorization = ConfigurationManager.AppSettings["WebapiPostHeader_Authorization"];
            var WebapiPostHeader_Systemcode = ConfigurationManager.AppSettings["WebapiPostHeader_Systemcode"];

            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Headers.Add("X-ECC-Current-Tenant", WebapiPostHeader_Tenant);
            req.Headers.Add("Accept-Language", WebapiPostHeader_Language);
            req.Headers.Add("Authorization", WebapiPostHeader_Authorization);
            //req.Headers.Add("Connect-Type", "application/json");
            req.Headers.Add("Systemcode", WebapiPostHeader_Systemcode);

            req.Accept = "*/*";
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Timeout = 10000;

            try
            {
                byte[] data = Encoding.UTF8.GetBytes(content);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { code = 500, message = ex.Message, data = new object() });
            }


            try
            {
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                using (Stream stream = resp.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (Stream stream = ex.Response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                else
                {
                    result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message, data = new object() });
                }
            }
            catch (Exception ex)
            {

                result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message, data = new object() });
            }

            return result;
        }

        public static string Post_Auto(string url, string content)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

            string result = "";
            
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Headers.Add("Connect-Type", "application/json");
                req.Accept = "*/*";
                req.Method = "POST";
                req.ContentType = "application/json";
                req.Timeout = 10000;

                // 写入请求数据
                if (!string.IsNullOrEmpty(content))
                {
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    req.ContentLength = data.Length;
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(data, 0, data.Length);
                    }
                }
                else
                {
                    req.ContentLength = 0;
                }

                // 获取响应
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                using (Stream stream = resp.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (Stream stream = ex.Response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                else
                {
                    // 返回标准格式的错误信息
                    result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message });
                }
            }
            catch (Exception ex)
            {
                // 返回标准格式的错误信息
                result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message });
            }

            return result;
        }

        public static JObject Post_WebAPI(string WebAPI_Url, string m_msg)
        {
            try
            {
                return JsonConvert.DeserializeObject<JObject>(WebApi.Post.Post_Auto(WebAPI_Url, m_msg));
            }
            catch (Exception ex)
            {
                return new JObject { { "code", 500 }, { "Message", ex.Message }, { "data", new JObject() } };
            }
        }

        public static string Postring1(string url, string token, Dictionary<string, string> dic)
        {
            string results = "";
            //url = "http://172.16.22.15:8000/" + url;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add("Authorization", "Bearer " + token);
            
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            try
            {
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    results = reader.ReadToEnd();
                }
                return results;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return e.Message;
                throw;
            }

        }


        public static string MyPost()
        {
            // var url = "http://192.168.1.224:41190/";
            var url = "http://127.0.0.1:41190/";
            var controller = "ZSaveTag";
            var action = "SelectPage";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("OpName","");
            dict.Add("StartTime", "2022-06-24 00:00:00");
            dict.Add("EndTime", "2022-06-30 00:00:00");
            dict.Add("PageCurrent", "1");
            dict.Add("PageSize", "2");


            var reqUrl = url + "/api/" + controller + "/" + action;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUrl);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Proxy = null;
            
            req.KeepAlive = false;

            #region 添加Post 参数
            JObject jObject = new JObject();
            jObject.Add("OpName", "");
            jObject.Add("StartTime", "2022-06-24 00:00:00");
            jObject.Add("EndTime", "2022-06-30 00:00:00");
            jObject.Add("PageCurrent", "2");
            jObject.Add("PageSize", "3");
            var jStr = jObject.ToString();

            //StringBuilder builder = new StringBuilder();
            //int i = 0;
            //foreach (var item in dict)
            //{
            //    if (i > 0)
            //        builder.Append("&");
            //    builder.AppendFormat("{0}={1}", item.Key, item.Value);
            //    i++;
            //}
            //byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            byte[] data = Encoding.UTF8.GetBytes(jStr);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            string result = "";

            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public static string MyPost(string url,string jsonStr)
        {
            string result = "";

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/json";
                req.Proxy = null;
                req.KeepAlive = false;

                byte[] data = Encoding.UTF8.GetBytes(jsonStr);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();


                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                Console.WriteLine(result);
                

            }
            catch (Exception err)
            {
                Console.WriteLine("<Error> " + err.Message);
            }

            return result;
        }

    }
}
