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

namespace PageAdmin.Web.Areas.Admin.Controllers
{
    /// <summary>
    /// 检测信息发布权限,所有过滤器都是单例的
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,Inherited = false)]
    public class CheckInfoAdminPermissionsAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string actionName = filterContext.RouteData.Values["Action"].ToString();
            if (actionName == "GetFieldByIds" || actionName == "LoadListByIds") { return; } //根据id查找数据不进行权限检测
            int tableId = StringHelper.Format<int>(filterContext.Controller.ViewBag.TableId.ToString());
            CurrentUser currentUser = (CurrentUser)filterContext.Controller.ViewBag.CurrentUser;
            AdminInfoPermissionsBLL adminInfoPermissionsBll = new AdminInfoPermissionsBLL();
            dynamic permissionsData = adminInfoPermissionsBll.GetAdminPermission(tableId, currentUser);
            filterContext.Controller.ViewBag.PermissionsSet = permissionsData;
            CheckPermissions(filterContext,permissionsData, currentUser);//检测权限
            switch (actionName.ToLower())
            {
                case "listdata":
                case "pagelistdata":
                    GetListWere(filterContext,permissionsData, currentUser);//构造搜索条件
                    break;
            }
        }

        //检测权限
        private void CheckPermissions(ActionExecutingContext filterContext, dynamic permissionsData, CurrentUser currentUser)
        {
            string actionName = filterContext.RouteData.Values["Action"].ToString();
            ////检测是否推送信息
            //if (_actionName.ToLower() == "edit" && !_isAjax)
            //{
            //    CheckTargetSourceId();
            //}
            if (currentUser.IsSuperAdmin)//超级管理员则终止
            {
                return;
            }
            if (permissionsData.CanAdmin=="0")
            {
                NoPermission(filterContext);
            }
            switch (actionName.ToLower())
            {
                case "add":
                    if (permissionsData.CanAdd == "0")
                    {
                        NoPermission(filterContext,"对不起，您没有添加信息的权限！");
                    }
                    break;
                case "edit":
                    CheckEditPermissions(filterContext, permissionsData);
                    break;

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

        //检测编辑权限
        private void CheckEditPermissions(ActionExecutingContext filterContext, dynamic permissionsData)
        {
            string canEdit = permissionsData.CanEdit;//2表示有编辑权限
            if (canEdit == "0")
            {
                NoPermission(filterContext,"对不起，您没有修改信息的权限!");
            }
            else if (canEdit == "1")
            {
                string table = StringHelper.Format<string>(filterContext.HttpContext.Request.QueryString["table"]);
                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 CheckDeletePermissions(ActionExecutingContext filterContext, dynamic permissionsData)
        {
            string canDelete = permissionsData.CanDelete;
            if (canDelete == "0")
            {
                NoPermission(filterContext,"对不起，您没有删除信息的权限!");
            }
            else if (canDelete == "1")
            {
                string table = StringHelper.Format<string>(filterContext.HttpContext.Request.QueryString["table"]);
                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 GetListWere(ActionExecutingContext filterContext, dynamic permissionsData, CurrentUser currentUser)
        {
            DbKeyValueList dicParams = new DbKeyValueList();
            string listWhere = "";
            string canAdminColumnids;
            int tableId = StringHelper.Format<int>(filterContext.Controller.ViewBag.TableId.ToString());
            if (currentUser.IsSuperAdmin) //为空则表示具有所有权限
            {
                canAdminColumnids = new ColumnBLL().GetColumnIds(tableId);
            }
            else
            {
                canAdminColumnids = new ColumnBLL().GetColumnIds(tableId,currentUser);
            }
            int intColumnId = StringHelper.Format<int>(filterContext.HttpContext.Request.QueryString["columnId"]);
            if (intColumnId == 0)
            {
                if (currentUser.IsSuperAdmin)
                {
                    listWhere += "";
                }
                else if(!string.IsNullOrEmpty(canAdminColumnids))
                {
                    listWhere += " and columnId in(" + canAdminColumnids + ")";
                }
            }
            else if (canAdminColumnids.Split(',').Contains(intColumnId.ToString())) //当前id包含在了canAdminColumnids中
            {
                string subColumnIds = intColumnId.ToString()+","+CommonDataHelper.GetCacheChildrenIds("pa_column", intColumnId);
                if (string.IsNullOrEmpty(subColumnIds))
                {
                    subColumnIds = intColumnId.ToString();
                }
                string[] arrColumnIds = canAdminColumnids.Split(',').Intersect(subColumnIds.Split(',')).ToArray();
                string columnIds = string.Join(",", arrColumnIds);
                columnIds = StringHelper.Unique<int>(columnIds);
                if (StringHelper.IsInt(columnIds))
                {
                    dicParams.Add("columnId", int.Parse(columnIds));
                    listWhere += " and columnId=@columnId";
                }
                else if(!string.IsNullOrEmpty(columnIds))
                {
                    listWhere += " and columnId in(" + columnIds + ")";
                }
            }
            else //不包含则构造一个查不出的条件
            {
                listWhere += " and id=0";
            }
            if (!currentUser.IsSuperAdmin && permissionsData.ListOnlyMyself == "1")
            {
                dicParams.Add("uid", currentUser.Uid);
                listWhere += " and uid=@uid"; //只能查看自己的信息
            }
            filterContext.Controller.ViewBag.FilterListParam = dicParams;
            filterContext.Controller.ViewBag.FilterListWhere = listWhere;
        }


        //无权限提示
        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)
                };
            }
        }
    }
}
