using AutoTurnOver.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AutoTurnOver.Models
{
    public class NoLoginAttribute : Attribute
    {
    }

    public class UserFilterAttribute : ActionFilterAttribute
    {

        /// <summary>
        ///  请求验证，当前验证部分不要抛出异常，ExceptionFilter不会处理
        /// </summary>
        /// <param name="context">请求内容信息</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //filterContext.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
            var context = filterContext.HttpContext;

            var isDefined = false;
            var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor != null)
            {
                isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(NoLoginAttribute)));
            }
            if (!isDefined)
            {
                isDefined = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(NoLoginAttribute)));
            }
            if (isDefined) return;

            string token = context.Request.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(token))
            {
                token = context.Request.Query["token"].FirstOrDefault();
            }
            if (token != null)
            {
                var getTokenValid = ConfigHelper.GetValue("Saas_GetTokenValid").ToString();
                var getUser = ConfigHelper.GetValue("Saas_GetUser").ToString();

                var httpHelper = new HHttpHelper();
                httpHelper.AddHeaderValue("Authorization", token);
                string tokenValidJson = httpHelper.Request(getTokenValid, HHttpHelper.RequestType.GET);
                var objToken = tokenValidJson.ToObj<TokenResult>();
                if (objToken.result)
                {
                    var userInfo = context.Session.GetString("UserInfo");
                    if (string.IsNullOrWhiteSpace(userInfo))
                    {
                        string userStr = httpHelper.Request(getUser, HHttpHelper.RequestType.GET);
                        tokenUser user_info = userStr.ToObj<tokenUser>();
                        user_info.result.has_admin = false;
                        context.Session.SetString("UserInfo", user_info.result.ToJson());
                    }
                    return;
                }
                else
                {
                    context.Response.StatusCode = 401;
                    filterContext.Result = new ContentResult
                    {
                        Content = "未授权",
                        StatusCode = StatusCodes.Status401Unauthorized,
                        ContentType = "text/html;charset=utf-8"
                    };
                }
            }
            else
            {
                context.Response.StatusCode = 401;
                filterContext.Result = new ContentResult
                {
                    Content = "未授权",
                    StatusCode = StatusCodes.Status401Unauthorized,
                    ContentType = "text/html;charset=utf-8"
                };
            }

        }

    }
}
