using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Pms.WebHandle
{
    /// <summary>
    /// http直接访问rest服务
    /// 通过URI执行，get/post/put/delete方法
    /// put暂停使用
    /// </summary>
    public class RestRequestHelper
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseUrl"></param>
        public RestRequestHelper(string baseUri)
        {
            this.BaseUri = baseUri;
        }
        /// <summary>
        /// 基地址
        /// </summary>
        private string BaseUri;

        /// <summary>
        /// Post调用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string Post(string data, string uri)
        {
            //Web访问对象
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //转成网络流
            byte[] buf = Encoding.UTF8.GetBytes(data);

            //设置
            myRequest.Method = "POST";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "text/plain";

            // 发送请求
            using (Stream newStream = myRequest.GetRequestStream())
            {
                newStream.Write(buf, 0, buf.Length);
                newStream.Close();
            }
            // 获得接口返回值
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }


        /// <summary>
        /// Post调用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="wholeURI"></param>
        /// <returns></returns>
        public string PostWithWholeURI(string data, string wholeURI,bool wmsRequest=false)
        {
            //Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(wholeURI);
            //转成网络流
            byte[] buf = Encoding.UTF8.GetBytes(data);

            //设置
            myRequest.Method = "POST";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json ";//text/plain
            if(wmsRequest)
            {
                myRequest.Headers.Add("Client", "WebService");
                myRequest.Headers.Add("Account", "AGVS");
                myRequest.Headers.Add("PassWord", "AGVS**a375");
            }
            
            //HttpRequestHeader httpRequestHeader = new HttpRequestHeader();

            // 发送请求
            using (Stream newStream = myRequest.GetRequestStream())
            {
                newStream.Write(buf, 0, buf.Length);
                newStream.Close();
            }
            // 获得接口返回值
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    //return HttpUtility.HtmlDecode(reader.ReadToEnd()); 
                    return reader.ReadToEnd();
                }
            }
        }


        /// <summary>
        /// Get调用
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string Get(string uri)
        {
            //Web访问对象
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            // 获得接口返回值
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        public string invokeHttpRequest(string strURL)
        {
            try
            {
                //执行HTTP请求 
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
                request.Timeout = 10000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                //获得返回数据 
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);//Encoding.GetEncoding("GBK")
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(reader.ReadToEnd());
                reader.Close();

                return doc.DocumentElement.InnerText;
            }
            catch { throw; }
        }

        /// <summary>
        /// Put调用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string Put(string uri)
        {
            //Web访问对象
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            myRequest.Method = "PUT";
            //转成网络流
            byte[] buf = Encoding.UTF8.GetBytes("");
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "text/plain";
            // 获得接口返回值
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// Delete调用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string Delete(string uri)
        {
            //Web访问对象
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            myRequest.Method = "DELETE";
            // 获得接口返回值
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }

    /// <summary>
    /// 对象 <----> json串相互转换
    /// 1、对象必须为public属性
    /// 2、仅public成员正常转换，非public成员值由系统分配
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 生成json
        /// </summary>
        /// <param name="type"></param>
        /// <param name="node"></param>
        /// <returns></returns>
        public static string ConvertToJson(System.Type type, object node)
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(type);
            using (var stream = new System.IO.MemoryStream())
            {
                js.WriteObject(stream, node);
                string str = Encoding.UTF8.GetString(stream.ToArray()); //Encoding.GetEncoding("GBK").GetString(stream.ToArray());
                return str;
            }
        }

        /// <summary>
        /// 解析对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static object ConvertToObject(System.Type type, string jsonString)
        {
            //jsonString.Trim('\0',' ');
            DataContractJsonSerializer js = new DataContractJsonSerializer(type);
            using (var s = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(jsonString)))//Encoding.GetEncoding("GBK").GetBytes(jsonString)
            {
                return js.ReadObject(s);
            }

        }

        /// <summary>
        /// 解析对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static object ConvertToObject(System.Type type, System.IO.Stream jsonStream)
        {
            using (StreamReader sr = new StreamReader(jsonStream))
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(type);
                var s = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(sr.ReadToEnd()));
                return js.ReadObject(s);
            }//end sr

        }


    }
}

