using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using QYZH.InteractiveMagazine.Models.Dto;


namespace QYZH.InteractiveMagazine.Infrastructure.Middleware;

/// <summary>
/// 数据验证过滤器
/// </summary>
public class ModelValidActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            Dictionary<string, string> errorDic = new Dictionary<string, string>();
            foreach (var key in context.ModelState.Keys)
            {
                var modelstate = context.ModelState[key];
                if (modelstate.Errors.Any())
                {
                    string errorStr = string.Join(",", modelstate.Errors.Select(e => e.ErrorMessage).ToList());
                    errorDic.Add(key, errorStr);
                }
            }
            var result = new BaseResponse<Dictionary<string, string>>() { code = ResultCode.BAD_REQUEST };

            result.message = string.Join("|", errorDic.Select(e => e.Value).Distinct());
            result.result = errorDic;
            context.Result = new JsonResult(result);
        }
    }

    //public override void OnActionExecuted(ActionExecutedContext context)
    //{
    //    if (context.Exception != null)
    //    {
    //        BaseResponse result = new BaseResponse() { Code = ResultCode.Fail };
    //        result.Message = context.Exception.Message;
    //        context.Result = new JsonResult(result);
    //    }
    //}
}

