using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Performance.Api
{
    public class ActionsFilter : IAsyncActionFilter
    {
        private readonly ILogger<ActionsFilter> _logger;
        private readonly IMemoryCache _cache;
        private readonly IHostingEnvironment _env;

        public ActionsFilter(ILoggerFactory factory, IMemoryCache cache, IHostingEnvironment env)
        {
            this._logger = factory.CreateLogger<ActionsFilter>();
            this._cache = cache;
            this._env = env;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var request = context.HttpContext.Request;
            //记录Request请求 
            var authorization = context.HttpContext.Request.Headers["Authorization"];
            var req = new { request.Path, request.Method, context.ActionArguments, Token = authorization.Count > 0 ? authorization.First() : "" };
            _logger.LogInformation($"请求内容 {JsonHelper.Serialize(req)}");
            //启用body倒带功能
            request.EnableRewind();

            //接口禁用 
            if (context.Filters.Any(item => item is ApiDisableAttribute))
            {
                var response = new ApiResponse(ResponseType.Disable, "接口已禁用");
                context.Result = new ObjectResult(response);
                return;
            }
            //验证请求参数
            if (!context.ModelState.IsValid)
            {
                var messageList = context.ModelState.Values
                    .Where(t => !string.IsNullOrEmpty(t?.Errors?.FirstOrDefault()?.ErrorMessage))
                    .Select(t => t?.Errors?.FirstOrDefault()?.ErrorMessage);
                var response = new ApiResponse(ResponseType.ParameterError, "参数错误", messageList);
                context.Result = new ObjectResult(response);
                var jsonData = JsonHelper.Serialize(context.Result);
                _logger.LogInformation($"响应结果:{jsonData}");
                LogHelper.Information($"请求地址：{context.HttpContext.Request.Path};响应结果：{jsonData}", "响应结果");
            }

            //记录response结果
            else
            {
                var executedContext = await next();
                if (executedContext.Exception != null)
                    throw executedContext.Exception;

                if (executedContext.Result is ObjectResult)
                {
                    LogHelper.Information(JsonHelper.Serialize(executedContext.Result), "响应结果");
                    var objectResult = (ObjectResult)executedContext.Result;
                    var jsonData = JsonHelper.Serialize(objectResult.Value);
                    _logger.LogInformation($"响应结果:{jsonData}");
                    LogHelper.Information($"请求地址：{context.HttpContext.Request.Path};响应结果：{jsonData}", "响应结果");
                }
            }
        }
    }

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class ApiDisableAttribute : Attribute, IFilterMetadata { }
}
