using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.KitChenManage.Core;
using BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.CheckService.Services;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Device.Services;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush.Services;
using BPA.SAAS.Manage.Core.System;
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;
        private readonly IThirdpartyPushService _thirdpartyPushService;

        public RequestAuditFiltercs( ICheckServices checkServices, IThirdpartyPushService thirdpartyPushService)
        {
            _checkServices = checkServices;
            _thirdpartyPushService= thirdpartyPushService;
        }

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

            CurrentUser.MessageId=Guid.NewGuid().ToString();

            //============== 这里是执行方法之前获取数据 ====================
            // 获取 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();

            // 获取控制器、路由信息
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            // 获取请求的方法
            var method = actionDescriptor.MethodInfo;

            // 获取请求参数（写入日志，需序列化成字符串后存储）
            var parameters = context.ActionArguments;

            //foreach (var parameter in parameters)
            //{
            //    var stingA = DtoValidator.GetSign(parameter.Value);
            //    var vvvv = stingA;
            //}

            var groupId = httpRequest.Headers["GroupId"];
            if (!string.IsNullOrEmpty(groupId))
            {
                CurrentUser.GroupId = groupId;
            }

            if (requestUrl.ToUpper().Contains("ExternalPlatform".ToUpper()))
            {

                var key = httpRequest.Headers["key"];
                var sign = httpRequest.Headers["sign"];
               
                List<PropertyInfo> proplist = new List<PropertyInfo>();
                if (parameters.Count<=0)
                {
                    //var sign = DtoValidator.GetAttributePrice(parameter.Value, "sign");
                    await _checkServices.CheckSign(key, "", sign);
                }
                else
                {
                    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;
            if (requestUrl.ToUpper().Contains("ExternalPlatform".ToUpper()))
            {
                try
                {
                    //记录日志
                    await SqlSugarDb.DbLog.Insertable(new BPA_ThirdpartyRequestLog()
                    {
                        Id = CurrentUser.MessageId,
                        CreateBy = DateTime.Now.ToString(),
                        GroupId = CurrentUser.GroupId,
                        RequestUrl = requestUrl,
                        ReauestMethod = httpRequest.Method,
                        ReauestParm = JsonConvert.SerializeObject(parameters),
                        ResultParm = !isRequestSucceed ? actionContext.Exception.ToString() : JsonConvert.SerializeObject(returnResult),
                        IP = remoteIPv4
                    }).ExecuteCommandAsync();

                    ////记录下发记录
                    //if (isRequestSucceed)
                    //{
                    //    foreach (var parameter in parameters)
                    //    {
                            
                    //        var isPush = DtoValidator.GetAttributePrice(parameter.Value, "isPush");
                    //        var callbackUrl = DtoValidator.GetAttributePrice(parameter.Value, "callbackUrl");
                    //        var storeIdList = DtoValidator.GetAttributePrice(parameter.Value, "storeIdList");
                    //        var deviceIdList = DtoValidator.GetAttributePrice(parameter.Value, "deviceIdList");

                    //        if (isPush.ToUpper() == "true".ToUpper())
                    //        {
                    //            var list = new List<string>();
                    //            if (!string.IsNullOrEmpty(deviceIdList))
                    //            {
                    //                list = JsonConvert.DeserializeObject<List<string>>(deviceIdList);
                    //            }
                    //            if ( !string.IsNullOrEmpty(storeIdList))
                    //            {
                    //                list = await _thirdpartyPushService.GetDeviceByStoreId(JsonConvert.DeserializeObject<List<string>>(storeIdList));
                    //            }

                    //            await _thirdpartyPushService.AddThirdpartyPushRecord(new BPA_ThirdpartyPushRecord()
                    //            {
                    //                Id = Guid.NewGuid().ToString(),
                    //                GroupId = CurrentUser.GroupId,
                    //                IsPush = false,
                    //                CallbackUrl = callbackUrl,
                    //                MessageId = msgId,
                    //                PushData = JsonConvert.SerializeObject(parameters),
                    //                PushDevice = JsonConvert.SerializeObject(list)
                    //            });
                    //        }
                    //        break;
                    //    }
                    //}
                  

                }
                catch (Exception e)
                {
                }
            }

        }
    }
}
