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
{
    /// <summary>
    /// 会员首页
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class DefaultAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            CurrentUser currentUser = filterContext.Controller.ViewBag.CurrentUser;
            MemberMenuBLL memberMenuBLL = new MemberMenuBLL();
            IEnumerable<dynamic> menuList = memberMenuBLL.GetList().Where(c => c.State == 1).OrderBy(c=>c.Xuhao);
            GetPermissions(filterContext, currentUser, menuList);
        }


        private void GetPermissions(ActionExecutingContext filterContext,CurrentUser currentUser, IEnumerable<dynamic> menuList)
        {
            string canTableIds = "", menuIds="";
            int departmentId = currentUser.DepartmentId;
            DepartmentBLL departmentBLL = new DepartmentBLL();
            if (!departmentBLL.IsExists(departmentId))
            {
                departmentId = 0;
            }
            if (departmentId > 0)
            {
                DepartmentPermissionsBLL departmentPermissions = new DepartmentPermissionsBLL();
                menuIds=departmentPermissions.GetMenuIds(departmentId);

                DepartmentInfoPermissionsBLL departmentInfoPermissionsBLL = new DepartmentInfoPermissionsBLL();
                canTableIds = departmentInfoPermissionsBLL.GetCanAdminTableIds(departmentId);
            }
            else
            {
                MemberGroupPermissionsBLL memberGroupPermissionsBLL = new MemberGroupPermissionsBLL();
                menuIds = memberGroupPermissionsBLL.GetMenuIds(currentUser.MemberGroupId);
                MemberGroupInfoPermissionsBLL memberGroupInfoPermissionsBLL = new MemberGroupInfoPermissionsBLL();
                canTableIds = memberGroupInfoPermissionsBLL.GetCanAdminTableIds(currentUser.MemberGroupId);
            }
            menuIds = StringHelper.Unique<int>(menuIds);
            if (string.IsNullOrEmpty(menuIds))
            {
                menuList = menuList.Where(c => c.Id == 0);
            }
            else
            {
                string[] arrMenuIds = menuIds.Split(',');
                menuList = menuList.Where(c => arrMenuIds.Contains<string>((string)(c.Id.ToString())));
            }
            filterContext.Controller.ViewBag.Menu = menuList;

            InfoTableBLL infoTableBLL = new InfoTableBLL();
            IEnumerable<dynamic> canAdminTableList = infoTableBLL.GetList(canTableIds);
            filterContext.Controller.ViewBag.CanAdminTableList = canAdminTableList.ToList().OrderBy(c => c.Xuhao);

        }
    }
}
