using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XYY.Core.Standard.ApiClient
{
    public static class HttpApiClientHelper
    {
        private static Dictionary<string, string> TestHost
            = new Dictionary<string, string>()
            {
                {"WMSHost","http://120.24.149.148/" }
            };
        private static Dictionary<string, string> ProductHost = new Dictionary<string, string>()
            {
                {"WMSHost","http://120.24.149.148/" }
            };

#if Debug
        public static bool IsTest => true;
#else
        public static bool IsTest => false;
#endif

        public static string WMSHost => IsTest ? TestHost["WMSHost"] : ProductHost["WMSHost"];
        public static string AdminToken => "132A7468DE079C6CEB59F383A661E612";
    }


    public class RequestException : Exception
    {

        public RequestException(string message) : base(message)
        {

        }

        /// <summary>
        /// 原始返回值
        /// </summary>
        public string OriginalContent
        {
            get; set;
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMessage
        {
            get; set;
        }

        /// <summary>
        /// 请求Id
        /// </summary>
        public string RequestId
        {
            get; set;
        }

        public string RequestUrl
        {
            get; set;
        }

        public object Request
        {
            get; set;
        }
    }


    public class HttpApiClient
    {
        private string host;
        private string agentToken;
        private ILogger<HttpApiClient> logger;

        public HttpApiClient(string host, ILogger<HttpApiClient> logger)
        {
            this.host = host;
            this.logger = logger;
        }

        public HttpApiClient(string host, string agentToken, ILogger<HttpApiClient> logger)
        {
            this.host = host;
            this.agentToken = agentToken;
            this.logger = logger;
        }

        public string BaseHost { get => host; }
        public string AgentToken { get => agentToken; }

        public async Task<OutModel> Post<OutModel>(string action)
        {
            return await Post<OutModel, object>(action, null);
        }


        public async Task<OutModel> Post<OutModel, InMode>(string action, InMode inMode)
        {
            if (host.EndsWith("/") && action.StartsWith("/"))
                host = host.Remove(host.Length - 1);
            string url = host + action;
            string body = "";
            System.Net.WebClient client = new System.Net.WebClient();
            try
            {
                string token = agentToken;
                client.Headers.Add("token", token);
                client.Headers.Add("Authorization", "token " + token); 
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("Accept", "application/json");
                if (inMode != null)
                    body = Newtonsoft.Json.JsonConvert.SerializeObject(inMode);
                string data = string.Empty;
                if (inMode != null)
                    data = await client.UploadStringTaskAsync(url, body);
                else
                    data = await client.DownloadStringTaskAsync(url);
                try
                {
                    OutModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<OutModel>(data);
                    return model;
                }
                catch (Exception ex)
                {
                    throw new Exception(" Json 反序列化失败" + ex.Message);
                }
            }
            catch (WebException ex)
            {
                string requestId = Guid.NewGuid().ToString();
                string content = new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                string message = ex.Status.ToString() + " " + ex.Message + " " + content;
                logger.LogError("http 请求失败{message} 请求url{url} body{body} request{requestId}", message, url, body, requestId);
                throw new Exception("http 请求失败" + message);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw new Exception("api 请求失败");
            }
        }

    }
}
