using BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.CheckService.Services;
using Furion;
using Furion.EventBus;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Web.Core
{
    public class RequestAuditFiltercs : IAsyncActionFilter
    {
        private readonly ICheckServices _checkServices;
        public RequestAuditFiltercs(ICheckServices checkServices)
        {
            _checkServices = checkServices;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {

       

        //============== 这里是执行方法之前获取数据 ====================
        // 获取 HttpContext 和 HttpRequest 对象
            var httpContext = context.HttpContext;
            var httpRequest = httpContext.Request;

            // 获取客户端 Ipv4 地址
            var remoteIPv4 = httpContext.GetRemoteIpAddressToIPv4();

            // 获取请求的 Url 地址
            var requestUrl = httpRequest.GetRequestUrlAddress();

            // 获取来源 Url 地址
            var refererUrl = httpRequest.GetRefererUrlAddress();

            if (requestUrl.ToUpper().Contains("ExternalPlatform".ToUpper()))
            {
                // 获取请求参数（写入日志，需序列化成字符串后存储）
                var parameters = context.ActionArguments;
                var key= httpRequest.Headers["key"];
                var sign= httpRequest.Headers["sign"];
                List<PropertyInfo> proplist = new List<PropertyInfo>();
                foreach (var parameter in parameters)
                {
                  var stingA=  DtoValidator.GetSign(parameter.Value);
                  //var sign = DtoValidator.GetAttributePrice(parameter.Value, "sign");
                  await _checkServices.CheckSign(key, stingA, sign);
                }
            }

            //============== 这里是执行方法之后获取数据 ====================
            var actionContext = await next();

            // 获取返回的结果
            var returnResult = actionContext.Result;

            // 判断是否请求成功，没有异常就是请求成功
            var isRequestSucceed = actionContext.Exception == null;
        }
    }
}
