using Furion.EventBus;
using Furion.JsonSerialization;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;
using System.Security.Claims;

namespace BPA.MES.Base.Application
{
    /// <summary>
    /// 名    称 ：接口AOP
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：  2023/7/20 15:04:06 
    /// 描    述 ：  
    /// </summary>
    public class OperLogAttribute : ActionFilterAttribute
    {
        public string _name;
        public OperLogAttribute(string name)
        {
            _name = name;
        }
        /// <summary>
        /// 执行操作前后
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 获取 HttpContext 和 HttpRequest 对象
            var httpContext = context.HttpContext;
            var httpRequest = httpContext.Request;
            var sw = new Stopwatch();
            sw.Start();
            var actionContext = await next();
            sw.Stop();
            var userName = httpContext.User?.FindFirstValue(ClaimConst.CLAINM_NAME);
            await MessageCenter.PublishAsync("ToDo:OperLog", new OperLogEntity()
            {
                Context = context.ActionArguments.Count < 1 ? string.Empty : JSON.Serialize(context.ActionArguments),
                Name = $"[{userName}]{_name}",
                Result = actionContext.Exception == null? "true" :  EnhancedStackTrace.Current().ToString()
            });
        }
    }
}
