using IRaCIS.Core.Application.Helper.OtherTool;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using System;
using System.Reflection;
using static System.Runtime.InteropServices.JavaScript.JSType;


namespace IRaCIS.Core.Application.Filter;



public class ModelActionFilter(IStringLocalizer _localizer, IConfiguration _config, IUserInfo _userInfo) : ActionFilterAttribute, IActionFilter
{


    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {

            var validationErrors = context.ModelState
                                          .Keys
                                          .SelectMany(k => context.ModelState[k]!.Errors)
                                          .Select(e => e.ErrorMessage)
                                          .ToArray();

            var request = context.HttpContext.Request;

            try
            {
                bool isOpenWeComNotice = _config.GetValue<bool>("WeComNoticeConfig:IsOpenWeComNotice");

                if (isOpenWeComNotice)
                {
                    string webhook = _config["WeComNoticeConfig:WebhookUrl"] ?? string.Empty;

                    var uri = new Uri(_config["SystemEmailSendConfig:SiteUrl"]);
                    var baseUrl = uri.GetLeftPart(UriPartial.Authority);

                    var userList = _config.GetSection("WeComNoticeConfig:VueNoticeUserList").Get<string[]>();

                    var requestBody = context.HttpContext.Items["RequestBody"] as string;


                    // 🔔 异步告警（不要阻塞请求）
                    _ = WeComNotifier.SendAlertAsync(
                        webhook: webhook,
                        alert: new WeComAlert
                        {
                            Env = baseUrl,
                            UserName = _userInfo.UserName.IsNotNullOrEmpty()?   $"{_userInfo.UserName}({_userInfo.UserTypeShortName})":  "匿名",
                            Api = $"{request.Method} {request.Path}",
                            Message = $"前端传递参数，后端模型验证失败\n 具体信息：{JsonConvert.SerializeObject(validationErrors)}",
                            JsonData = requestBody,
                            AtUsers = userList ?? []
                        }
                    );

                }


            }
            catch (Exception ex)
            {
                Log.Logger.Error($"模型验证过滤器里发送企业微信出现错误：{ex.Message}");
            }

           

            //---提供给接口的参数无效。
            context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["ModelAction_InvalidAPIParameter"] + JsonConvert.SerializeObject(validationErrors), ApiResponseCodeEnum.BackEndAnomaly));
        }
    }
}




