using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Utils;
using System;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.Member.Controllers.FindPassword
{

    /// <summary>
    /// 找回密码 安全验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class ConfirmValidateAttribute : ActionFilterAttribute
    {
        private TipsInfo _TipsInfo = null;
        //检测验证码，判断登录等等
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _TipsInfo = new TipsInfo();
            ValidateFindUser(filterContext);//检测手机验证码
        }

        /// <summary>
        /// 检测验证码
        /// </summary>
        /// <param name="filterContext"></param>
        private void ValidateFindUser(ActionExecutingContext filterContext)
        {
           string cookieKey = "_FindUserName";
            string userName = CookieHelper.Get(cookieKey);
            if (userName == null)
            {
                Error(filterContext);
                return;
            }
            userName = EncryptHelper.DesDecrypt(userName, SystemConfig.Get().SecretKey);
            if (userName == null)
            {
                Error(filterContext);
                return;
            }
            MemberBLL memberBLL = new MemberBLL();
            dynamic data = memberBLL.GetData(userName);
            if (data == null)
            {
                Error(filterContext);
                return;
            }
            int uid = data.Id;
            CurrentUser currentUser = memberBLL.GetUser(uid);
            if (currentUser == null)
            {
                Error(filterContext);
                return;
            }
            if(data.EmailState==0)
            {
                currentUser.Email = "";
            }
            if (data.MobileState == 0)
            {
                currentUser.Mobile="";
            }
            filterContext.Controller.ViewBag.FindUser = currentUser;
        }


        //无权限提示
        private void Error(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    ContentType = "application/json",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { State = 0, Msg = "对不起，参数错误！" }
                };
            }
            else
            {
                filterContext.RouteData.DataTokens["area"] = "Member";
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new
                {
                    action = "Index"
                }));
            }
        }
    }
}
