using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace System.Web.Mvc
{
    /// <summary>
    /// 登录验证
    /// </summary>    
    public class LF : ActionFilterAttribute
    {
        /// <summary>
        /// 是否登录验证
        /// </summary>
        public bool IsLoginFilter = true;
        /// <summary>
        /// 维护站点是否可以访问
        /// </summary>
        public bool IsMaintenance = true;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #region url处理
            var url = filterContext.HttpContext.Request.Url.ToString();

            if (WebManage.IsAllowVisit(url) != true)
            {
                filterContext.Result = new RedirectResult(RFrameGenerate.Common.CurrentManage.Domain + "error/index");
                return;
            }

            if (url.IndexOf(".shop.") != -1 && filterContext.HttpContext.Request.RawUrl == "/")
            {
                filterContext.Result = new RedirectResult(url + "WxShop/Index?s=" + DateTime.Now.Second + "&inviter=0");//跳到首页,s为总部标签
                return;
            }
            else if (url.IndexOf(".shop.") != -1 && filterContext.HttpContext.Request.RawUrl.ToLower() == "/wxshop/index")
            {
                filterContext.Result = new RedirectResult(url + "?m=" + DateTime.Now.Second + "&inviter=0");//跳到首页,m为个人标签
                return;
            }

            if (IsMaintenance == true && RFrameGenerate.Common.CurrentManage.IsMaintenance == true && url.Contains("shop.official") != true && url.Contains("wxbd8a7ff14b976781.shop.") != true && url.Contains("jioushuiguo.shop.") != true && url.Contains("http://ticket.") != true)
            {
                filterContext.Result = new RedirectResult(RFrameGenerate.Common.CurrentManage.Domain + "home/maintenance");
            }

            #endregion
            #region 登录过滤

            if (IsLoginFilter)
            {
                var Request = filterContext.HttpContext.Request;
                string CookieUrl = !Request.IsAjaxRequest() ? Request.Url.PathAndQuery : Request.UrlReferrer.PathAndQuery;
                if (CookieUrl.ToLower() != "/theme/main/control")
                    Utils.WriteCookie(SessionKeys.COOKIE_URL_REFERRER, CookieUrl, 24);

                if (CurrentUser.GetCurrUserGuid() == null || CurrentUser.GetCurrUserGuid() == Guid.Empty)//是否登录
                {
                    AjaxRequest.IsAjaxRequest(filterContext);
                }
                else
                {
                    if (IsApplicationDropped(filterContext))
                    {
                        filterContext.HttpContext.Response.Write("<script>alert('您的帐号已被强制下线，请您重新登录！');window.location.replace('" + CurrentManage.OfflineLoginResult + "');</script>");
                        CurrentUser.SetCurrUser(null, null);
                    }
                }
            }

            #endregion
        }

        /// <summary>
        /// 获取IP
        /// </summary>
        /// <returns></returns>
        protected string GetIP(HttpRequestBase Request)
        {
            string ip = string.Empty;
            if (!string.IsNullOrEmpty(Request.ServerVariables["HTTP_VIA"]))
                ip = Convert.ToString(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            if (string.IsNullOrEmpty(ip))
                ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
            return ip;
        }
        /// <summary>
        /// 判断用户是否Application掉线
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        public static bool IsApplicationDropped(ActionExecutingContext filterContext)
        {
            if (CurrentManage.ApplicationSignOutSwitch)
            {
                var Application = filterContext.HttpContext.Application;
                var Session = filterContext.HttpContext.Session;
                Hashtable hOnline = (Hashtable)Application["Online"];
                if (hOnline != null)
                {
                    if (hOnline.ContainsKey(Session.SessionID) == true && hOnline[Session.SessionID].ToString() == "_repetition_")
                    {
                        hOnline.Remove(Session.SessionID);
                        return true;
                    }
                }
            }
            return false;
        }
    }
    /// <summary>
    /// 权限验证
    /// </summary>
    public class PF : ActionFilterAttribute
    {
        private List<string> codeList = new List<string>();

        public PF(string param)
        {
            codeList.Add(param);
        }

        public PF(Type param)
        {
            Type type = param;
            object[] tables = type.GetCustomAttributes(typeof(RemarkAttribute), true);
            if (tables.Length > 0)
                codeList.Add(((RemarkAttribute)(tables[0])).Value);
            else
                codeList.Add(((RemarkAttribute)Activator.CreateInstance(typeof(RemarkAttribute))).Value);
        }

        public PF(params string[] param)
        {
            codeList = param.ToList();
        }

        PermissionManage permissionManage = new PermissionManage();
        /// <summary>
        /// 是否权限验证
        /// </summary>
        public bool IsPermissionFilter = false;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (IsPermissionFilter)
            {
                if (permissionManage.IsPermission(CurrentUser.GetCurrUserGuid(), codeList) == false)
                {//没权限跳到登录页面      
                    AjaxRequest.IsAjaxRequest(filterContext);
                }
            }
        }
    }
    //结合 jqueryOverride.min.js
    public sealed class AjaxRequest
    {
        public static void IsAjaxRequest(ActionExecutingContext filterContext)
        {
            var Request = filterContext.HttpContext.Request;
            if (Request.IsAjaxRequest())
            {
                if (Request.Form["page"] != "yes")
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new { Result = "NoRight" }
                    };
                }
                else
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new { Result = "PageNoRight" }
                    };
                }
            }
            else
            {
                CurrentUser.SetCurrUser(string.Empty, null);
                Utils.WriteCookie(SessionKeys.COOKIE_URL_REFERRER, "", 24);
                if (CurrentManage.OfflineLoginResult.ToLower().Contains("?") == true)
                    filterContext.Result = new RedirectResult(CurrentManage.OfflineLoginResult + "&p=1");
                else
                    filterContext.Result = new RedirectResult(CurrentManage.OfflineLoginResult + "?p=1");
            }
        }
    }

    //public sealed class RequestDeal
    //{
    //    public static bool AR(ActionExecutingContext filterContext)
    //    {
    //        var Request = filterContext.HttpContext.Request;
    //        var Response = filterContext.HttpContext.Response;
    //        if (Request.IsAjaxRequest() != true && Request.Url.AbsolutePath.ToLower().StartsWith("/home/load") != true && Request.QueryString.AllKeys.Contains("c-l") != true)
    //        {
    //            string url = Request.Url.ToString();
    //            if (url.Contains("?") == true)
    //                filterContext.HttpContext.Session["RedirUrl"] = Request.Url.ToString() + "&c-l=" + url.GetHashCode();
    //            else
    //                filterContext.HttpContext.Session["RedirUrl"] = Request.Url.ToString() + "?c-l=" + url.GetHashCode();

    //            filterContext.HttpContext.Session["UrlReferrer"] = Request.UrlReferrer;

    //            filterContext.Result = new RedirectResult("/Home/Load");
    //            return true;
    //        }
    //        return false;
    //    }
    //}
}