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

		public IModelManager ModelManager { get; set; }

		public IHostManager HostManager { get; set; }

		public IGroupManager GroupManager { get; set; }

		#region Action

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

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

			IList<object> result = new List<object>();

			foreach(var model in list)
			{
				result.Add(new 
				{ 
					ID = model.ID,
					Name = model.Name,
					CorrectedTemp = model.CorrectedTemp,
					FanRunStatus = model.FanRunStatus,
					ExhaustFanStatus = model.ExhaustFanStatus,
					ExhausFanTime = model.ExhausFanTime,
					InfraredDelayPO = model.InfraredDelayPO,
					DoorDelayPO = model.DoorDelayPO,
					PullCardDelayPO = model.PullCardDelayPO,
					Remark = model.Remark,
					ModifiedDate = model.ModifiedDate,
					ApplyDate = model.ApplyDate,
					ApplyUser = model.ApplyUser
				});
			}

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

		[Authorize]
		public ActionResult LoadModelDetail(int? modelId)
		{
			IList<object> details = new List<object>();

			if (modelId.HasValue)
			{
				Model model = ModelManager.Get(modelId);
				if (model != null && model.Details != null)
				{
					foreach(ModelDetail detail in model.Details) {
						details.Add(new 
						{
							ID = detail.ID,
							ModelStatus = detail.ModelStatus,
							OnOff = detail.OnOff,
							ModelType = detail.ModelType,
							Speed = detail.Speed,
							SummerTemp = detail.SummerTemp,
							WinterTemp = detail.WinterTemp,
							TimingControl = detail.TimingControl,
							Timer = detail.Timer,
							AllowElectric = detail.AllowElectric
						});
					}
				}
			}
			else 
			{
				details.Add(new { ID = 0, ModelStatus = "插卡时", OnOff = true });
				details.Add(new { ID = 0, ModelStatus = "拔卡时", OnOff = true });
				details.Add(new { ID = 0, ModelStatus = "待租时", OnOff = true });
				details.Add(new { ID = 0, ModelStatus = "停租时", OnOff = true });
			}

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

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

				entity.ModifiedDate = DateTime.Now;
				entity.Remark = "";

				Model existModel = ModelManager.GetByName(entity.Name);

				if (entity.ID == 0)
				{
					if (existModel != null) {
                        throw new ApplicationException(HttpContext.InnerLanguage("ConfigurationName") + "【" + entity.Name + "】" + HttpContext.InnerLanguage("AlreadyExist"));
					}

					if (entity.Details != null)
					{
						foreach (ModelDetail detail in entity.Details)
						{
							detail.Model = entity;
						}
					}

                    ModelManager.Save(entity);

					SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("New"), entity.Name);
				}
				else
				{
					if (existModel != null && existModel.ID != entity.ID) 
					{
                        throw new ApplicationException(HttpContext.InnerLanguage("ConfigurationName") + "【" + entity.Name + "】"+ HttpContext.InnerLanguage("AlreadyExist"));
					}

					var model = this.ModelManager.Get(entity.ID);

					model.Name = entity.Name;
					model.CorrectedTemp = entity.CorrectedTemp;
					model.FanRunStatus = entity.FanRunStatus;
					model.ExhaustFanStatus = entity.ExhaustFanStatus;
					model.ExhausFanTime = entity.ExhausFanTime;
					model.InfraredDelayPO = entity.InfraredDelayPO;
					model.DoorDelayPO = entity.DoorDelayPO;
					model.PullCardDelayPO = entity.PullCardDelayPO;

					CopyModelDetail(model.Details.FirstOrDefault(r => r.ModelStatus == "插卡时"), entity.Details.FirstOrDefault(r => r.ModelStatus == "插卡时"));
					CopyModelDetail(model.Details.FirstOrDefault(r => r.ModelStatus == "拔卡时"), entity.Details.FirstOrDefault(r => r.ModelStatus == "拔卡时"));
					CopyModelDetail(model.Details.FirstOrDefault(r => r.ModelStatus == "待租时"), entity.Details.FirstOrDefault(r => r.ModelStatus == "待租时"));
					CopyModelDetail(model.Details.FirstOrDefault(r => r.ModelStatus == "停租时"), entity.Details.FirstOrDefault(r => r.ModelStatus == "停租时"));

					ModelManager.Update(model);

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

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

		[Authorize]
        public ActionResult Delete(IList<int> idList, IList<string> nameList)
		{
            ModelManager.Delete(idList.Cast<object>().ToList());
            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Delete"), string.Join(",", nameList));
			return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
		}

		[Authorize]
		public ActionResult Apply(int modelID, string hostIDs)
		{
			IList<int> ids = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<int>>(hostIDs);

			Model model = ModelManager.Get(modelID);
			if (model == null)
			{
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("InvalidAirConditioningEnergySavingSolutions") });
			}

			IList<Host> hosts = new List<Host>();
			foreach (int id in ids)
			{
				Host host = HostManager.Get(id);
				if (host != null)
				{
					hosts.Add(host);
				}
			}

			ModelManager.ApplyModel(model, hosts, User.Identity.Name);

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

		[Authorize]
		public ActionResult LoadGroupTreeWithRoom(int? modelID)
		{
			IList<Host> appliedHosts = new List<Host>();

			if (modelID.HasValue)
			{
				Model model = ModelManager.Get(modelID);
				if (!String.IsNullOrEmpty(model.Hosts))
				{
					IList<int> hostIDs = model.Hosts.Split(',').Select(r => Convert.ToInt32(r)).ToList();
					foreach (int id in hostIDs)
					{
						appliedHosts.Add(HostManager.Get(id));
					}
				}
			}

            var groupTree = GroupManager.CreateGroupTreeWithRoom(null, appliedHosts, CurrentHotelID);
			return Json(groupTree, JsonRequestBehavior.AllowGet);
		}

		private void CopyModelDetail(ModelDetail modelDetail1, ModelDetail modelDetail2)
		{
			if (modelDetail1 != null && modelDetail2 != null)
			{
				modelDetail1.OnOff = modelDetail2.OnOff;
				modelDetail1.ModelType = modelDetail2.ModelType;
				modelDetail1.Speed = modelDetail2.Speed;
				modelDetail1.SummerTemp = modelDetail2.SummerTemp;
				modelDetail1.WinterTemp = modelDetail2.WinterTemp;
				modelDetail1.TimingControl = modelDetail2.TimingControl;
				modelDetail1.Timer = modelDetail2.Timer;
				modelDetail1.AllowElectric = modelDetail2.AllowElectric;
			}
		}

		#endregion

	}
}
