using RMYY_CallCenter_Api.Models;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace RMYY_CallCenter_Api.Filter
{
    public class AuthorizeFilter : AuthorizeAttribute
    {
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var ad = filterContext.ActionDescriptor;
            if (ad.IsDefined(typeof(AllowAnonymousAttribute), true)
                || ad.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }

            var context = filterContext.RequestContext.HttpContext;
            var header = context.Request.Headers;
            string token = ""; //context.Request["token"];
            if (header.AllKeys.Contains("Authorization"))
            {
                token = header["Authorization"].ToString().Substring(7);//Bearer token
                //LogHelper.Info(header["Authorization"].ToString());
            }
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    bool isAuth = false;
                    //获取FormsAuthenticationTicket对象
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
                    if (ticket != null && !ticket.Expired && !string.IsNullOrEmpty(ticket.UserData))
                    {
                        Dictionary<string, string> userData = ticket.UserData.ToObject<Dictionary<string, string>>();
                        if (userData != null)
                        {
                            var user = new Bll.T_Sys_UserAccount().GetModel(userData["F_UserCode"]);
                            if (user != null && user.F_RoleId.ToString() == userData["F_RoleId"])
                            {
                                string action = ad.ControllerDescriptor.ControllerName + "/" + ad.ActionName;
                                bool actionauth = Common.GetAuthActions().Contains(action.ToLower());
                                if ((actionauth && Common.GetRoleActions(user.F_RoleId).Contains(action.ToLower()))|| !actionauth || user.F_UserCode=="8000")
                                {
                                    isAuth = true;
                                    context.User = new FormsPrincipal<Model.T_Sys_UserAccount>(ticket, user);//重新给context.User赋值。
                                }
                                else
                                {
                                    context.Response.StatusCode = 200;
                                    filterContext.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = "无权限" }.ToJson() };
                                    return;
                                }
                            }
                        }
                    }
                    if (!isAuth)
                    {
                        context.Response.StatusCode = 200;
                        filterContext.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.notoken.ToString(), message = "token无效或过期，请重新登录。" }.ToJson() };
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error("身份验证失败", ex);
                    context.Response.StatusCode = 200;
                    filterContext.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.notoken.ToString(), message = "token无效或过期，请重新登录。" }.ToJson() };
                    return;
                }
            }
            else
            {
                context.Response.StatusCode = 200;
                filterContext.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.notoken.ToString(), message = "未传入token，请重新登录。" }.ToJson() };
                return;
            }

            if (filterContext != null)
            {
                base.OnAuthorization(filterContext);
            }
        }
    }
}