using System;
using System.Net;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace GxPress.Common.Middleware
{
    /// <summary>
    /// 自定义异常中间件
    /// </summary>
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next.Invoke(context);
            }
            catch (BusinessException be)
            {
                _logger.LogDebug(be.Message);
                await HandleBusinessException(context, be);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                await HandleSystemException(context, ex);
            }
        }



        /// <summary>
        /// 处理业务异常
        /// </summary>
        /// <param name="context"></param>
        /// <param name="be"></param>
        /// <returns></returns>
        private Task HandleBusinessException(HttpContext context, BusinessException be)
        {
            context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(JsonConvert.SerializeObject(new
            {
                be.Message,
                be.StackTrace
            }));
        }

        /// <summary>
        /// 处理系统异常
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private Task HandleSystemException(HttpContext context, Exception ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(JsonConvert.SerializeObject(ex));
        }

    }
}