using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Com.FirmLib.Common;
using FirmHttpDao;
using FWindSoft;
using FWindSoft.Net.Http;
using Newtonsoft.Json.Linq;

namespace Com.FirmLib
{
    /// <summary>
    /// 基础逻辑操作类
    /// </summary>
    public class BaseHttpBll
    {
        protected string m_ExtensionUri;
        protected HttpClient m_HttpClient;

        #region 错误机制

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

        #endregion

        #region 地址信息相关

        /// <summary>
        /// 获取基础地址
        /// </summary>
        /// <returns></returns>
        protected virtual string BaseEndUri()
        {
            return BllHttpSetting.Instance.EndUri;
        }

        /// <summary>
        /// 获取创建组
        /// </summary>
        /// <returns></returns>
        protected virtual string CreateKey()
        {
            return BllHttpSetting.Instance.InsertKey();
        }

        /// <summary>
        /// 获取删除组
        /// </summary>
        /// <returns></returns>
        protected virtual string DeleteKey()
        {
            return BllHttpSetting.Instance.DeleteKey();
        }

        /// <summary>
        /// 获取更新组
        /// </summary>
        /// <returns></returns>
        protected virtual string UpdateKey()
        {
            return BllHttpSetting.Instance.UpdateKey();
        }

        /// <summary>
        /// 获取查询组
        /// </summary>
        /// <returns></returns>
        protected virtual string QueryKey()
        {
            return BllHttpSetting.Instance.SearchKey();
        }

        #endregion

        public BaseHttpBll(string extensionUri)
        {
            Init(extensionUri);
        }

        protected void Init(string extensionUri)
        {
            this.m_ExtensionUri = extensionUri;
        }


        //protected void HandlerError(Task<HttpResponseMessage> result)
        //{
        //    HandlerError(result.Result);
        //}

        protected virtual HttpClient CreateHttpClient()
        {
            //if (m_HttpClient != null)
            //    return m_HttpClient;
            //return m_HttpClient = HttpClientManager.CreateClient();// new HttpClient() { BaseAddress = new Uri(GetEndUri()) };
            return HttpClientManager.CreateClient();
        }

        /// <summary>
        /// 获取操作的api
        /// </summary>
        /// <returns></returns>
        protected virtual string GetEndUri()
        {
            return this.BaseEndUri() + this.m_ExtensionUri;
        }

        #region 捕获业务处理返回消息

        protected void CatchErrorMessage(JObject jobject)
        {
            PostResult p = PostResult.CreatePostResult(jobject);
            this.ErrorMessage = p.ResultMessage;
        }

        #endregion

        #region 基础命令封装

        public string PostJsonAsync(Uri requeUri, JObject jobject)
        {
            RequestInfo request = new RequestInfo(requeUri.ToString(), jobject);
            try
            {
                #region 发送请求
                var client = CreateHttpClient();
                var response = client.PostJosnAsync(requeUri, jobject);
                #endregion
                return HandlerTaskResponse(response,request);
            }
            catch (Exception e)
            {
                throw;
            }        
        }

        public string PostJsonAdd(JObject jobject)
        {
            return PostJsonAsync(new Uri(GetEndUri() + CreateKey(), UriKind.RelativeOrAbsolute), jobject);
        }

        public string PostJsonUpdate(JObject jobject)
        {
            return PostJsonAsync(new Uri(GetEndUri() + UpdateKey(), UriKind.RelativeOrAbsolute), jobject);
        }

        public string PostJsonDelete(JObject jobject)
        {
            return PostJsonAsync(new Uri(GetEndUri() + DeleteKey(), UriKind.RelativeOrAbsolute), jobject);
        }

        public string PostJsonQuery(JObject jobject)
        {
            return PostJsonAsync(new Uri(GetEndUri() + QueryKey(), UriKind.RelativeOrAbsolute), jobject);
        }

        public string PostJsonQuery()
        {
            return PostJsonAsync(new Uri(GetEndUri() + QueryKey(), UriKind.RelativeOrAbsolute), new JObject());
        }

        #endregion


        #region 业务结果处理
        /// <summary>
        /// 业务结果处理
        /// </summary>
        /// <param name="responseResult"></param>
        /// <param name="success"></param>
        /// <param name="fail"></param>
        /// <returns></returns>
        public static bool HandlerResult(string responseResult, Action<JObject> success, Action<JObject> fail)
        {
            JObject result = JObject.Parse(responseResult);
            PostResult p = PostResult.CreatePostResult(result);
            if (p.IsSuccess)
            {
                success?.Invoke(result);
                return true;
            }

            fail?.Invoke(result);
            return false;
        }

        public static bool HandlerResult(string responseResult, Action<JObject> success)
        {
            return HandlerResult(responseResult, success, null);
        }

        public static bool HandlerResult(string responseResult)
        {
            return HandlerResult(responseResult, null, null);
        }

        #endregion



        #region 网络异常错误处理

        /// <summary>
        /// 处理错误返回消息
        /// </summary>
        /// <param name="responseMessage"></param>
        /// <param name="requestInfo"></param>
        public static void HandlerError(HttpResponseMessage responseMessage, RequestInfo requestInfo)
        {
            if (responseMessage.StatusCode != HttpStatusCode.OK)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(string.Format("StatusCode:{0}", (int) responseMessage.StatusCode));
                builder.AppendLine();
                builder.Append(string.Format("Url:{0}", responseMessage.RequestMessage.RequestUri));
                HttpApiException httpEx = new HttpApiException(builder.ToString());
                if (requestInfo != null)
                {
                    httpEx.RequestUrl = requestInfo.Head;
                    httpEx.RequestContent = requestInfo.Content;
                }

                throw httpEx;
            }

        }

        /// <summary>
        /// 处理返回消息任务
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="requestInfo"></param>
        /// <returns></returns>
        public static string HandlerTaskResponse(Task<HttpResponseMessage> ts, RequestInfo requestInfo)
        {
            try
            {
                var responseResult = ts.Result;
                if (responseResult.IsSuccessStatusCode)
                {
                    var strContent = responseResult.Content.ReadAsStringAsync();
                    return strContent.Result;
                }
                else
                {
                    HandlerError(responseResult, requestInfo);
                }

                return string.Empty;
            }
            catch (Exception e)
            {
                #region 异常处理
                var useE = e;
                while (useE.InnerException != null)
                {
                    useE = useE.InnerException;
                }

                HttpApiException httpEx = new HttpApiException(useE.Message, useE);
                var info = requestInfo;
                if (info != null)
                {
                    httpEx.RequestUrl = info.Head;
                    httpEx.RequestContent = info.Content;
                }

                throw httpEx;

                #endregion
            }
            finally
            {

            }
            return string.Empty;
        }
        #endregion
    }
}
