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

namespace PageAdmin.Web.Areas.Member.Controllers.InfoData
{
    /// <summary>
    /// 检测信息发布权限
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,Inherited = false)]
    public class CheckInfoPermissionsAttribute : ActionFilterAttribute
    {
        private CurrentUser _CurrentUser;
        private string _ActionName;
        private string _Table;
        private int _TableId = 0;
        private int _DepartmentId = 0;
        private dynamic  _Permissions;
        private string _Method;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _Method = filterContext.HttpContext.Request.HttpMethod.ToLower();
            _ActionName = filterContext.RouteData.Values["Action"].ToString();
            _CurrentUser = (CurrentUser)filterContext.Controller.ViewBag.CurrentUser;
            _DepartmentId = _CurrentUser.DepartmentId;
            CheckTable(filterContext);
            GetPermissions(filterContext);
            CheckPermissions(filterContext);
        }


        private void CheckTable(ActionExecutingContext filterContext)
        {
            InfoTableBLL infoTableBLL = new InfoTableBLL();
            _Table = filterContext.RequestContext.HttpContext.Request.QueryString["table"];
            _TableId = infoTableBLL.GetTableId(_Table);
            if (_TableId == 0)
            {
                NoPermission(filterContext, "无效的table参数!");
            }
        }

        private void GetPermissions(ActionExecutingContext filterContext)
        {
            DepartmentBLL departmentBLL = new DepartmentBLL();
            if (!departmentBLL.IsExists(_DepartmentId))
            {
                _DepartmentId = 0;
            }
            if (_DepartmentId > 0)
            {
                DepartmentInfoPermissionsBLL departmentInfoPermissionsBLL = new DepartmentInfoPermissionsBLL();
                _Permissions = departmentInfoPermissionsBLL.GetPermission(_TableId, _DepartmentId);
            }
            else
            {
                MemberGroupInfoPermissionsBLL memberGroupInfoPermissionsBLL = new MemberGroupInfoPermissionsBLL();
                _Permissions = memberGroupInfoPermissionsBLL.GetPermission(_TableId, _CurrentUser.MemberGroupId);
            }
            if (_Method == "get")
            {
                filterContext.Controller.ViewBag.Permissions= _Permissions;
            }
        }

        //检测权限
        private void CheckPermissions(ActionExecutingContext filterContext)
        {
            string actionName = filterContext.RouteData.Values["Action"].ToString();
            if (_Permissions.CanAdmin==0)
            {
                NoPermission(filterContext);
            }
            switch (actionName.ToLower())
            {
                case "add":
                    if(_Method=="get")
                    {
                        if (_Permissions.CanAdd == 0)
                        {
                            NoPermission(filterContext, "对不起，您没有添加内容的权限！");
                        }
                        CheckMaxNum(filterContext);
                    }
                    break;
                case "edit":
                    if (_Method == "get")
                    {
                        CheckEditPermissions(filterContext);
                    }
                    break;

                case "delete":
                    CheckDeletePermissions(filterContext);
                    break;
            }
        }

        //检测最大发布数
        private void CheckMaxNum(ActionExecutingContext filterContext)
        {
            int maxNum = _Permissions.MaxNum;
            if (maxNum == 0)
            {
                return;
            }
            else
            {
                DataBaseContext dbContext = DbHelper.DbContext();
                dbContext.SetDbParamter("uid", _CurrentUser.Uid);
                int count = (int)(dbContext.GetField(_Table, "count(id) as co", "uid=@uid") ?? 0);
                if (count>= maxNum)
                {
                    NoPermission(filterContext, "对不起，您当前账户最多只能发布"+ maxNum+"条信息！");
                }
            }
        }


        //检测编辑权限
        private void CheckEditPermissions(ActionExecutingContext filterContext)
        {
           byte canEdit = _Permissions.CanEdit;//2表示有编辑权限
            if (canEdit ==0)
            {
                NoPermission(filterContext,"对不起，您没有修改权限!");
            }
            else if (canEdit ==1)
            {
                int id = StringHelper.Format<int>(filterContext.HttpContext.Request["id"]);
                DataBaseContext dbContext = DbHelper.DbContext();
                object state = dbContext.GetField(_Table, "state", "id=" + id);
                if(state==null)
                {
                    NoPermission(filterContext, "对不起，当前内容已被删除!");
                }
                else if((short)state==1)
                {
                    NoPermission(filterContext,"对不起，当前内容已通过审核，您没有权限进行修改!");
                }
            }
        }


        //检测删除权限
        private void CheckDeletePermissions(ActionExecutingContext filterContext)
        {
            byte canDelete = _Permissions.CanDelete;
            if (canDelete ==0)
            {
                NoPermission(filterContext,"对不起，您没有删除权限!");
            }
            else if (canDelete ==1)
            {
                int id = StringHelper.Format<int>(filterContext.HttpContext.Request["id"]);
                DataBaseContext dbContext = DbHelper.DbContext();
                string state = (dbContext.GetField(_Table, "state", "id=" + id)??"0").ToString();
                if (state == null || state == "1")
                {
                    NoPermission(filterContext, "对不起，当前内容已通过审核，您没有权限删除!");
                }
            }
        }

     
        //无权限提示
        private void NoPermission(ActionExecutingContext filterContext,string modelText = "对不起，您没有当前内容的管理权限！")
        {
            bool isAjax = filterContext.RequestContext.HttpContext.Request.IsAjaxRequest();
            if (isAjax)
            {
                filterContext.Result = new ContentResult
                {
                    ContentType = "application/json",
                    Content = "{\"State\":\"0\",\"Msg\":\"" + modelText + "\"}"
                };
            }
            else
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "NoPermissions",
                    ViewData = new ViewDataDictionary(modelText)
                };
            }
        }
    }
}
