

using Newtonsoft.Json;

namespace CloudGaming.Code.Filter;


/// <summary>
/// 
/// </summary>
public class CustomResultFilter : IResultFilter
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IServiceProvider _serviceProvider;
    private readonly AppConfig _appConfig;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="httpContextAccessor"></param>
    /// <param name="appConfig"></param>
    /// <param name="serviceProvider"></param>
    public CustomResultFilter(IHttpContextAccessor httpContextAccessor, AppConfig appConfig, IServiceProvider serviceProvider)
    {
        _httpContextAccessor = httpContextAccessor;
        _appConfig = appConfig;
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 结果发送到客户端前
    /// </summary>
    /// <param name="context"></param>
    public void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is ObjectResult objectResult)
        {
            if (objectResult.Value == null)
            {
                BaseResponse<string> baseStringResponse = new BaseResponse<string>(ResponseCode.Success, "", null);
                objectResult.Value = baseStringResponse.ToString();
                return;
            }

            // 获取当前用户的信息
            if (objectResult.Value != null)
            {
                var httpContext = context.HttpContext;
                var path = httpContext.Request.Path.Value ?? "";
                var apiPrefix = path.Replace('/', '.').TrimStart('.');
                var sw = Stopwatch.StartNew();
                CloudGamingBase cloudGamingBase = new CloudGamingBase(_serviceProvider);
                var x = objectResult.Value.GetType();
                object? value = null;
                if (!x.FullName.Contains("HuanMeng.DotNetCore.Base.BaseResponse"))
                {
                    //特殊处理
                    if (objectResult.Value is string)
                    {
                        BaseResponse<string> baseStringResponse = new BaseResponse<string>(ResponseCode.Success, "", objectResult.Value.ToString());
                        value = baseStringResponse;
                        if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
                        {
                            var messageAttribute = MessageAttributeExtend.GetMessageAttribute(controllerActionDescriptor);
                            // 如果存在MessageAttribute，则设置响应消息
                            if (messageAttribute != null)
                            {
                                baseStringResponse.Message = messageAttribute.Message;
                            }
                        }
                        sw.Stop();
                        context.HttpContext.Response.Headers.TryAdd("X-Request-Duration-Filter", sw.Elapsed.TotalMilliseconds.ToString());
                        objectResult.Value = baseStringResponse.ToString();
                        return;

                    }
                    else
                    {
                        BaseResponse<object> baseResponse = new BaseResponse<object>(ResponseCode.Success, "", objectResult.Value);
                        value = baseResponse;
                        // 获取当前执行的Action方法的信息并进行类型检查
                        if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
                        {
                            var messageAttribute = MessageAttributeExtend.GetMessageAttribute(controllerActionDescriptor);
                            // 如果存在MessageAttribute，则设置响应消息
                            if (messageAttribute != null)
                            {
                                baseResponse.Message = messageAttribute.Message;
                            }
                        }
                    }
                    var dic = value.ToDictionaryOrList(apiPrefix, it => cloudGamingBase.Cache.AppImageCache[it]);
                    objectResult.Value = dic;
                }
                //else
                //{
                //    //value = objectResult.Value;
                //}


                sw.Stop();
                context.HttpContext.Response.Headers.TryAdd("X-Request-Duration-Filter", sw.Elapsed.TotalMilliseconds.ToString());
            }
        }

    }

    /// <summary>
    ///  结果发送到客户端后
    /// </summary>
    /// <param name="context"></param>
    public void OnResultExecuted(ResultExecutedContext context)
    {
        // 可在执行完结果后处理其他逻辑
    }
}
