using Furion;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nirvana.Common;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Waste.Application
{
    public class ApiAsyncActionFilter : Attribute, IAsyncActionFilter
    {
        private readonly ILoggerService _loggerService;
        private readonly IBusinessApiService _businessApiService;
        public ApiAsyncActionFilter()
        {
            _loggerService = App.GetService<ILoggerService>();
            _businessApiService = App.GetService<IBusinessApiService>();
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            // 拦截之前
            var request = context.HttpContext.Request;
            if (!request.Query.ContainsKey("appid"))
            {
                var result = new ResultInfo(ApiResultState.NOAPPID, "缺少appid参数");
                var jsonresult = new JsonResult(result);
                context.Result = jsonresult;
                return;
            }
            string appid = request.Query.Where(x => x.Key == "appid").FirstOrDefault().Value;
            if (string.IsNullOrEmpty(appid))
            {
                var result = new ResultInfo(ApiResultState.NONAPPID, "appid无效");
                var jsonresult = new JsonResult(result);
                context.Result = jsonresult;
                return;
            }
            string ip = request.HttpContext.Connection.RemoteIpAddress.ToString();
            var res = await _businessApiService.IsWhiteIP(appid, ip);
            if (res.code != ApiResultState.SUCCESS)
            {
                var jsonresult = new JsonResult(res);
                context.Result = jsonresult;
                return;
            }
            var resultContext = await next();

            // 拦截之后

            // 异常拦截
            if (resultContext.Exception != null)
            {
                var action = $"{request.Path}{request.QueryString.Value}";
                _loggerService.AddErrorLogger(resultContext.Exception, $"appid={appid}", action);
            }
        }
    }

    public class WasteAuthorizeAttribute : Attribute, IAsyncActionFilter, IAsyncPageFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (OperatorProvider.Provider.GetCurrent() != null && (OperatorProvider.Provider.GetCurrent().UserId != Guid.Empty || OperatorProvider.Provider.GetCurrent().IsSuper))
            {
                _ = await next.Invoke();
                return;
            }

            context.Result = new StatusCodeResult(401);
        }

        public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
        {
            return Task.CompletedTask;
        }

        public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
        {
            if (OperatorProvider.Provider.GetCurrent() != null && (OperatorProvider.Provider.GetCurrent().UserId != Guid.Empty || OperatorProvider.Provider.GetCurrent().IsSuper))
            {
                _ = await next.Invoke();
                return;
            }

            context.Result = new StatusCodeResult(401);
        }
    }
}
