using LifePayment.Application.Contracts;
using LifePayment.Domain.Shared;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;

namespace LifePayment.HttpApi
{
    public class ChannelFilterAttribute : Attribute, IAsyncActionFilter
    {

        public ChannelFilterAttribute()
        {

        }


        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ActionDescriptor.IsControllerAction())
            {
                await next();
                return;
            }

            var checkerService = context.GetRequiredService<ILifePayService>();

            foreach (var argument in context.ActionArguments)
            {
                // 检查参数类型是否为 ChannelsBaseInput
                if (argument.Value is ChannelsBaseInput model)
                {
                    // 获取 Channel 参数的值
                    string channelValue = model.CheckChannelId;
                    if (!string.IsNullOrEmpty(channelValue))
                    {
                        var result = await checkerService.CheckChannelsStatus(channelValue);
                        if (result)
                        {
                            await next();
                        }
                        else
                        {
                            throw new UserFriendlyException("没有对应的渠道");
                        }

                    }
                }
            }


        }


    }
}