using LY.App.Service;
using System.Text;
namespace LY.App.MiddleWare
{
    public class CustomErrorMiddleware
    {
        private readonly RequestDelegate _next;
        private string body = string.Empty;
        private readonly LogService _logger;
        public CustomErrorMiddleware(RequestDelegate requestDelegate, LogService logger)
        {
            this._next = requestDelegate;
            _logger = logger;
        }
        public async Task Invoke(HttpContext context, IConfiguration configuration)
        {
            try
            {
                // Check if the request is a form post with a file
                if (context.Request.HasFormContentType && context.Request.Form.Files.Count > 0)
                {
                    foreach (var file in context.Request.Form.Files)
                    {
                        // Log file information
                        //_logger.LogInformation($"File uploaded - Name: {file.Name}, " +
                        //       $"FileName: {file.FileName}, " +
                        //       $"ContentType: {file.ContentType}, " +
                        //       $"Size: {file.Length} bytes");
                    }
                }
                else
                {
                    context.Request.EnableBuffering();
                    using (var reader = new StreamReader(context.Request.Body,
                        encoding: Encoding.UTF8,
                        detectEncodingFromByteOrderMarks: false,
                        leaveOpen: true))
                    {
                        body = await reader.ReadToEndAsync();
                        // Do some processing with body…
                        // Reset the request body stream position so the next middleware can read it
                        context.Request.Body.Position = 0;
                    }
                }
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                await HandleError(context, ex, configuration);
            }
        }
        /// 
        /// 错误信息处理方法
        /// 
        /// 
        /// 
        /// 
        private async Task HandleError(HttpContext context, Exception ex, IConfiguration configuration)
        {
            string pars = string.Empty;
            var method = context.Request.Method.ToUpper();
            var enable = configuration.GetSection("log2db").Value.ToLower();
            if (enable == "true")
            {
                switch (method)
                {
                    case "GET":
                        pars = context.Request.QueryString.ToString();
                        break;
                    case "POST":
                        //   var requestReader = new StreamReader(context.Request.Body);
                        // pars = await requestReader.ReadToEndAsync();
                        pars = body;
                        break;
                    default:
                        break;
                }
                await _logger.AddLog(new Model.AddLog()
                {
                    StackTrace = ex.StackTrace.Length > 1000 ? ex.StackTrace.Substring(0, 999) : ex.StackTrace,
                    Message = ex.Message,
                    Parameters = pars,
                    url = context.Request.Path,
                });
            }
            Console.WriteLine($"错误消息:{ex.Message}错误追踪{ex.StackTrace}");
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/json;charset=utf-8;";
            await context.Response.WriteAsJsonAsync(new { code = 1, msg = $"抱歉,服务端出错了,错误消息:{ex.Message}", data = "" });
        }
    }
    public static class RequestCultureMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomErrorMiddleware(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware();
        }
    }
}