using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using YGNT.Infrastructure.Extension;
using YGNT.Infrastructure.Model;

namespace YGNT.Infrastructure.Helper
{
    /// <summary>
    /// Http连接操作帮助类 
    /// </summary>
    public class HttpHelper:IHttpHelper
    {
        private readonly IHttpContextAccessor _context;

        public HttpHelper(IHttpContextAccessor context)
        {
            _context = context;
        }
        private string GetToken()
        {
            string accessToken = _context.HttpContext.Request.Headers["Authorization"];
            string token = "";
            if (!string.IsNullOrEmpty(accessToken))
            {
                accessToken= accessToken.Substring("Bearer ".Length).Trim();
                var jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(accessToken);
                var tokenObj = jwtToken.Claims.FirstOrDefault(i => i.Type == JwtRegisteredClaimNames.Jti);
                if (tokenObj != null)
                {
                    token = tokenObj.Value;
                }
            }
            return token;
        }
        public HttpResult GetRequestResult(string resultJson)
        {
            HttpResult httpResult = new HttpResult();
            try
            {
                var jObj = JObject.Parse(resultJson);
                int code = jObj.Value<int>("code");
                if (code == 200 || code == 0)
                {
                    httpResult.Data = jObj["data"];
                    httpResult.Success = true;
                }
                else
                {

                    httpResult.Message = jObj.Value<string>("msg");
                }
            }
            catch (Exception ex)
            {
                httpResult.Message = ex.Message;
                return httpResult;
            }

            return httpResult;
        }
        public async Task<HttpResult> BaseRequestAsync(string uri, string type, string token = "")
        {
            string serviceUrl = uri;
            HttpResult httpResult = new HttpResult();
            try
            {
                //构造http请求的对象
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                httpWebRequest.Method = type;
                if (string.IsNullOrEmpty(token))
                {
                    token = GetToken();
                }
                httpWebRequest.Headers.Add("Authorization", token);
                // 获得接口返回值
                using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        string resultJson = await reader.ReadToEndAsync();
                        return GetRequestResult(resultJson);
                    }
                }
            }
            catch (Exception ex)
            {
                httpResult.Message = ex.Message;
                return httpResult;
            }
        }

        public async Task<HttpResult> BaseRequestAsync(string uri, string data, string type, string token = "")
        {
            //Web访问对象，构造请求的url地址
            string serviceUrl = uri;// string.Format("{0}/{1}", this.BaseUri, uri);
            HttpResult httpResult = new HttpResult();
            try
            {
                //构造http请求的对象
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //转成网络流
                byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data);
                //设置
                httpWebRequest.Method = type;
                httpWebRequest.ContentLength = buf.Length;
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                if (string.IsNullOrEmpty(token))
                {
                    token = GetToken();
                }
                httpWebRequest.Headers.Add("Authorization", token);
                // httpWebRequest.MaximumAutomaticRedirections = ;
                httpWebRequest.AllowAutoRedirect = true;

                // 发送请求
                Stream newStream = httpWebRequest.GetRequestStream();
                newStream.Write(buf, 0, buf.Length);
                newStream.Close();
                // 获得接口返回值
                using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        string resultJson = await reader.ReadToEndAsync();
                        return GetRequestResult(resultJson);
                    }
                }
            }
            catch (Exception ex)
            {
                httpResult.Message = ex.Message;
                return httpResult;
            }
        }

        public async Task<HttpResult> PostAsync(string uri, string data)
        {
            return await BaseRequestAsync(uri, data, "POST", "");
        }

        public async Task<HttpResult> PutAsync(string uri, string data)
        {
            return await BaseRequestAsync(uri, data, "PUT");
        }


        public async Task<HttpResult> DeleteAsync(string uri, string data)
        {
            return await BaseRequestAsync(uri, data, "DELETE");
        }

        public async Task<HttpResult> GetAsync(string uri)
        {
            return await BaseRequestAsync(uri, "GET");
        }

        public async Task<HttpResult> GetTokenAsync(string uri, string token)
        {
            return await BaseRequestAsync(uri, "GET", token);
        }

        public async Task<HttpResult> GetAsync(string uri, string data)
        {
            return await BaseRequestAsync(uri, data, "GET","");
        }

        public async Task<HttpResult> GetResponse(string url, string token = "")
        {
            HttpResult httpResult = new HttpResult();
            if (url.StartsWith("https"))
            { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }

            using (HttpClient httpClient = new HttpClient())
            {
                if (string.IsNullOrEmpty(token))
                {
                    token = GetToken();
                }
                if(!string.IsNullOrEmpty(token))
                {
                httpClient.DefaultRequestHeaders.Add("Authorization", token);
                }

                using (HttpResponseMessage response = await httpClient.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();
                        httpResult = GetRequestResult(result);
                    }
                    return httpResult;
                }
            }
        }
    }
}
