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

namespace XS_BLL
{
    public class HttpHelper
    {
        /// <summary>
        /// http传参 设置header值
        /// </summary>
        /// <param name="url">路径</param>
        /// <param name="strPost">请求JSON  body</param>
        /// <param name="contentType">类别</param>
        /// <param name=""></param>
        /// <returns></returns>
        public static string PostJson(string url, string strPost, string contentType = "application/json;charset=utf-8")
        {
            string retJson = string.Empty;
            try
            {
                //string reqCode = UtilityBLL.GetReceiveValues(strPost, "reqCode");
                string reqCode = "";
                Hashtable head = new Hashtable();
                //head.Add("appKey", Global.appKey);
                //head.Add("requestPlan", Global.requestPlan);
                //head.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //head.Add("version", Global.version);
                //head.Add("httpVersion", Global.httpVersion);
                //head.Add("sign", utilityBLL.GenerateMD5(Global.appSecret + reqCode));
                //head.Add("sign", "A71253A5731E6261ADE4E23283AF2B28");

                retJson = Http(url, "POST", contentType, head, strPost);
                //UtilityBLL.CreateINTERFACE_LOG(url, "WCS ==>> WMS", strPost, retJson );
                //JsonSerializerSettings setting= new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                //string code = UtilityBLL.GetReceiveValues(retJson, "data,code");
                string code = UtilityBLL.GetReceiveValues(retJson, "code");
                if (retJson == "操作超时")
                {
                    return retJson = JsonConvert.SerializeObject(new { reqCode = reqCode, code = 900, message = retJson });
                }
                else if (retJson == "远程服务器返回错误: (500) 内部服务器错误。")
                {
                    return retJson = JsonConvert.SerializeObject(new { reqCode = reqCode, code = 900, message = retJson });
                }
                else if (!string.IsNullOrEmpty(code))// code == "0" || code == "1" || code == "00" || code == "01" || code == "99" || code == "200"|| code == "400")
                {
                    return retJson;
                }
                else
                {
                    //reqCode = UtilityBLL.GetReceiveValues(strPost, "reqCode");
                    retJson = JsonConvert.SerializeObject(new { reqCode = reqCode, code = 900, message = retJson });
                    return retJson;
                }

            }
            catch (Exception ex)
            {
                string reqCode = UtilityBLL.GetReceiveValues(strPost, "strPost");
                return JsonConvert.SerializeObject(new { reqCode = reqCode, code = 200, message = ex.Message });
            }
        }

        /// <summary>
        /// 不做catch处理,需要在外部做
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method">默认GET,空则补充为GET</param>
        /// <param name="contenttype">默认json,空则补充为json</param>
        /// <param name="header">请求头部</param>
        /// <param name="data">请求body内容</param>
        /// <returns></returns>
        public static string Http(string url, string method = "GET", string contenttype = "application/json;charset=utf-8", Hashtable header = null, string data = null)
        {
            string json = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = string.IsNullOrEmpty(method) ? "GET" : method;
                request.ContentLength = 0;

                request.KeepAlive = false;  //设置不建立持久性连接连接
                request.ProtocolVersion = HttpVersion.Version10; //http的版本有2个,一个是1.0,一个是1.1 具体更具实际情况测试替换

                request.ContentType = string.IsNullOrEmpty(contenttype) ? "application/json;charset=utf-8" : contenttype;
                Encoding encoding = Encoding.UTF8;
                //request.ContentLength = buffer.Length;
                //request.GetRequestStream().Write(buffer, 0, buffer.Length);

                if (header != null)
                {
                    foreach (var i in header.Keys)
                    {
                        request.Headers.Add(i.ToString(), header[i].ToString());
                    }
                }
                if (!string.IsNullOrEmpty(data))
                {
                    //request.Accept = "text/html, application/xhtml+xml, */*";
                    byte[] buffer = encoding.GetBytes(data.ToString());
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                request.Timeout = 1000 * 10;
                Stream ResponseStream = response.GetResponseStream();
                StreamReader StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8"));
                json = StreamReader.ReadToEnd();
                StreamReader.Close();
                ResponseStream.Close();
                return json;
            }
            catch (Exception ex)
            {
                return json = ex.Message;
            }

        }
    }
}