using Furion;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using System;
using System.IO;
using System.Threading.Tasks;
using YBDevice.Core;

namespace YBDevice.NApi
{
    /// <summary>
    /// API接口请求日志记录
    /// </summary>
    public class ApiLoggerFilter : IAsyncAlwaysRunResultFilter
    {
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (Configs.GetBoolValue("IsApiLog"))
            {
                var resultinfo = string.Empty;
                var result = context.Result;
                if (result is EmptyResult)
                {
                    context.Result = new JsonResult(new ResultInfo { code = ResultState.NOAUTH, message = "内容读取失败" });
                }
                else
                {
                    var res = result as ObjectResult;
                    if (res == null)
                    {
                        var res1 = result as ContentResult;
                        resultinfo = res1 != null ? res1.Content : "";
                    }
                    resultinfo = res != null ? res.Value.ToJson() : "";
                    var request = context.HttpContext.Request;
                    var _logger = App.GetService<ILoggerService>();
                    if (request != null)
                    {
                        try
                        {
                            var action = request.Path.ToString();//请求地址
                            var Remote_Addr = context.HttpContext.Connection.RemoteIpAddress.ToString(); //远程主机IP
                            var request_method = request.Method;
                            var query_string = request.QueryString.Value;
                            var user_agent = request.Headers["User-Agent"];
                            if (request.Method == "POST" && request.ContentLength > 0)
                            {
                                request.EnableBuffering();
                                request.Body.Position = 0;
                                // post请求方式获取请求参数，.net core 2.0 不支持.Form 直接获取 
                                using (var sr = new StreamReader(request.Body))
                                {
                                    query_string = await sr.ReadToEndAsync();
                                }
                            }
                            var msg = $"======{action}=====\r\nip:{Net.Ip}\r\nparam:{query_string}\r\nua:{user_agent}\r\nresult:{resultinfo}\r\n======{action}=====";
                            _logger.AddLogger(msg, 4);
                        }
                        catch (Exception ex)
                        {
                            var msg = $"写API日志发生错误";
                            _logger.AddErrorLogger(ex);
                        }
                    }
                }
            }
            await next();
        }
    }
}
