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

namespace WebSite.Controllers
{
    public class RoomCardController : BaseController
    {
		public IRoomCardManager RoomCardManager { get; set; }

		public IRoomCardTypeManager RoomCardTypeManager { get; set; }

        public ActionResult Index()
        {
			#if SIMON
			return View("SimonIndex");
			#else
            return View();
			#endif
        }

		public ActionResult Edit(int? id)
		{
			if (id.HasValue)
			{
				return View(RoomCardManager.Get(id.Value));
			}

            return View(new RoomCard { ID = 0, CardNumber = "", RoomCardType = null, UserNumber = "", UserName = "", Sort = 1 });
		}

        [Authorize]
        public ActionResult LoadAllByPage(int page, int rows, string order, string sort)
        {
            long total = 0;

            var list = RoomCardManager.LoadAllByPage(out total, page, rows, order, sort, CurrentHotelID);

            var result = list.Select(r => new
            {
                r.ID,
                r.CardNumber,
                CardTypeID = r.RoomCardType.ID,
                CardType = r.RoomCardType.Name,
                r.UserNumber,
                r.UserName,
                r.Sort
            }).ToList();

            return Json(new { total = result.Count, rows = result });
        }

		[Authorize]
		public ActionResult LoadRoomCardTypes()
		{
            var list = RoomCardTypeManager.LoadAll();
			return Json(list);
		}

		[Authorize]
		public ActionResult Save(string jsonData)
		{
			var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<RoomCard>(jsonData);

            var existRoomCard = RoomCardManager.GetByCarNumber(entity.CardNumber, CurrentHotelID);
			if (existRoomCard != null && (entity.ID == 0 || entity.ID != existRoomCard.ID))
			{
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("CardNumber") + "【" + entity.CardNumber + "】" + HttpContext.InnerLanguage("AlreadyExist") });
			}

			if (entity.ID == 0)
            {
                entity.HotelID = CurrentHotelID;
				RoomCardManager.Save(entity);
			}
			else
			{
				var roomCard = RoomCardManager.Get(entity.ID);
				roomCard.CardNumber = entity.CardNumber;
                roomCard.RoomCardType = entity.RoomCardType;
				roomCard.UserNumber = entity.UserNumber;
				roomCard.UserName = entity.UserName;
                roomCard.Sort = entity.Sort;
                roomCard.HotelID = CurrentHotelID;

				RoomCardManager.Update(roomCard);
			}

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

		[Authorize]
		public ActionResult Delete(IList<int> idList)
		{
			RoomCardManager.Delete(idList.Cast<object>().ToList());

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