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

namespace Waste.Application
{
    public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
    {
        private readonly ILoggerService _loggerService;

        public LogExceptionHandler(ILoggerService loggerService)
        {
            _loggerService = loggerService;
        }
        /// <summary>
        /// 全局异常处理提供器
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            // 写日志
            if (context != null)
            {
                var ex = context.HttpContext.Features.Get<IExceptionHandlerFeature>();
                //如果是用户取消的异常,则不必记录到日志
                if (context.HttpContext.RequestAborted.IsCancellationRequested && (ex is TaskCanceledException || ex is OperationCanceledException))
                {
                    Console.WriteLine("用户取消了操作");
                    context.HttpContext.Response.StatusCode = 200;
                    var contentresult = new ContentResult();
                    contentresult.Content = "操作已取消";
                    context.Result = contentresult;
                }
                else
                {
                    var request = context.HttpContext.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();
                        }
                    }
                    //记录日志
                    var exs = context.Exception;
                    _loggerService.AddErrorLogger(exs, query_string, action);
                    context.HttpContext.Response.StatusCode = 200;
                    var contentresult = new ContentResult();
                    contentresult.Content= "系统异常";
                    context.Result = contentresult;
                }
            }
        }
    }
}
