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

namespace WebSite.Controllers
{
    public class SysUserController : BaseController
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SysUserController));
		private const int AuthorityID = 51;

		public ISysUserManager SysUserManager { get; set; }
		public ISysRoleManager SysRoleManager { get; set; }
        public IGroupManager GroupManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }
        public ISysHotelGroupManager SysHotelGroupManager { get; set; }

		#region Action

        [Authorize]
        public ActionResult Index()
        {
            switch (User.Identity.Name.ToLower())
            {
                case "admin":
                case "blw":
                    ViewData["Account"] = true;
                    break;
                default:
                    ViewData["Account"] = false;
                    break;
            }
            return View("SimonIndex");
        }

		[Authorize]
		public ActionResult Edit(int? id)
		{
			if (id.HasValue)
			{
				return View(SysUserManager.Get(id));
			}
			var model = new SysUsers { ID = 0, Account = "", Role = null, Group = null, ActiveIndicator = true, Sort = 1, Remark = "" };
			return View(model);
		}

		public ActionResult ChangePassword(int id)
		{
			ViewData["ID"] = id;
			return View();
		}

		[Authorize]
		[HttpPost]
		public ActionResult ChangePassword(int id, string password)
		{
			if (String.IsNullOrEmpty(password))
			{
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("ThePasswordCanNotBeEmptyPleaseReEnter") });
			}
			SysUsers user = SysUserManager.Get(id);
			if (user != null)
			{
				SysUserManager.Update(user, password);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("ResetPassword"), user.Account);
			}
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("PasswordResetSuccess") });
		}

        [Authorize]
        public ActionResult LoadAllByPage(string order, string sort, int? groupId)//int page, int rows, 
        {
            if (groupId.HasValue)
            {
                //long total = 0;
                //IList<SysUsers> list = this.SysUserManager.LoadAllByPage(out total, page, rows, order, sort, 1, groupId, CurrentHotelID);

                IList<SysUsers> list = this.SysUserManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && !r.IsDeleted
                    && (r.Group.ID == groupId || (r.Group.Parent != null && r.Group.Parent.ID == groupId)
                    || (r.Group.Parent != null && r.Group.Parent.Parent != null && r.Group.Parent.Parent.ID == groupId))).ToList();
                
                IList<object> result = new List<object>();
                foreach (var user in list)
                {
                    result.Add(new
                    {
                        ID = user.ID,
                        Account = user.Account,
                        RoleID = user.Role != null ? user.Role.ID.ToString() : "",
                        RoleName = user.Role != null ? user.Role.Name : "",
                        GroupID = user.Group != null ? user.Group.ID.ToString() : "",
                        GroupName = GroupManager.BuildGroupName(user.Group),
                        //SysHotelGroupName = SysHotelGroupManager.BuildGroupName(user.SysHotelGroup),
                        ActiveIndicator = user.ActiveIndicator,
                        Sort = user.Sort,
                        Remark = user.Remark,
                        CreatedBy = user.CreatedBy,
                        CreatedDate = user.CreatedDate,
                        ModifiedBy = user.ModifiedBy,
                        ModifiedDate = user.ModifiedDate,
                        HotelID = user.HotelID,
                        Password2 = user.Password2
                        //HotelName = ReturnNameByLanguage(hotel.Name, hotel.EName, hotel.TWName)
                    });
                }
                return Json(new { total = result.Count, rows = result });
            }
            else
            {
                return Json(new { total = 0, rows = new List<object>() });
            }
        }

        [Authorize]
        public ActionResult AuthorityHotel(int id)
        {
            return View(new SysUsers { ID = id });
        }

        //[Authorize]
        //public ActionResult LoadAuthorityHotel(int userID)
        //{
        //    IList<object> tree = new List<object>();
        //    var hotelList = SysHotelManager.LoadAll().OrderBy(o => o.Sort).OrderBy(o => o.SysHotelGroup.Sort).ToList();
        //    var userHotelList = SysUserManager.Get(userID).Hotels;
        //    foreach (SysHotel hotel in hotelList)
        //    {
        //        bool check = false;
        //        foreach (SysHotel userHoltel in userHotelList)
        //        {
        //            if (hotel.ID == userHoltel.ID)
        //            {
        //                check = true;
        //                break;
        //            }
        //        }
        //        tree.Add(new
        //        {
        //            id = hotel.ID,
        //            text = hotel.Code + " -> " + SysHotelGroupManager.BuildGroupName(hotel.SysHotelGroup) + " -> " + ReturnNameByLanguage(hotel.Name, hotel.EName, hotel.TWName),
        //            @checked = check
        //        });
        //    }
        //    return Json(tree, JsonRequestBehavior.AllowGet);
        //}
        /// <summary>
        /// 保存授权酒店
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="hotelID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveAuthorityHotel(int userID, IList<int> hotelIDs)
        {
            var user = SysUserManager.Get(userID);
            user.Hotels.Clear();
            foreach (int hotelID in hotelIDs)
            {
                user.Hotels.Add(SysHotelManager.Get(hotelID));
            }
            SysUserManager.SaveOrUpdate(user);

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

        [Authorize]
        public ActionResult Save(string jsonData)
        {
            var user = Newtonsoft.Json.JsonConvert.DeserializeObject<SysUsers>(jsonData);
            try
            {
                var existUser = SysUserManager.Get(user.Account);
                IList<SysHotel> hotels = new List<SysHotel>();
                hotels.Add(SysHotelManager.Get(CurrentHotelID));
                if (user.ID == 0)
                {
                    if (null != existUser)
                    {
                        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("Account") + "【" + user.Account + "】" + HttpContext.InnerLanguage("AlreadyExist") });
                    }
                    user.Name = user.Account;
                    user.CreatedBy = user.ModifiedBy = this.User.Identity.Name;
                    user.CreatedDate = user.ModifiedDate = DateTime.Now;
                    user.Hotels = hotels;
                    user.HotelID = CurrentHotelID;

                    SysUserManager.Save(user);
                    SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("New"), user.Account);
                }
                else
                {
                    var currentUser = SysUserManager.Get(user.ID);
                    if (existUser != null && existUser.ID != currentUser.ID)
                    {
                        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("Account") + "【" + user.Account + "】" + HttpContext.InnerLanguage("AlreadyExist") });
                    }
                    currentUser.Account = user.Account;
                    currentUser.Role = user.Role;
                    currentUser.Group = user.Group;
                    //currentUser.SysHotelGroup = user.SysHotelGroup;
                    currentUser.ActiveIndicator = user.ActiveIndicator;
                    currentUser.Sort = user.Sort;
                    currentUser.Remark = user.Remark;
                    currentUser.ModifiedBy = User.Identity.Name;
                    currentUser.ModifiedDate = DateTime.Now;
                    currentUser.HotelID = CurrentHotelID;

                    SysUserManager.Update(currentUser);
                    SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), user.Account);
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }

        [Authorize]
        public ActionResult Delete(IList<int> idList, IList<string> nameList)
        {
            //SysUserManager.Delete(idList.Cast<object>().ToList());
            foreach (int id in idList)
            {
                SysUsers user = SysUserManager.Get(id);
                user.IsDeleted = true;
                SysUserManager.Update(user);
            }
            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Delete"), string.Join(",", nameList));
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
        }

        private IList<SysHotel> GetHotels(IList<int> hotelIDs)
        {
            IList<SysHotel> hotels = new List<SysHotel>();
            if (hotelIDs != null)
            {
                foreach (int hotelID in hotelIDs)
                {
                    var hotel = SysHotelManager.Get(hotelID);
                    if (hotel != null && !hotels.Contains(hotel))
                    {
                        hotels.Add(hotel);
                    }
                }
            }
            return hotels;
        }

		#endregion
	}
}
