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

namespace WebSite.Controllers
{
    public class AppController : BaseController
    {
        #region Properties

        public IHostManager HostManager { get; set; }

        public IHostModalManager HostModalManager { get; set; }

        public IHostAirManager HostAirManager { get; set; }

        public IRoomServiceManager RoomServiceManager { get; set; }

        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }

        public ILightControlManager LightControlManager { get; set; }

        public IAppRoomManager AppRoomManager { get; set; }

        public IAppHotelManager AppHotelManager { get; set; }

        public IAppMenuManager AppMenuManager { get; set; }

        public ITvControlManager TvControlManager { get; set; }

        public IRoomTypeModalManager RoomTypeModalManager { get; set; }

        public IAlarmSettingManager AlarmSettingManager { get; set; }

        #endregion

        public ActionResult Login(string mac)
        {
            if (!Regex.IsMatch(mac, @"^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$") &&
                !Regex.IsMatch(mac, @"^\d{6}$"))
            {
                return Json(new { IsSuccess = false, Result = "房号未知，请联系管理员。" }, JsonRequestBehavior.AllowGet);
            }

            AppRoom appRoom = AppRoomManager.GetRoomNumber(mac);
            if (appRoom == null)
            {
                appRoom = new AppRoom();
                appRoom.MAC = mac;
                appRoom.RoomNumber = "";
                AppRoomManager.Save(appRoom);

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

            if (!String.IsNullOrEmpty(appRoom.RoomNumber))
            {
                return Json(new { IsSuccess = true, Result = appRoom.RoomNumber }, JsonRequestBehavior.AllowGet);
            }

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

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

            if (host != null)
            {
                ViewData["RoomNumber"] = host.RoomNumber;
                //ViewData["CurrentTemp"] = host.CurrentTemp;

                IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID);

                var list = HostAirManager.LoadAll().Where(r => r.HostID == host.ID).Take(1).Select(r => r.CurrentTemp).ToList();

                if (list.Count() > 0)
                {
                    ViewData["Temp"] = list[0];
                }
            }
            else
            {
                ViewData["RoomNumber"] = "";
                ViewData["CurrentTemp"] = "";
                ViewData["Temp"] = 0;
                ViewData["AlarmList"] = new List<AlarmService>();
            }

            var AppMenus = AppMenuManager.LoadAll().Where(r => r.ActiveIndicator == true).OrderBy(r => r.Sort).ToList();

            ViewData["AppMenuControl"] = AppMenus;

            ViewData["Date"] = DateTime.Now.ToString("dd/MM");
            ViewData["Week"] = GetWeek(DateTime.Now.DayOfWeek);


            return View();
        }


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

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

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

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

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

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

                Service.Add(alarmService);
            }

            return Json(Service);
        }

        public ActionResult Validate(string roomNumber)
        {
            if (String.IsNullOrEmpty(roomNumber))
            {
                return Content("房号不能为空。");
            }

            Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null)
            {
                return Content("无效的房号。");
            }

            return Content(String.Empty);
        }

        [HttpPost]
        public ActionResult ServiceControl(string roomNumber, string groupAddress, int status)
        {
            try
            {
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null)
                {
                    throw new ApplicationException("无效的房号！");
                }

                if (String.IsNullOrEmpty(groupAddress))
                {
                    throw new ApplicationException("无效的服务编号！");
                }

                RoomServiceManager.SetService(host, groupAddress, status);

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

        }

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

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

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

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

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

                lightList.Add(light);
            }

            ViewData["LightList"] = lightList;

            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
            {
                Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null)
                {
                    throw new ApplicationException("无效的房号。");
                }

                var hostModal = HostModalManager.GetByModalAddress(host.ID, groupAddress);
                if (hostModal == null)
                {
                    throw new ApplicationException("无效的灯光。");
                }

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

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

        public ActionResult Television(string roomNumber)
        {
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null)
            {
                throw new ApplicationException("无效的房号。");
            }

            return View();
        }

        [HttpPost]
        public ActionResult Television(string roomNumber, TvKey key)
        {
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

                if (host == null)
                {
                    throw new ApplicationException("无效的房号。");
                }

                TvControlManager.SendKey(host, key);

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

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

            if (host == null)
            {
                throw new ApplicationException("无效的房号。");
            }

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

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

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

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

                list.Add(air);
            }

            return Json(list);
        }
        [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);
        }

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

            if (host == null)
            {
                throw new ApplicationException("无效的房号。");
            }

            return View();
        }

        [HttpPost]
        public ActionResult AirConditionControl(string roomNumber, int hostId, int airId, AirProperty property, int status)
        {
            Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

            if (host == null)
            {
                throw new ApplicationException("无效的房号。");
            }

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

            return Json(new { IsSuccess = true });
        }

        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();
                if (hostModals.Count % 2 != 0)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("CurtainConfigNotCorrect"));
                }

                var curtainList = new List<CurtainModel>();

                var num = hostModals.Count / 2;
                for (int i = 0; i < num; i++)
                {
                    var curtain = CreateCurtainModel(hostModals.Skip(i * 2).Take(2).ToList());
                    if (curtain.CurtainOpen == null ||
                        curtain.CurtainClose == null)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("CurtainConfigNotCorrect"));
                    }

                    curtainList.Add(curtain);
                }

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

        public ActionResult CurtainControl(string roomNumber)
        {
            var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

            if (host == null)
            {
                throw new ApplicationException("无效的房号。");
            }

            return View();
        }

        [HttpPost]
        public ActionResult CurtainControl(string roomNumber, string groupAddress, int status)
        {
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);

                if (host == null)
                {
                    throw new ApplicationException("无效的房号。");
                }

                HostModalManager.UpdateHostModalStatus(host, groupAddress, status);

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

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

            List<RoomTypeScene> list = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID).OrderBy(r => r.Sort).ToList();

            ViewData["AppSceneControl"] = list;

            return View();
        }

        [HttpPost]
        public ActionResult Scene(string roomNumber, int sceneID)
        {
            Host host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
            if (host == null && sceneID < 1)
            {
                return Json(new { IsSuccess = false, Message = "无效的房号。" });
            }

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

            LightControlManager.ApplyScene(host, scene);

            return Json(new { IsSuccess = true, Message = "设置场景成功！" });
        }

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

        public ActionResult HotelIntroduction()
        {
            IList<AppHotel> result = AppHotelManager.LoadAll().ToList();

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

            foreach (AppHotel appHotel in result)
            {
                if (!isCN)
                {
                    if (appHotel.Code == "H03")
                    {
                        ViewData["HoteName"] = appHotel.Value;
                    }
                    else if (appHotel.Code == "H04")
                    {
                        ViewData["Introduction"] = appHotel.Value;
                    }
                }
                else
                {
                    if (appHotel.Code == "H01")
                    {
                        ViewData["HoteName"] = appHotel.Value;
                    }
                    else if (appHotel.Code == "H02")
                    {
                        ViewData["Introduction"] = appHotel.Value;
                    }
                }
            }
            return View();
        }

        public ActionResult About()
        {
            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            version = version.Substring(0, version.LastIndexOf("."));

            ViewData["Version"] = version;

            return View();
        }

        #region Private Methods

        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;
        }

        /// <summary>
        /// 转换星期到中文+英文简写形式
        /// </summary>
        /// <param name="week"></param>
        /// <returns></returns>
        private string GetWeek(DayOfWeek week)
        {
            switch (week)
            {
                case DayOfWeek.Monday:
                    return "Mon.";
                case DayOfWeek.Tuesday:
                    return "Tues.";
                case DayOfWeek.Wednesday:
                    return "Wed.";
                case DayOfWeek.Thursday:
                    return "Thur.";
                case DayOfWeek.Friday:
                    return "Fri.";
                case DayOfWeek.Saturday:
                    return "Sat.";
                case DayOfWeek.Sunday:
                    return "Sun.";
                default:
                    return "";
            }
        }

        #endregion
    }

    public class Air
    {
        public string Name { get; set; }
        public string ModalAddress { get; set; }
        public int HostID { get; set; }
        public int RoomTypeAirID { get; set; }
        public int Status { get; set; }//空调开关状态，2/关，1/开
        public int CurrentTemp { get; set; }
        public int SettingTemp { get; set; }
        public int Mode { get; set; }
        public int FanSpeed { get; set; }
        public int Valve { get; set; }
    }

    public class Curtain
    {
        public string ModalAddress { get; set; }
        public string Name { get; set; }
        public int Status { get; set; }
    }

    public class Music
    {
        /// <summary>
        /// 回路名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 回路地址
        /// </summary>
        public string ModalAddress { get; set; }
        /// <summary>
        /// 1开，2关
        /// </summary>
        public int Status { get; set; }
        /// <summary>
        /// 音量大小1~10
        /// </summary>
        public int Brightness { get; set; }
        /// <summary>
        /// 1播放，2暂停，3上一曲，4下一曲，5音量加，6音量减
        /// </summary>
        public int Mode { get; set; }
    }

    public class Light
    {
        public string ModalAddress { get; set; }
        public string Name { get; set; }
        public int Status { get; set; }
        public int Brightness { get; set; }
    }

    public class AlarmService
    {
        public string Code { get; set; }
        public string Name { get; set; }
        public bool Status { get; set; }
    }
}
