using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Nirvana.Common.ApiBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nirvana.Common
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class MyExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        public MyExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
              //  new ApiLoggerApplication().InsertErrorLog(ex);
                await HandleExceptionAsync(httpContext, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
        {
            //记录日志
          //  new ApiLoggerApplication().InsertErrorLog(ex);
            return Task.CompletedTask;
        }

        public void OnException(ExceptionContext context)
        {
            context.ExceptionHandled = true;
        }
    }

    /// <summary>
    /// Extension method used to add the middleware to the HTTP request pipeline.
    /// </summary>
    public static class MyExceptionMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyExceptionMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyExceptionMiddleware>();
        }
    }

    public static class ExceptionHandlingExtensions
    {
        public static void UseMyExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(builder => {

                builder.Run(async context =>
                {
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    context.Response.ContentType = "application/json";
                    var ex = context.Features.Get<IExceptionHandlerFeature>();
                    if (ex != null)
                    {
                        var request = context.Request;
                        var action = request.Path.Value;
                        var query_string = request.QueryString.Value;
                        if (request.Method == "POST" && request.ContentLength > 0)
                        {
                            request.EnableBuffering();
                            request.Body.Position = 0;
                            using (var sr = new StreamReader(request.Body))
                            {
                                query_string = await sr.ReadToEndAsync();
                            }
                        }
                        //记录日志
                      //  new ApiLoggerApplication().InsertErrorLog(ex.Error, query_string, action);
                        //new ApiLoggerApplication().InsertErrorLog(ex.Error);
                    }
                    var result = new ResultInfo { code = ResultState.SYSTEMERROR, message = ex?.Error?.Message ?? "系统异常" };
                    await context.Response.WriteAsync(result.ToJson());
                });
            });
        }
    }
}
