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 GroupController : BaseController
    {
        private const int AuthorityID = 30;

		public IGroupManager GroupManager { get; set; }

		public IHostManager HostManager { get; set; }

		public ISysUserManager SysUserManager { get; set; }

		#region Action

		//
        // GET: /Group/

        public ActionResult Index()
        {
            return View();
		}

		public ActionResult Edit(int? id, int? parentId)
		{
			if (id.HasValue)
			{
				return View(GroupManager.Get(id));
			}			
			return View(new Group { ID = 0, Name = "", Parent = new Group { ID = parentId.GetValueOrDefault() }, Sort = 1 });
		}

		[Authorize]
        public ActionResult LoadGroupTree(int? hotelID) 
		{
            if (!hotelID.HasValue)
            {
                hotelID = CurrentHotelID;
            }
            IList<Group> groups = GroupManager.LoadAll().Where(r => r.HotelID == hotelID).ToList();
			return Json(BuildGroupTree(groups, null), JsonRequestBehavior.AllowGet);
		}

        [Authorize]
        public ActionResult LoadGroupTree2(int? hotelID)
        {
            if (!hotelID.HasValue || hotelID == 0)
            {
                hotelID = CurrentHotelID;
            }
            return Json(GroupManager.CreateGroupTree(null, Convert.ToInt16(hotelID)), JsonRequestBehavior.AllowGet);
        }

		[Authorize]
		public ActionResult LoadGroupTreeWithRoom()
		{
            var groupTree = GroupManager.CreateGroupTreeWithRoom(null, null, CurrentHotelID);
			return Json(groupTree, JsonRequestBehavior.AllowGet);
		}

        [Authorize]
        public ActionResult LoadCurrentUserGroupTree()
        {
            SysUsers currentUser = SysUserManager.Get(User.Identity.Name);
            if (currentUser.HotelID > 0 && currentUser.Group == null)//酒店用户没有楼层分组权限
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
            IList<object> groupTree = new List<object>();
            groupTree.Add(new { id = 0, text = HttpContext.InnerLanguage("HotelFloor"), iconCls = "tree-node-no-icon" });
            //如果该用户所在分组同属于当前酒店，则获取该分组下客房，否则获取该酒店下所有客房
            if (currentUser.Group != null && currentUser.Group.HotelID == CurrentHotelID)
            {
                groupTree.Add(GroupManager.CreateGroupTree2(currentUser.Group, CurrentHotelID));
            }
            else
            {
                IList<Group> currentGroup = GroupManager.GetGroupList(CurrentHotelID);
                if (currentGroup.Count > 0)
                {
                    groupTree.Add(GroupManager.CreateGroupTree2(currentGroup[0], CurrentHotelID));
                }
            }

            return Json(groupTree, JsonRequestBehavior.AllowGet);
        }

		#region 加载控件数据
		
		[Authorize]
		public ActionResult LoadDataForGroupComboTree()
		{
			SysUsers currentUser = SysUserManager.Get(User.Identity.Name);
			if (currentUser.Group == null)
			{
				return Json(null, JsonRequestBehavior.AllowGet);
			}
			IList<object> groupTree = new List<object>();
            //如果该用户所在分组同属于当前酒店，则获取该分组下客房，否则获取该酒店下所有客房
            if (currentUser.Group.HotelID == CurrentHotelID)
            {
                groupTree.Add(GroupManager.CreateGroupTree2(currentUser.Group, CurrentHotelID));
            }
            else
            {
                IList<Group> currentGroup = GroupManager.GetGroupList(CurrentHotelID);
                groupTree.Add(GroupManager.CreateGroupTree2(currentGroup[0], CurrentHotelID));
            }

			return Json(groupTree, JsonRequestBehavior.AllowGet);
		}

		#endregion

		[Authorize]
		[HttpPost]
		public ActionResult Save(string jsonData) 
		{
			try
			{
				Group entity = Newtonsoft.Json.JsonConvert.DeserializeObject<Group>(jsonData);
                entity.HotelID = CurrentHotelID;
				if (entity.ID == 0)
				{
					GroupManager.Save(entity);
				}
				else
				{
					GroupManager.Update(entity);
				}

				SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), entity.Name);

				return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
			}
		}

		[Authorize]
		[HttpPost]
		public ActionResult Delete(int id) 
		{
			try
			{
				SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Delete"), GroupManager.Get(id).Name);

                GroupManager.Delete(id);

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

			}
			catch (ApplicationException ex) 
			{
				return Json(new { IsSuccess = true, Message = ex.Message });
			}
		}

		#endregion

		#region Private Methods

		/// <summary>
		/// 构造楼层树，用于 easyui-treegrid
		/// </summary>
		/// <param name="groups"></param>
		/// <param name="parent"></param>
		/// <returns></returns>
		private IList<object> BuildGroupTree(IList<Group> groups, Group parent) 
		{
			IList<object> groupTree = new List<object>();

			IList<Group> subGroups = groups.Where(r => r.Parent == parent).OrderBy(o => o.Sort).ToList();

			foreach (Group group in subGroups)
			{
				IList<object> children = BuildGroupTree(groups, group);
				
				if (children.Count != 0)
				{
					groupTree.Add(new { ID = group.ID, Name = group.Name, Sort = group.Sort, children = children });
				}
				else
				{
					groupTree.Add(new { ID = group.ID, Name = group.Name, Sort = group.Sort});
				}
			}

			return groupTree;
		}

		/// <summary>
		/// 构造当前用户所属楼层树
		/// </summary>
		/// <param name="groups"></param>
		/// <param name="group"></param>
		/// <returns></returns>
		private object BuildCurrentUserGroupTree(IList<Group> groups, Group group)
		{
			IList<Group> subGroups = groups.Where(r => r.Parent == group).OrderBy(o => o.Sort).ToList();

			if (subGroups.Count == 0)
			{
				return new { id = group.ID, text = group.Name, iconCls = "tree-node-no-icon" };
			}
			
			IList<object> children = new List<object>();

			foreach (Group subGroup in subGroups)
			{
				children.Add(BuildCurrentUserGroupTree(groups, subGroup));
			}

			return new { id = group.ID, text = group.Name, iconCls = "tree-node-no-icon", children = children };
		}

		#endregion

	}
}
