using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

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

    /// <summary>
    /// 注册特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class ConfigAttribute : ActionFilterAttribute
    {
        //检测验证码，判断登录等等
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (CookieHelper.Get("UserToken") != null)
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary()
                {
                   { "controller", "Default" },
                   { "action", "Index" }
                });
                return;
            }
            MemberGroupBLL memberGroupBLL = new MemberGroupBLL();
            dynamic configData = XmlHelper.AllNodeValue("configuration", "/Config/MemberReg.config",true);
            filterContext.Controller.ViewBag.Open = configData.Open;
            filterContext.Controller.ViewBag.MobileFieldSet = configData.MobileFieldSet;
            filterContext.Controller.ViewBag.EmailFieldSet = configData.EmailFieldSet;
            filterContext.Controller.ViewBag.VerificationCode = configData.VerificationCode;
            filterContext.Controller.ViewBag.MobileOnlyOne = configData.MobileOnlyOne;
            filterContext.Controller.ViewBag.EmailOnlyOne = configData.EmailOnlyOne;


            int defaultMemberGroupId = 1;
            defaultMemberGroupId = StringHelper.Format<int>(configData.DefaultMemberGroupId);
            int memberGroupId = StringHelper.Format<int>(filterContext.HttpContext.Request["memberGroupId"]);
            if (memberGroupId>0)
            {
                if(memberGroupBLL.CanReg(memberGroupId))
                {
                    defaultMemberGroupId = memberGroupId;
                }
            }
            filterContext.Controller.ViewBag.DefaultMemberGroupId = defaultMemberGroupId;

            FieldBLL fieldBll = new FieldBLL();
            IEnumerable<dynamic> fieldList;
            if(configData.ShowCustomField=="1")
            {
               fieldList = fieldBll.GetFieldList("pa_member", "add", null, FromEnum.Member);
            }
            else
            {
                fieldList = new List<dynamic>();
            }
            filterContext.Controller.ViewBag.FieldData = fieldList;

            IEnumerable<dynamic> canRegMemberGroupList = memberGroupBLL.GetList().Where(c => c.CanReg == 1).OrderBy(c=>c.Rank);
            filterContext.Controller.ViewBag.CanRegMemberGroupList = canRegMemberGroupList;
        }

    }
}
