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

namespace WebSite.Controllers
{
	public class WeiXinController : BaseController
	{
		private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(WeiXinController));
		public IHostManager HostManager { get; set; }
		public IHostModalManager HostModalManager { get; set; }
		public IHostAirManager HostAirManager { get; set; }
		public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }
		public ILightControlManager LightControlManager { get; set; }
		public ITvControlManager TvControlManager { get; set; }
		public IRoomTypeModalManager RoomTypeModalManager { get; set; }
		public IRoomServiceManager RoomServiceManager { get; set; }
		public IAlarmSettingManager AlarmSettingManager { get; set; }
		public ICurtainControlManager CurtainControlManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }
        public IUnlockControlManager UnlockControlManager { get; set; }
        public IMusicControlManager MusicControlManager { get; set; }
        public IAppMenuManager AppMenuManager { get; set; }
        public IRoomTypeWXMenusManager RoomTypeWXMenusManager { get; set; }

        public IList<RoomTypeWXMenus> WXMenuList;
        
        public ActionResult Index(string code, string creatDate)
        {
            SysHotel sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
            if (sysHotel == null)
            {
                ViewData["Error"] = "验证码有误，请联系管理员。";
                return View("Error");
            }
            else
            {
                CurrentHotelID = sysHotel.ID;//缓存当前酒店ID
                return Login();
            }
        }

        [HttpGet]
        public ActionResult Login()
        {
            if (Request.Cookies["WXRoomNumber"] == null)
            {
                ViewData["RoomNumber"] = "";
            }
            else
            {
                ViewData["RoomNumber"] = Request.Cookies["WXRoomNumber"].Value;
            }
            return View("Login");
        }

        [HttpPost]
        public ActionResult Login(string roomNumber, string identity)
        {
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    return Json(new { IsSuccess = false, Message = "无效房号或客房未出租。" });
                }
                else
                {
                    //using (ServiceReference1.syncstatusSoapClient wsClient = new ServiceReference1.syncstatusSoapClient())
                    //{
                    //    if (!wsClient.ValidateNumber(CurrentHotelID, roomNumber, identity))
                    //    {
                    //        return Json(new { IsSuccess = false, Message = "验证码有误。" });
                    //    }
                    //}
                }
                //获取微信显示的菜单
                WXMenuList = new List<RoomTypeWXMenus>();
                IList<RoomTypeWXMenus> WXMenus = RoomTypeWXMenusManager.LoadAll(host.RoomType.ID).Where(r => r.ActiveIndicator == true).ToList();
                if (WXMenus.Count == 0)
                {
                    return Json(new { IsSuccess = false, Message = "登录失败，原因：未设置微信菜单"  });
                }
                int width = 100 / WXMenus.Count;
                foreach (RoomTypeWXMenus menu in WXMenus)
                {
                    WXMenuList.Add(new RoomTypeWXMenus { Code = menu.Code, Name = menu.Name, Class = menu.Class, Width = width });
                }
                Session["WXMenuList"] = WXMenuList;
                Response.Cookies["WXRoomNumber"].Value = roomNumber;
                Response.Cookies["WXRoomNumber"].Expires = DateTime.Now.AddYears(1);

                return Json(new { IsSuccess = true, Message = "登录成功。", Target = "/WeiXin/" + WXMenuList[0].Code + "?RoomNumber=" + roomNumber });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = "登录失败，原因：" + ex.Message });
            }
        }
        /// <summary>
        /// 微信开锁
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
        public ActionResult Unlock(string roomNumber, string code, string creatDate)
        {
            if (!string.IsNullOrEmpty(code))
            {
                SysHotel sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
                if (sysHotel == null)
                {
                    ViewData["Error"] = "验证码有误，请联系管理员。";
                    return View("Error");
                }
                else
                {
                    CurrentHotelID = sysHotel.ID;//缓存当前酒店ID
                }
            }
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
                return View("Error");
            }
            ViewData["RoomNumber"] = roomNumber;
            return View();
        }
        /// <summary>
        /// 开锁控制
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UnlockControl(string roomNumber)
        {
            try
            {
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    return Json(new { IsSuccess = true, Message = "无效房号或客户未出租。" });
                }

                UnlockControlManager.Send(host);

                return Json(new { IsSuccess = true, Message = "开锁成功。" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = true, Message = "操作失败，原因：" + ex.Message });
            }
        }
        /// <summary>
        /// 灯光
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <param name="code"></param>
        /// <param name="creatDate"></param>
        /// <returns></returns>
        public ActionResult Light(string roomNumber, string code, string creatDate)
        {
            if (!string.IsNullOrEmpty(code))
            {
                SysHotel sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
                if (sysHotel == null)
                {
                    ViewData["Error"] = "验证码有误，请联系管理员。";
                    return View("Error");
                }
                else
                {
                    CurrentHotelID = sysHotel.ID;//缓存当前酒店ID
                }
            }
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
                return View("Error");
            }
            ViewData["RoomNumber"] = roomNumber;

            IList<HostModal> lightModals = HostModalManager.LoadAll().Where(r => r.HostID == host.ID && r.Modal.Name != null && r.Modal.Name != "" && r.Modal.ActiveIndicator == true).ToList();
            IList<Light> LightList = new List<Light>();
            IList<Light> DimmerList = new List<Light>();
            foreach (HostModal modal in lightModals)
            {
                switch (modal.Modal.Type)
                {
                    case DeviceType.Relay:
                    case DeviceType.Expand:
                        Light light = new Light { Name = ((Boolean)Session["isCN"]) ? modal.Modal.Name : modal.Modal.EnglishName, ModalAddress = modal.Modal.ModalAddress, Status = modal.Brightness };
                        LightList.Add(light);
                        break;
                    case DeviceType.Dimmer:
                    case DeviceType.PWMDimmer:
                    case DeviceType.PWMExpand:
                    case DeviceType.LVout://弱电输出
                    //case DeviceType.Strip:
                    case DeviceType.Traic:
                    case DeviceType.PB20:
                    case DeviceType.PB20_LD:
                    case DeviceType.PB20_LS:
                        Light dimmer = new Light { Name = ((Boolean)Session["isCN"]) ? modal.Modal.Name : modal.Modal.EnglishName, ModalAddress = modal.Modal.ModalAddress, Status = modal.Brightness };
                        DimmerList.Add(dimmer);
                        break;
                }
            }
            ViewData["LightList"] = LightList;
            ViewData["DimmerList"] = DimmerList;

            return View();
        }

        //public ActionResult LoadLightDimmer(string roomNumber)
        //{
        //    Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

        //    IList<HostModal> DimmerModals = HostModalManager.Load(host.ID, DeviceType.Dimmer).Where(r => r.Modal.AppApply).ToList();

        //    IList<Light> DimmerLightList = new List<Light>();

        //    bool isCN = (Request.Cookies["isCN"].Value == "zh-cn");

        //    foreach (HostModal modal in DimmerModals)
        //    {
        //        Light light = new Light { Name = isCN ? modal.Modal.Name : modal.Modal.EnglishName, ModalAddress = modal.Modal.ModalAddress, Status = modal.Brightness };

        //        DimmerLightList.Add(light);
        //    }

        //    return Json(DimmerLightList);
        //}

        [HttpPost]
        public ActionResult LightControl(string roomNumber, string groupAddress, int status)
        {
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
                    return View("Error");
                }
                if (!host.Status)
                {
                    string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

                    return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
                }
                ViewData["RoomNumber"] = roomNumber;

                var hostModal = HostModalManager.GetByModalAddress(host.ID, groupAddress);
                if (hostModal == null)
                {
                    ViewData["Error"] = "无效的灯光。";
                    return View("Error");
                }

                HostModalManager.SetDevice(host, hostModal, (status == 1 ? 1 : 2), status);

                return Json(new { IsSuccess = true, Message = "操作成功！" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = "操作失败，原因：" + ex.Message });
            }
        }
        /// <summary>
        /// 场景
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
        public ActionResult Scene(string roomNumber)
        {
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
                return View("Error");
            }
            ViewData["RoomNumber"] = roomNumber;

            IList<RoomTypeScene> modals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator == true).OrderBy(r => r.Sort).ToList(); ;
            List<SceneState> sceneList = new List<SceneState>();
            var lightState = new LightState();
            foreach (var modal in modals)
            {
                SceneState sceneState = new SceneState
                {
                    SceneID = modal.ID,
                    Name = modal.Name,
                    Icon = modal.Icon
                };
                sceneList.Add(sceneState);
            }
            ViewData["SceneList"] = sceneList;
            return View();
        }
        /// <summary>
        /// 场景控制
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <param name="sceneId"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult SceneControl(string roomNumber, int? sceneId)
		{
			try
			{
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
					return View("Error");
				}

				if (!host.Status)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

					return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
				}


				if (!sceneId.HasValue || sceneId == 0)
				{
					ViewData["Error"] = "无效的场景。";
					return View("Error");
				}


				var scene = RoomTypeSceneManager.Get(sceneId);
				if (scene == null)
				{
					return Json(new { IsSuccess = false, Message = "无效的场景。" });
				}

                LightControlManager.ApplyScene(host, scene);

				return Json(new { IsSuccess = true, Message = "设置场景成功！" });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}
		}
        /// <summary>
        /// 风扇
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
		public ActionResult Fan(string roomNumber)
		{
			ViewData["RoomNumber"] = roomNumber;

            Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
				return View("Error");
			}

            IList<HostModal> DimmerModals = HostModalManager.Load(host.ID, DeviceType.Dimmer).Where(r => r.Modal.Name != "" && r.Modal.Name != null).ToList();

			IList<Light> FanList = new List<Light>();

			foreach (HostModal modal in DimmerModals)
			{
                Light light = new Light { Name = ((Boolean)Session["isCN"]) ? modal.Modal.Name : modal.Modal.EnglishName, ModalAddress = modal.Modal.ModalAddress, Status = modal.Brightness };

				FanList.Add(light);
			}

			ViewData["FanList"] = FanList;

			return View();
		}
        /// <summary>
        /// 风扇控制
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <param name="groupAddress"></param>
        /// <param name="status"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult FanControl(string roomNumber, string groupAddress, int status)
		{
			try
			{
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
					return View("Error");
				}

				if (!host.Status)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

					return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
				}


				var hostModal = HostModalManager.GetByModalAddress(host.ID, groupAddress);
				if (hostModal == null)
				{
					ViewData["Error"] = "无效的灯光。";
					return View("Error");
				}

                HostModalManager.SetDevice(host, hostModal, (status != 0 ? 1 : 0), status);

				return Json(new { IsSuccess = true });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = true, Message = ex.Message });
			}
		}
        
		[HttpPost]
		public ActionResult LoadAirSetting(int hostId, int airId)
		{
			HostAir hostAir = HostAirManager.GetByModalTypeID(hostId, airId);

			object air = new
			{
				Running = hostAir.OnOff,
				SettingTemp = hostAir.SettingTemp,
				Speed = hostAir.Speed,
				HightTemp = hostAir.HightTemp,
				LowerTemp = hostAir.LowerTemp,
				Mode = hostAir.Mode
			};

			return Json(air);
		}

		[HttpGet]
		public ActionResult Air(string roomNumber)
		{
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
				return View("Error");
			}

			//var air = RoomTypeModalManager.Get(host.RoomType, "空调");
			//if (air == null)
			//{
			//    ViewData["Error"] = "无效的空调。";
			//    return View("Error");
			//}

			ViewData["RoomNumber"] = roomNumber;
			//ViewData["AirModalId"] = air.ModalID;

			return View();
		}

		public List<Air> ListAir(string roomNumber)
		{
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

			List<HostAir> hostAir = HostAirManager.LoadAll().Where(r => r.HostID == host.ID).ToList();

			List<Air> list = new List<Air>();

			foreach (HostAir item in hostAir)
			{
				Air air = new Air { HostID = item.HostID, Name = item.Modal.CustomerName, RoomTypeAirID = item.Modal.ModalType.ID };

				list.Add(air);
			}

			return list;

		}

		public ActionResult LoadAir(string roomNumber)
		{
			try
			{
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
					return View("Error");
				}

				List<Air> list = ListAir(roomNumber);

				if (list.Count <= 0)
				{
					ViewData["Error"] = "该房号未配置空调。";
					return View("Error");
				}

				return Json(list);
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}
		}

		[HttpPost]
		public ActionResult Air(string roomNumber, int airId, AirProperty property, int status)
		{
			try
			{
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
					return View("Error");
				}

				if (!host.Status)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

					return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
				}

				//if (host != null)
				//{
				//    HostAirManager.SetAirProperty(host, airId, property, status);
				//}

				if (host != null)
				{
					HostAirManager.SetAirProperty(host, airId, property, status);
				}

				return Json(new { IsSuccess = true, Message = "操作成功！" });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}
		}

		[HttpGet]
		public ActionResult Television(string roomNumber)
		{
			ViewData["RoomNumber"] = roomNumber;

            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
			if (host == null || host.RoomStatus.ID != 2)
			{
				throw new ApplicationException("无效房号或客户未出租。");
			}

			return View();
		}

		[HttpPost]
		public ActionResult Television(string roomNumber, TvKey key)
		{
			try
			{
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
					return View("Error");
				}

				if (!host.Status)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

					return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
				}

				TvControlManager.SendKey(host, key);

				return Json(new { IsSuccess = true, Message = "操作成功。" });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}
		}

		[HttpPost]
		public ActionResult Service(string roomNumber, string groupAddress, int status)
		{
			try
			{
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
				if (host == null || host.RoomStatus.ID != 2)
				{
					throw new ApplicationException("无效房号或客户未出租。");
				}

				if (!host.Status)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

					return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
				}

				if (String.IsNullOrEmpty(groupAddress))
				{
					throw new ApplicationException("无效的服务编号！");
				}
                if (groupAddress == "B09")//开锁
                {
                    UnlockControlManager.Send(host);
                }
                else
                {
                    RoomServiceManager.SetService(host, groupAddress, status);
                }

                return Json(new { IsSuccess = true, Message = "操作成功。" });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}

		}


		public ActionResult LoadAlarm(string roomNumber)
		{
            Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

            IList<AlarmSetting> AlarmList = AlarmSettingManager.LoadAll('B').Where(r => r.HotelID == CurrentHotelID).Where(r => r.AppApply).ToList();

			IList<AlarmService> Service = new List<AlarmService>();

			for (int i = 0; i < AlarmList.Count; i++)
			{
				AlarmService alarmService = new AlarmService();

				alarmService.Status = RoomServiceManager.Get(host.ID, AlarmList[i].Code).Status;
				alarmService.Name = AlarmList[i].Name;
				alarmService.Code = AlarmList[i].Code;

				Service.Add(alarmService);
			}

			return Json(Service);
		}

		[HttpGet]
        public ActionResult Service(string roomNumber, string code, string creatDate)
        {
            if (!string.IsNullOrEmpty(code))
            {
                SysHotel sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
                if (sysHotel == null)
                {
                    ViewData["Error"] = "验证码有误，请联系管理员。";
                    return View("Error");
                }
                else
                {
                    CurrentHotelID = sysHotel.ID;//缓存当前酒店ID
                }
            }
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
				return View("Error");
            }
			ViewData["RoomNumber"] = roomNumber;

            IList<HostModal> serviceModals = HostModalManager.Load(host.ID, DeviceType.ServiceInfo).Where(r => r.Modal.Name != null && r.Modal.Name != "" && r.Modal.ActiveIndicator == true).ToList();
            IList<Light> ServiceList = new List<Light>();
            foreach (HostModal modal in serviceModals)
            {
                Light light = new Light { Name = ((Boolean)Session["isCN"]) ? modal.Modal.Name : modal.Modal.EnglishName, ModalAddress = modal.Modal.ModalAddress, Status = modal.Brightness };
                ServiceList.Add(light);
            }
            ViewData["ServiceList"] = ServiceList;

			return View();
		}

        public ActionResult LoadCurtain(string roomNumber, DeviceType deviceType)
		{
			try
			{
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

				if (host == null)
				{
					throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoomNumber"));
				}

                //var hostModals = HostModalManager.Load(host.ID, deviceType).OrderBy(r => r.Modal.Sort).ToList();
                IList<HostModal> hostModals = HostModalManager.LoadAll().Where(r => r.HostID == host.ID && r.Modal.Type == DeviceType.Curtain
                    && r.Modal.Name != null && r.Modal.Name != "" && r.Modal.ActiveIndicator == true).ToList();

				var curtainList = new List<CurtainModel>();
                
				for (int i = 0; i < hostModals.Count; i++)
				{
					curtainList.Add(new CurtainModel() { Name = hostModals[i].Modal.Name, status = -1, curtainId = Convert.ToInt32(hostModals[i].Modal.ModalAddress) });
				}

				return Json(new { IsSuccess = true, Data = curtainList });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}
		}

		public class CurtainModel
		{
			public string Name { get; set; }

			public int curtainId { get; set; }

			public int status { get; set; }
		}


		//private CurtainModel CreateCurtainModel(IList<HostModal> hostModals)
		//{
		//    var curtain = new CurtainModel();

		//    bool isCN = (Request.Cookies["isCN"].Value == "zh-cn");

		//    if (hostModals.Count >= 2)
		//    {
		//        var curtainOpenModal = hostModals.FirstOrDefault(r => r.Modal != null &&
		//                                                            r.Modal.Subtype.HasValue &&
		//                                                            (r.Modal.Subtype.Value == DeviceSubtype.CurtainOpen ||
		//                                                            r.Modal.Subtype.Value == DeviceSubtype.GauzeOpen));
		//        if (curtainOpenModal != null) 

		//        {
		//            curtain.CurtainOpen = new CurtainOpenCloseModel
		//            {
		//                Address = curtainOpenModal.Modal.ModalAddress,
		//                Name = isCN ? curtainOpenModal.Modal.Name : curtainOpenModal.Modal.EnglishName,
		//                Subtype = curtainOpenModal.Modal.Subtype.Value,
		//                Status = curtainOpenModal.Status
		//            };
		//        }

		//        var closeSubtype = curtain.CurtainOpen.Subtype == DeviceSubtype.CurtainOpen ? DeviceSubtype.CurtainClose : DeviceSubtype.GauzeClose;

		//        var curtainCloseModal = hostModals.FirstOrDefault(r => r.Modal != null && r.Modal.Subtype.HasValue && r.Modal.Subtype.Value == closeSubtype);
		//        if (curtainCloseModal != null)
		//        {
		//            curtain.CurtainClose = new CurtainOpenCloseModel
		//            {
		//                Address = curtainCloseModal.Modal.ModalAddress,
		//                Name = isCN ? curtainCloseModal.Modal.Name : curtainCloseModal.Modal.EnglishName,
		//                Subtype = curtainCloseModal.Modal.Subtype.Value
		//            };
		//        }
		//    }

		//    return curtain;
		//}


		[HttpGet]
		public ActionResult Curtain(string roomNumber)
		{
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                ViewData["Error"] = "无效房号或客房未出租。";
				return View("Error");
			}

			ViewData["RoomNumber"] = roomNumber;

			return View();
		}

		[HttpPost]
		public ActionResult Curtain(string roomNumber, int CurtainId, CurtainCtrl ctrl)
		{
			try
			{
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

				if (host == null || host.RoomStatus.ID != 2)
				{
					throw new ApplicationException("无效房号或客户未出租。");
				}

				if (!host.Status)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);

					return Json(new { IsSuccess = false, Message = "操作失败，原因：" + message });
				}

				CurtainControlManager.SendCtrl(host, CurtainId, ctrl);

				return Json(new { IsSuccess = true, Message = "操作成功。" });
			}
			catch (Exception ex)
			{
				return Json(new { IsSuccess = false, Message = ex.Message });
			}
        }

        [HttpGet]
        public ActionResult Music(string roomNumber)
        {
            ViewData["RoomNumber"] = roomNumber;

            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null || host.RoomStatus.ID != 2)
            {
                throw new ApplicationException("无效房号或客户未出租。");
            }

            return View();
        }

        [HttpPost]
        public ActionResult Music(string roomNumber, MusicKey key)
        {
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null || host.RoomStatus.ID != 2)
                {
                    ViewData["Error"] = "无效房号或客房未出租。";
                    return View("Error");
                }

                MusicControlManager.SendKey(host, key);

                return Json(new { IsSuccess = true, Message = "操作成功。" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }
        /// <summary>
        /// 小白调用
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <param name="RobotAction"></param>
        /// <returns></returns>
        public ActionResult GetRobotAction(string roomNumber, string RobotAction)
        {
            Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

            if (host == null)
            {
                return Json(new { IsSuccess = false, Result = "房号未知，请联系管理员。" }, JsonRequestBehavior.AllowGet);
            }

            string[] item = RobotAction.Split('|');

            if (item.Length > 0)
            {
                if (item[0] == "Light")
                {
                    string groupAddress = item[1];

                    int status = Convert.ToInt32(item[2]);

                    LightControl(roomNumber, groupAddress, status);

                    return Json(new { IsSuccess = true, Result = "灯光下发成功" }, JsonRequestBehavior.AllowGet);

                }
                else if (item[0] == "Scene")
                {
                    int sceneId = Convert.ToInt32(item[1]);

                    SceneControl(roomNumber, sceneId);

                    return Json(new { IsSuccess = false, Result = "场景下发成功" }, JsonRequestBehavior.AllowGet);
                }
                else if (item[0] == "Air")
                {
                    List<Air> list = ListAir(roomNumber);

                    Air air = list[0];

                    AirProperty property = (AirProperty)Enum.Parse(typeof(AirProperty), item[1]);

                    Air(roomNumber, air.RoomTypeAirID, property, int.Parse(item[2]));

                    return Json(new { IsSuccess = true, Result = "空调下发成功" }, JsonRequestBehavior.AllowGet);

                }
                else if (item[0] == "Television")
                {
                    TvKey key = (TvKey)Enum.Parse(typeof(TvKey), item[1]);
                    Television(roomNumber, key);

                    return Json(new { IsSuccess = true, Result = "电视下发成功" }, JsonRequestBehavior.AllowGet);
                }
                else if (item[0] == "Curtain")
                {
                    //Curtain(roomNumber, item[1], 0);
                    //Curtain(roomNumber, item[2], 0);
                    //Curtain(roomNumber, item[3], int.Parse(item[4]));
                    CurtainCtrl key = (CurtainCtrl)Enum.Parse(typeof(CurtainCtrl), item[2]);
                    Curtain(roomNumber, Convert.ToInt32(item[1]), key);
                    return Json(new { IsSuccess = true, Result = "窗帘下发成功" }, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(new { IsSuccess = false, Result = "未知，请联系管理员。" }, JsonRequestBehavior.AllowGet);
        }

        //private void CreateWeiXinJsApiConfig()
        //{
        //    var accessToken = Common.MemoryCacheHelper.Get("WeiXinAccessToken", "") as Common.WeiXinAccessToken;
        //    if (accessToken == null)
        //    {
        //        accessToken = Common.WeiXinHelper.GetAccessToken();
        //        if (accessToken.ErrorCode == 0)
        //        {
        //            Common.MemoryCacheHelper.Set("WeiXinAccessToken", accessToken, DateTimeOffset.Now.AddSeconds(accessToken.ExpiresIn));
        //        }
        //    }

        //    var jsApiTicket = Common.MemoryCacheHelper.Get("WeiXinJsApiTicket", "") as Common.WeiXinJsApiTicket;
        //    if (jsApiTicket == null)
        //    {
        //        jsApiTicket = Common.WeiXinHelper.GetJsApiTicket(accessToken.AccessToken);
        //        if (jsApiTicket.ErrorCode == 0)
        //        {
        //            Common.MemoryCacheHelper.Set("WeiXinJsApiTicket", jsApiTicket, DateTimeOffset.Now.AddSeconds(jsApiTicket.ExpiresIn));
        //        }
        //    }

        //    string noncestr = Common.WeiXinHelper.CreateNonceStr();

        //    int timestamp = Common.WeiXinHelper.GetCurrentTimeStamp();

        //    string signature = Common.WeiXinHelper.CreateJsApiSignature(jsApiTicket.Ticket, noncestr, timestamp, Request.Url.AbsoluteUri);

        //    ViewData["AppId"] = Common.WeiXinHelper.AppId;
        //    ViewData["Timestamp"] = timestamp;
        //    ViewData["NonceStr"] = noncestr;
        //    ViewData["Signature"] = signature;
        //    ViewData["JsApiTicket"] = jsApiTicket.Ticket;
        //}

        public ActionResult Error(string msg)
        {
            ViewData["Error"] = msg;

            return View();
        }
	}
	/// <summary>
	/// 灯光状态类
	/// </summary>
	public class LightState
	{
		public string ModalID { get; set; }

		public string Name { get; set; }

		public int Status { get; set; }
	}
	/// <summary>
	/// 场景类
	/// </summary>
	public class SceneState
	{
		public int SceneID { get; set; }

		public string Name { get; set; }

		public string Icon { get; set; }
	}
}
