using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Service;
using Domain;

namespace WebSite.Controllers
{
    public class SysRoleController : BaseController
    {
        private const int AuthorityID = 50;
        public ISysRoleManager SysRoleManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public ISysAuthorityManager SysAuthorityManager { get; set; }
        public ISysHotelGroupManager SysHotelGroupManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }

        #region Action

        [Authorize]
        public ActionResult Index()
        {
            return View("SimonIndex");
        }

        [Authorize]
        public ActionResult Edit(int? id)
        {
            if (id.HasValue)
            {
                return View(SysRoleManager.Get(id));
            }

            return View(new SysRole { ID = 0, Name = "", Sort = 1, Remark = "" });
        }

        //[Authorize]
        //public ActionResult LoadAllByPage(int page, int rows, string order, string sort)
        //{
        //    long total = 0;
        //    var list = this.SysRoleManager.LoadAllByPage(out total, page, rows, order, sort);

        //    var result = new { total = total, rows = list };

        //    return Json(result);
        //}
        /// <summary>
        /// 装载到下拉框控件
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadAll()
        {
            SysUsers user = this.SysUserManager.Get(User.Identity.Name);//当前用户角色不装载出来
            IList<SysRole> roles = SysRoleManager.LoadAll().Where(r => r.ID != user.Role.ID && r.HotelID == CurrentHotelID).OrderBy(o => o.Sort).ToList();
            IList<object> result = new List<object>();
            foreach (SysRole role in roles)
            {
                result.Add(new { ID = role.ID, Name = role.Name });
            }
            return Json(result);
        }
        /// <summary>
        /// 角色管理主页面显示
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadAll2(int? groupId)
        {
            IList<object> result = new List<object>();
            try
            {

                SysUsers user = this.SysUserManager.Get(User.Identity.Name);//当前用户角色不装载出来
                IList<SysRole> roles = SysRoleManager.LoadAll().Where(r => r.ID != user.Role.ID && r.HotelID == CurrentHotelID).OrderBy(o => o.HotelID).ThenBy(o => o.Sort).ToList();
                foreach (SysRole role in roles)
                {
                    if (role.Authorities.Count > 0)
                    {
                        var nnn = role.Authorities.Select(r => ReturnNameByLanguage(r.Name, r.EName, r.TWName)).ToArray();
                        string authorities = String.Join("、", nnn);
                        if (!string.IsNullOrEmpty(authorities))
                        {
                            result.Add(new { ID = role.ID, Name = role.Name, Sort = role.Sort, Authorities = authorities });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return Json(new { IsSuccess = true, data = result }, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult Save(int id, string name, int sort, IList<int> authorities)//,int sysHotelGroupID
        {
            SysRole existRole = this.SysRoleManager.Get(name);
            SysRole entity = new SysRole();
            var newAuthorities = GetAuthorities(authorities);

            if (id == 0)
            {
                //新增
                if (null != existRole)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("RoleName") + "【" + name + "】" + HttpContext.InnerLanguage("AlreadyExist") });
                }

                entity.ID = id;
                entity.Name = name;
                entity.Authorities = newAuthorities;
                entity.Sort = sort;
                entity.ActiveIndicator = true;
                entity.CreatedBy = entity.ModifiedBy = this.User.Identity.Name;
                entity.CreatedDate = entity.ModifiedDate = DateTime.Now;
                entity.HotelID = CurrentHotelID;
                entity.SysHotelGroup = new SysHotelGroup();// SysHotelGroupManager.Get(sysHotelGroupID);酒店角色无分组

                SysRoleManager.Save(entity);

                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("New"), name);
            }
            else
            {
                //更新
                var role = this.SysRoleManager.Get(id);

                if (existRole != null && existRole.ID != role.ID)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("RoleName") + "【" + name + "】" + HttpContext.InnerLanguage("AlreadyExist") });
                }

                role.Name = name;
                role.Authorities.Clear();
                role.Authorities = newAuthorities;
                role.Sort = sort;
                role.ModifiedBy = this.User.Identity.Name;
                role.ModifiedDate = DateTime.Now;
                //role.HotelID = CurrentHotelID;//不修改所属酒店
                //role.SysHotelGroup = SysHotelGroupManager.Get(sysHotelGroupID);

                SysRoleManager.Update(role);

                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), name);
            }

            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }

        [HttpPost]
        [Authorize]
        public ActionResult Delete(int id)
        {
            try
            {
                SysRole role = this.SysRoleManager.Get(id);

                if (role.Name == HttpContext.InnerLanguage("SuperAdministrator"))
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("SuperAdministratorRoleCanNotBeDeleted"));
                }

                this.SysRoleManager.Delete(id);

                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Delete"), role.Name);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (ApplicationException ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }
        /// <summary>
        /// 通过角色获取对应的权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoleAuthorities(int? roleId)
        {
            IList<SysAuthority> allAuthorities = SysAuthorityManager.LoadAll().Where(r => r.ParentID == 0 || r.ParentID == 1000).ToList();//获取第一层功能权限和第一级别菜单权限
            SysRole userRole = SysUserManager.Get(User.Identity.Name).Role;//当前登录用户角色
            IList<SysAuthority> userAuthority = new List<SysAuthority>();//当前登录用户角色权限
            foreach (var authority in userRole.Authorities)
            {
                userAuthority.Add(authority);
                var parentNode = userRole.Authorities.Where(r => r.ID == authority.ParentID).FirstOrDefault();//判断其上级菜单是否存在，如果不存在，则添加进来
                if (parentNode == null && !userAuthority.Contains(parentNode))
                {
                    userAuthority.Add(allAuthorities.Where(r => r.ID == authority.ParentID).FirstOrDefault());
                }
            }
            var first = allAuthorities.Where(r => r.ID == 1000).FirstOrDefault();//后台菜单权限：解决二级菜单全都没有打勾的问题
            if (!userAuthority.Contains(first))
            {
                userAuthority.Add(first);
            }
            SysRole editRole = null;//当前编辑的角色
            if (roleId.HasValue)
            {
                editRole = SysRoleManager.Get(roleId);
            }
            return Json(BuildAuthoritiesTree(userAuthority, editRole, 0), JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult SaveRoleAuthorities(int roleId, IList<int> authorityIdList)
        {
            try
            {
                SysRoleManager.SaveRoleAuthorities(roleId, authorityIdList);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (ApplicationException ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }

        #endregion

        /// <summary>
        /// 构造权限树，用于设置角色权限
        /// </summary>
        /// <param name="role"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private IList<object> BuildAuthoritiesTree(IList<SysAuthority> userAuthority, SysRole editRole, int parentId)
        {
            IList<object> authoritiesTree = new List<object>();
            IList<SysAuthority> authorities = SysAuthorityManager.GetAuthorities(parentId);
            foreach (SysAuthority authority in authorities)
            {
                IList<object> children = BuildAuthoritiesTree(userAuthority, editRole, authority.ID);
                bool hasAuthority = false;
                if (editRole != null)
                {
                    hasAuthority = editRole.Authorities.Contains(authority);
                }
                if (authority.ActiveIndicator)
                {
                    if (User.Identity.Name.ToLower() == "admin" || (User.Identity.Name.ToLower() != "admin" && userAuthority.Contains(authority)))
                    {
                        if (children.Count != 0)
                        {
                            authoritiesTree.Add(new { id = authority.ID, text = ReturnNameByLanguage(authority.Name, authority.EName, authority.TWName), @checked = hasAuthority, children = children });
                        }
                        else
                        {
                            authoritiesTree.Add(new { id = authority.ID, text = ReturnNameByLanguage(authority.Name, authority.EName, authority.TWName), @checked = hasAuthority });
                        }
                    }
                }
            }
            return authoritiesTree;
        }

        private IList<SysAuthority> GetAuthorities(IList<int> authorityIDs)
        {
            IList<SysAuthority> authorities = new List<SysAuthority>();
            if (authorityIDs != null)
            {
                foreach (int authorityId in authorityIDs)
                {
                    var authority = SysAuthorityManager.Get(authorityId);
                    if (authority != null && !authorities.Contains(authority))
                    {
                        authorities.Add(authority);
                    }
                }
            }
            return authorities;
        }
    }
}
