using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;

namespace AutoTurnOver.Utility
{
    public class HHttpHelper
    {
        private Dictionary<string, string> _heads = new Dictionary<string, string>();

        public string Request(string url, RequestType type, string data = "", string host = null, string entype = null, int timeout = 0)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (timeout <= 0)
            {
                request.Timeout = 1000 * 30;
            }
            else
            {
                request.Timeout = timeout;
            }
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36";
            request.Accept = "*";
            foreach (var item in _heads)
            {
                SetHeaderValue(request.Headers, item.Key, item.Value);
            }
            if (!string.IsNullOrEmpty(host))
            {
                SetHeaderValue(request.Headers, "Host", host);
            }
            switch (type)
            {
                case RequestType.GET:
                    if (string.IsNullOrWhiteSpace(request.ContentType))
                        request.ContentType = "text/html; charset=UTF-8";
                    request.Method = "GET";
                    break;

                case RequestType.POST:
                    {
                        if (string.IsNullOrWhiteSpace(entype))
                            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                        else
                            request.ContentType = entype;

                        request.Method = "POST";
                        byte[] bytes = Encoding.UTF8.GetBytes(data);
                        request.ContentLength = bytes.Length;
                        Stream requestStream = request.GetRequestStream();
                        requestStream.Write(bytes, 0, bytes.Length);
                        requestStream.Close();
                        break;
                    }
                default:
                    request.ContentType = "text/html; charset=UTF-8";
                    break;
            }
            StringBuilder builder = new StringBuilder();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            while (reader.Peek() != -1)
            {
                builder.Append(reader.ReadLine());
            }
            responseStream.Dispose();
            reader.Close();
            response.Close();
            Thread.Sleep(10);

            return builder.ToString();
        }

        public string UploadFile(string url, byte[] bytes)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 0x927c0;
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36";
            request.Accept = "*";
            foreach (var item in _heads)
            {
                SetHeaderValue(request.Headers, item.Key, item.Value);
            }


            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Method = "POST";
            //byte[] bytes = File2Bytes(filePath);
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            StringBuilder builder = new StringBuilder();
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                while (reader.Peek() != -1)
                {
                    builder.Append(reader.ReadLine());
                }
                responseStream.Dispose();
                reader.Close();
                response.Close();
                Thread.Sleep(10);
            }
            catch (Exception ex)
            {
            }
            return builder.ToString();
        }

        public string PostFile(string url, string filePath, string fileName, string access_token, string aop_signature,
            string fileByteName)
        {
            byte[] fileContentByte = new byte[1024]; // 文件内容二进制

            #region 将文件转成二进制

            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileContentByte = new byte[fs.Length]; // 二进制文件
            fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            #endregion


            #region 定义请求体中的内容 并转成二进制

            string boundary = "ceshi";
            string Enter = "\r\n";

            string fileContentStr = "--" + boundary + Enter
                                    + "Content-Type:application/octet-stream" + Enter
                                    + $"Content-Disposition: form-data; name=\"{fileByteName}\"; filename=\"" + fileName +
                                    "\"" + Enter + Enter;


            var fileContentStrByte = Encoding.UTF8.GetBytes(fileContentStr); //fileContent一些名称等信息的二进制（不包含文件本身）


            #endregion


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "multipart/form-data;boundary=" + boundary;

            Stream myRequestStream = request.GetRequestStream(); //定义请求流

            #region 将各个二进制 安顺序写入请求流 modelIdStr -> (fileContentStr + fileContent) -> uodateTimeStr -> encryptStr





            myRequestStream.Write(fileContentStrByte, 0, fileContentStrByte.Length);
            myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);



            #endregion

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();//发送
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }


            Stream myResponseStream = response.GetResponseStream();//获取返回值
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }


        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public static byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }


            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];


            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();


            return buff;
        }

        public void AddHeaderValue(string name, string value)
        {
            _heads.Add(name, value);
        }

        private void SetHeaderValue(WebHeaderCollection head, string name, string value)
        {
            PropertyInfo property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.NonPublic | BindingFlags.Instance);
            if (property != null)
            {
                NameValueCollection values = property.GetValue(head, null) as NameValueCollection;
                values[name] = value;
            }
        }



        public enum RequestType
        {
            GET,
            POST
        }
    }
}
