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

namespace CallCenterApi.Interface
{
    public class AuthorityAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            var 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)
                        {
                            var user = new BLL.T_Sys_UserAccount().GetModel(userData["F_UserCode"]);
                            if (user != null && user.F_RoleId.ToString() == userData["F_RoleID"])
                            {
                                isAuth = true;
                                context.User = new FormsPrincipal<Model.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)
                {
                    WriteLog(filterContext, "验证失败：" + ex.ToString());
                    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);
            }
        }
        private void WriteLog(AuthorizationContext filterContext,string error)
        {
            var log = LogFactory.GetLogger(filterContext.Controller.ToString()+"/"+ filterContext.ActionDescriptor.ActionName);
            log.Error(error);
        }

    }
}