using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace CallCenterApi.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 (!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)
                        {
                            T_Sys_UserAccount user = new T_Sys_UserAccount();
                            var usercache = CacheHelper.Get<T_Sys_UserAccount>(userData["F_UserCode"]);
                            if (usercache == null)
                            {
                                user = new BLL.T_Sys_UserAccount().GetModel(userData["F_UserCode"]);
                                CacheHelper.Insert(userData["F_UserCode"], user, 60);
                            }
                            else
                            {
                                user = usercache;
                            }
                            if (user != null && user.F_RoleId.ToString() == userData["F_RoleId"])
                            {
                                isAuth = true;
                                context.User = new FormsPrincipal<T_Sys_UserAccount>(ticket, user);//重新给context.User赋值。
                            }
                        }
                    }
                    if (!isAuth)
                    {
                        context.Response.StatusCode = 200;
                        filterContext.Result = new ContentResult { Content = new AjaxResult { state = ResultTypes.notoken.ToString(), message = "token无效或过期，请重新登录。" }.ToJson() };
                        return;
                    }
                }
                catch (Exception ex)
                {
                    var log = LogFactory.GetLogger(filterContext.Controller.ToString());
                    log.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);
            }
        }
    }
}