using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Common;
using Domain;
using Service;
using WebSite.Models;
using System.Text;
using CommonEntity;
using System.Web.Caching;

namespace WebSite.Controllers
{
    public class RoomStatusController : BaseController
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RoomStatusController));
        public IHostManager HostManager { get; set; }
        //阿宝添加的
        public ISysHotelManager SysHotelManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public IGroupManager GroupManager { get; set; }
        public IRoomStatusManager RoomStatusManager { get; set; }
        public IRoomServiceManager RoomServiceManager { get; set; }
        public IAlarmSettingManager AlarmSettingManager { get; set; }
        public IHostModalManager HostModalManager { get; set; }
        public IHostFaultsManager HostFaultsManager { get; set; }



        //阿宝添加的
        public ICarbonVIPMananger CarbonVIPManager { get; set; }

        /// <summary>
        /// LieECO Manager
        /// </summary>
        public ILieECOMananger LieECOManager { get; set; }
        /// <summary>
        /// 空调设置权限ID
        /// </summary>
        private const int AUTHORITY_AIRSETTING = 1002;

        #region Action

        [Authorize]
        public ActionResult Index()
        {
            return View("SimonIndex");
        }
        /// <summary>
        /// 客房详细
        /// </summary>
        /// <param name="hostID"></param>
        /// <returns></returns>
        public ActionResult RoomDetail(int hostID)
        {
            Host host = HostManager.Get(hostID);
            if (host == null)
            {
                ViewData["ErrorMsg"] = HttpContext.InnerLanguage("InvalidRoom");
                return View("Error");
            }

            //ViewData["ConnectingRooms"] = HostManager.GetConnectRoomHosts(host);
            //获取服务信息
            IList<string> services = new List<string>();
            //var currentServices = RoomServiceManager.LoadCurrentRoomServices(host.ID);
            var currentServices = HostModalManager.Load(hostID, DeviceType.ServiceInfo).Where(r => r.Modal.Name != "" && r.Status == 1);
            foreach (var service in currentServices)
            {
                services.Add(ReturnNameByLanguage(service.Modal.Name, service.Modal.EnglishName, service.Modal.TWName));
            }
            ViewData["Services"] = services;
            //获取故障信息
            //IList<string> abnormities = new List<string>();
            //var currentAbnormities = HostFaultsManager.LoadCurrentHostFault(host.ID); //.LoadAll().Where(r => r.HostID == host.ID);
            //foreach (var abnormity in currentAbnormities)
            //{
            //    string strFault = (Language == Domain.Language.CN) ? Convert.ToString(((object[])(abnormity))[3]) : Convert.ToString(((object[])(abnormity))[4]);
            //    strFault += "(" + Convert.ToString(((object[])(abnormity))[0]) + ",";
            //    switch (Convert.ToInt16(((object[])(abnormity))[1]))
            //    {
            //        case 1://状态
            //            strFault += HttpContext.InnerLanguage("Status") + ":";
            //            if (Convert.ToInt16(((object[])(abnormity))[2]) == 0)
            //            {
            //                strFault += HttpContext.InnerLanguage("Online");
            //            }
            //            else
            //            {
            //                strFault += HttpContext.InnerLanguage("Offline");
            //            }
            //            break;
            //        case 2://电量
            //            strFault += HttpContext.InnerLanguage("Electricity") + ":" + Convert.ToString(((object[])(abnormity))[2]) + "%";
            //            break;
            //    }
            //    abnormities.Add(strFault + ")");
            //}
            //ViewData["Abnormities"] = abnormities;

            //获取客房信息
            var roomInfoModel = new RoomInfoModel();
            roomInfoModel.HostID = host.ID;
            roomInfoModel.RoomNumber = host.RoomNumber;
            roomInfoModel.RoomStatus = ReturnNameByLanguage(host.RoomStatus.Name, host.RoomStatus.EName, host.RoomStatus.TWName);
            roomInfoModel.IP = CSRedisCacheHelper.Get<string>(host.HostNumber, host.MAC);

            string k2 = CacheKey.PowerSupply + "_" + host.HostNumber;
            bool b = CSRedisCacheHelper.ForeverGet<bool>(k2);

            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + host.HostNumber;
            Host HHH = null;
            object obj = MemoryCacheHelper.Get(Key);
            if (obj != null)
            {
                HHH = obj as Host;
                roomInfoModel.Identity = (HHH.RoomCard != null && HHH.RoomCard.RoomCardType != null) ? (Language == Language.CN ? HHH.RoomCard.RoomCardType.Name : HHH.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");
                roomInfoModel.HostStatus = HHH.Status ? HttpContext.InnerLanguage("Online") : HttpContext.InnerLanguage("Offline");
                roomInfoModel.PowerSupply = HHH.PowerSupply;

                roomInfoModel.PowerSupply = b;
            }
            else
            {
                roomInfoModel.Identity = (host.RoomCard != null && host.RoomCard.RoomCardType != null) ? (Language == Language.CN ? host.RoomCard.RoomCardType.Name : host.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");
                roomInfoModel.HostStatus = host.Status ? HttpContext.InnerLanguage("Online") : HttpContext.InnerLanguage("Offline");
                roomInfoModel.PowerSupply = b;
            }


            return View("CtrlRoomDetail", roomInfoModel);
        }
        /// <summary>
        /// 客房详细中的空调信息
        /// </summary>
        /// <param name="hostID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadHostAirs(int hostID)
        {
            IList<HostModal> hostModals = HostModalManager.Load(hostID, DeviceType.AirConditioner).Where(r => r.Modal.Name != "").ToList();
            var result = hostModals.Select(r => new
            {
                HostID = r.HostID,
                ModalID = r.Modal.ID,
                ModalAddress = r.Modal.ModalAddress,
                Name = ReturnNameByLanguage(r.Modal.Name, r.Modal.EnglishName, r.Modal.TWName),
                Status = r.Status,// (r.Status == 1 ? HttpContext.InnerLanguage("AirOn") : HttpContext.InnerLanguage("AirOff")),
                CurrentTemp = r.CurrentTemp,
                SettingTemp = r.SettingTemp,
                Mode = r.Mode,
                FanSpeed = r.FanSpeed,
                ValveName = (r.Valve == 1 ? HttpContext.InnerLanguage("ValveOn") : HttpContext.InnerLanguage("ValveOff"))
            });

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 异常信息
        /// </summary>
        /// <param name="hostID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadCurrentHostFault(int hostID)
        {
            var hostFault = HostFaultsManager.LoadHostFault(hostID);
            var restult = hostFault.Select(r => new
            {
                Name = ReturnNameByLanguage(r[0].ToString(), r[1].ToString(), r[2].ToString()),
                Address = r[7],
                AbnormalStatus = (Convert.ToBoolean(r[3]) == false ? "" : (Convert.ToDateTime(r[9]).Year < 1900 ? "" : r[8])),
                StatusDate = (Convert.ToBoolean(r[3]) == false ? "" : (Convert.ToDateTime(r[9]).Year < 1900 ? "" : Convert.ToDateTime(r[9]).ToString("yyyy-MM-dd HH:mm:ss"))),
                AbnormalElectricQty = (Convert.ToBoolean(r[4]) == false ? "" : (Convert.ToDateTime(r[11]).Year < 1900 ? "" : r[8])),
                ElectricQtyDate = (Convert.ToBoolean(r[4]) == false ? "" : (Convert.ToDateTime(r[11]).Year < 1900 ? "" : Convert.ToDateTime(r[11]).ToString("yyyy-MM-dd HH:mm:ss"))),
                Abnormal3 = Convert.ToDateTime(r[13]).Year < 1900 ? "" : (Convert.ToInt16(r[12]) * 10).ToString(),//数据乘以10，单位mA
                Abnormal3Date = Convert.ToDateTime(r[13]).Year < 1900 ? "" : Convert.ToDateTime(r[13]).ToString("yyyy-MM-dd HH:mm:ss"),
                Abnormal4 = Convert.ToDateTime(r[15]).Year < 1900 ? "" : r[14],
                Abnormal4Date = Convert.ToDateTime(r[15]).Year < 1900 ? "" : Convert.ToDateTime(r[15]).ToString("yyyy-MM-dd HH:mm:ss"),
                Abnormal5 = Convert.ToDateTime(r[17]).Year < 1900 ? "" : r[16],
                Abnormal5Date = Convert.ToDateTime(r[17]).Year < 1900 ? "" : Convert.ToDateTime(r[17]).ToString("yyyy-MM-dd HH:mm:ss")
            }).Where(A => !string.IsNullOrEmpty(A.Name));
            return Json(restult, JsonRequestBehavior.AllowGet);
        }


        public ActionResult AirCondition(int hostID)
        {
            Host host = HostManager.Get(hostID);
            if (host == null)
            {
                ViewData["ErrorMsg"] = HttpContext.InnerLanguage("InvalidRoom");
                return View("Error");
            }

            ViewData["EnableAirSetting"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_AIRSETTING);

            var roomInfoModel = new RoomInfoModel();
            roomInfoModel.HostID = host.ID;
            roomInfoModel.RoomNumber = host.RoomNumber;
            roomInfoModel.RoomStatus = ReturnNameByLanguage(host.RoomStatus.Name, host.RoomStatus.EName, host.RoomStatus.TWName);
            roomInfoModel.Identity = (host.RoomCard != null && host.RoomCard.RoomCardType != null) ? (Language == Language.CN ? host.RoomCard.RoomCardType.Name : host.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");
            roomInfoModel.HostStatus = host.Status ? HttpContext.InnerLanguage("Online") : HttpContext.InnerLanguage("Offline");
            roomInfoModel.IP = host.IP;

            return View("CtrlAirCondition", roomInfoModel);
        }
        /// <summary>
        /// 房态设置
        /// </summary>
        /// <param name="hostID"></param>
        /// <returns></returns>
        public ActionResult RoomStatus(int hostID)
        {
            Host host = HostManager.Get(hostID);
            if (host == null)
            {
                ViewData["ErrorMsg"] = HttpContext.InnerLanguage("InvalidRoom");
                return View("Error");
            }
            var list = RoomStatusManager.LoadAll().OrderBy(r => r.Sort).ToList();
            IList<RoomStatus> result = new List<RoomStatus>();
            foreach (var roomstatus in list)
            {
                result.Add(new RoomStatus
                {
                    ID = roomstatus.ID,
                    Name = ReturnNameByLanguage(roomstatus.Name, roomstatus.EName, roomstatus.TWName), //((Boolean)Session["isCN"]) ? roomstatus.Name : roomstatus.EName,
                    Sort = roomstatus.Sort
                });
            }
            ViewData["RoomStatus"] = result;
            var roomInfoModel = new RoomInfoModel();
            roomInfoModel.HostID = host.ID;
            roomInfoModel.RoomNumber = host.RoomNumber;
            roomInfoModel.RoomStatus = ReturnNameByLanguage(host.RoomStatus.Name, host.RoomStatus.EName, host.RoomStatus.TWName);
            roomInfoModel.Identity = (host.RoomCard != null && host.RoomCard.RoomCardType != null) ? (Language == Language.CN ? host.RoomCard.RoomCardType.Name : host.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");
            roomInfoModel.HostStatus = host.Status ? HttpContext.InnerLanguage("Online") : HttpContext.InnerLanguage("Offline");
            roomInfoModel.IP = CSRedisCacheHelper.Get<string>(host.HostNumber, host.MAC);
            roomInfoModel.PowerSupply = host.PowerSupply;
            return View("CtrlRoomStatus", roomInfoModel);
        }
        /// <summary>
        /// 客房详细房间信息
        /// </summary>
        /// <param name="hostID"></param>
        /// <returns></returns>
        public ActionResult DeviceStatus(int hostID)
        {
            Host host = HostManager.Get(hostID);
            if (host == null)
            {
                ViewData["ErrorMsg"] = HttpContext.InnerLanguage("InvalidRoom");
                return View("Error");
            }
            var roomInfoModel = new RoomInfoModel();
            roomInfoModel.HostID = host.ID;
            roomInfoModel.RoomNumber = host.RoomNumber;
            roomInfoModel.RoomStatus = ReturnNameByLanguage(host.RoomStatus.Name, host.RoomStatus.EName, host.RoomStatus.TWName);//(host.RoomStatus != null) ? (Language == Language.CN ? host.RoomStatus.Name : host.RoomStatus.EName) : "";
            roomInfoModel.Identity = (host.RoomCard != null && host.RoomCard.RoomCardType != null) ? (Language == Language.CN ? host.RoomCard.RoomCardType.Name : host.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");
            roomInfoModel.HostStatus = host.Status ? HttpContext.InnerLanguage("Online") : HttpContext.InnerLanguage("Offline");
            roomInfoModel.IP = CSRedisCacheHelper.Get<string>(host.HostNumber, host.MAC);

            return PartialView("CtrlLightStatus", roomInfoModel);
        }
        /// <summary>
        /// 楼层加载信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <param name="groupId"></param>
        /// <param name="status"></param>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
        //public ActionResult LoadRoomStatus(int page, int rows, string order, string sort, int? groupId, int? status, string roomNumber)
        //{
        //    Group group = groupId.HasValue ? GroupManager.Get(groupId) : SysUserManager.Get(User.Identity.Name).Group;
        //    if (group == null)
        //    {
        //        return Json(new { IsSuccess = false, Message = "您没有分配楼层，不能查看客房状态。" });
        //    }
        //    var list = HostManager.LoadAll(order, sort, group, roomNumber);
        //    if (status.HasValue)
        //    {
        //        list = list.Where(r => r.Status == (status == 1 ? true : false)).ToList();
        //    }
        //    long total = list.LongCount();
        //    list = list.Skip((page - 1) * rows).Take(rows).ToList();
        //    var result = list.Select(r => CreateHost(r));
        //    return Json(new { IsSuccess = true, Data = new { total = total, rows = result } });
        //}        
        /// <summary>
        /// 首页房间加载信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRooms(int page, int rows, int? groupId, bool isAirDetect = false)
        {

            //这里需要
            try
            {
                Group group = null;
                if (groupId.HasValue)
                {
                    string likeKey = "LoadGroupPrefix_" + groupId.Value;
                    object odata = MemoryCacheHelper.Get(likeKey);
                    if (odata != null)
                    {
                        group = odata as Group;
                    }
                    else
                    {
                        group = GroupManager.Get(groupId.Value);
                        MemoryCacheHelper.Set(likeKey, group);
                    }
                }
                else
                {
                    var sysUser = SysUserManager.Get(User.Identity.Name);
                    if (sysUser != null)
                    {
                        group = sysUser.Group;
                    }
                }
                int groupID = group != null ? group.ID : 0;
                int lang = Session["isCN"] != null ? (int)Session["isCN"] : 0;
                long total = 0;

                string LLL = "LoadRoomsPrefix_" + "_" + CurrentHotelID + "_" + groupID;
                object oook = MemoryCacheHelper.Get(LLL);
                IList<Room> roomList = null;
                if (oook == null)
                {
                    roomList = HostManager.LoadRooms(out total, page, rows, groupID, lang, CurrentHotelID);
                    MemoryCacheHelper.Set(LLL, roomList);
                }
                else
                {
                    roomList = (IList<Room>)oook;
                }
                IList<IGrouping<int, Room>> groupRooms = roomList.GroupBy(g => g.GroupSort).ToList();
                ConcurrentBag<FloorModel> floors = new ConcurrentBag<FloorModel>();

                Parallel.ForEach(groupRooms, (groupRoom) =>
                {
                    var floor = new FloorModel();
                    ConcurrentBag<RoomModel> rooms = new ConcurrentBag<RoomModel>();
                    Parallel.ForEach(groupRoom, (room) =>
                    {
                        var hostID = room.HostID;
                        var roomnum = room.RoomNumber;
                        var roomModel = new RoomModel();

                        #region 碳达人
                        StringBuilder sb = new StringBuilder();
                        sb.Append(CacheKey.CarbonVIP_Prefix);
                        sb.Append("_");
                        sb.Append(hostID.ToString());
                        string Key = sb.ToString();
                        roomModel.ID = room.HostID;
                        string current_status = CSRedisCacheHelper.Get<string>(Key);
                        if (string.IsNullOrEmpty(current_status))
                        {
                            string DKey = string.Format("DKey_{0}_{1}_{2}_{3}", CurrentHotelID, roomnum, "054000001", "054000100");
                            var ddd = HttpContext.Cache.Get(DKey);
                            List<SomeDeviceExistsData> takeOutdata = new List<SomeDeviceExistsData>();
                            if (ddd != null)
                            {
                                takeOutdata = ddd as List<SomeDeviceExistsData>;
                            }
                            else
                            {
                                var lll = SysHotelManager.IsExistsSomeDeviceRoomModal(CurrentHotelID, roomnum, "054000001", "054000100");
                                takeOutdata = lll;
                                HttpContext.Cache.Insert(DKey, lll, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                            }
                            if (takeOutdata.Count > 0)
                            {
                                current_status = "exists_nostatus";
                            }
                            else
                            {
                                current_status = "";
                            }
                        }
                        roomModel.CarbonVIP = current_status;
                        #endregion

                        string host_number = room.HostNumber;
                        string mac = room.MAC;
                        bool is_online = CSRedisCacheHelper.Contains(host_number, mac);

                        if (!string.IsNullOrEmpty(mac))
                        {

                            ///能耗
                            //string nenghaoKey = CacheKey.NengHao + "_" + mac;
                            string nenghaoKey = CacheKey.NengHao + "_" + host_number;
                            //var NNNHHH = CSRedisCacheHelper.ForeverGet<NengHao>(nenghaoKey);
                            var NNNHHH = CSRedisCacheHelper.Get_Partition<NengHao>(nenghaoKey, 1);
                            if (NNNHHH != null)
                            {
                                roomModel.Power = NNNHHH.P.ToString() + "w";
                            }
                            else
                            {
                                roomModel.Power = "";
                            }
                        }



                        roomModel.HostStatus = is_online;
                        roomModel.RoomNumber = room.RoomNumber;
                        roomModel.LockStatusName = (room.LockStatus == 1 ? HttpContext.InnerLanguage("LockOn") : HttpContext.InnerLanguage("LockOff"));

                        roomModel.RoomStatus = room.RoomStatus;
                        if (room.DoorLock)//房门开还是房门关
                        {
                            roomModel.RoomStatus += "(" + HttpContext.InnerLanguage("DoorOpen") + ")";//"," + roomModel.LockStatusName +
                        }
                        else
                        {
                            roomModel.RoomStatus += "(" + HttpContext.InnerLanguage("DoorClose") + ")";//"," + roomModel.LockStatusName +
                        }
                        roomModel.RoomStatusID = room.RoomStatusID;
                        roomModel.Identity = room.Identity;
                        roomModel.IsConnectingRoom = false;
                        roomModel.PowerSupplyName = room.PowerSupply ? ("<font style='color:green'>" + HttpContext.InnerLanguage("Normal") + "</font>") : ("<font style='color:red'>" + HttpContext.InnerLanguage("Lock") + "</font>");
                        roomModel.LockVoltage = room.LockVoltage;
                        roomModel.Peripheral = HttpContext.InnerLanguage("Peripheral") + "(";
                        if (room.PeripheralOfflineCount > 0)
                        {
                            roomModel.Peripheral += HttpContext.InnerLanguage("Offline") + ":<font style='color:red'>" + room.PeripheralOfflineCount + "</font>,";
                        }
                        if (room.PeripheralLowPowerCount > 0)
                        {
                            roomModel.Peripheral += HttpContext.InnerLanguage("LowPower") + ":<font style='color:red'>" + room.PeripheralLowPowerCount + "</font>";
                        }
                        //如果无离线和低电，则不显示
                        if (room.PeripheralOfflineCount == 0 && room.PeripheralLowPowerCount == 0)
                        {
                            roomModel.Peripheral = "";
                        }
                        else
                        {
                            if (room.PeripheralLowPowerCount == 0)
                            {
                                roomModel.Peripheral = roomModel.Peripheral.Replace(",", "");
                            }
                            roomModel.Peripheral += ")";
                        }


                        //原来使用Redis
                        //var cache_data = CSRedisCacheHelper.Get_Partition<SomeDeviceExistsData>(CKey);
                        string CKey = CacheKey.HostInfo_Key_HostNumber + "_" + host_number;
                        object ooo = MemoryCacheHelper.Get(CKey);


                        if (ooo != null)
                        {

                            Host cache_data = ooo as Host;

                            string k2 = CacheKey.PowerSupply + "_" + cache_data.HostNumber;
                            bool b = CSRedisCacheHelper.ForeverGet<bool>(k2);


                            string k3 = CacheKey.LockVoltage + "_" + cache_data.HostNumber;
                            float b3 = CSRedisCacheHelper.ForeverGet<float>(k3);

                            roomModel.LockVoltage = b3;
                            roomModel.LockStatusName = (cache_data.LockStatus == 1 ? HttpContext.InnerLanguage("LockOn") : HttpContext.InnerLanguage("LockOff"));
                            roomModel.PowerSupplyName = b ? ("<font style='color:green'>" + HttpContext.InnerLanguage("Normal") + "</font>") : ("<font style='color:red'>" + HttpContext.InnerLanguage("Lock") + "</font>");
                            if (cache_data.RoomStatus == null)
                            {
                                roomModel.RoomStatus = "空房";
                            }
                            else
                            {
                                roomModel.RoomStatus = cache_data.RoomStatus.Name;
                            }

                            if (cache_data.DoorLockStatus)//房门开还是房门关
                            {
                                roomModel.RoomStatus += "(" + HttpContext.InnerLanguage("DoorOpen") + ")";//"," + roomModel.LockStatusName +
                            }
                            else
                            {
                                roomModel.RoomStatus += "(" + HttpContext.InnerLanguage("DoorClose") + ")";//"," + roomModel.LockStatusName +
                            }
                        }


                        //Host hh = null;
                        string KongTiaoAddress = "";


                        string CurrentRoomKongTiao = "GetRoomKongTiaoStatus+" + CurrentHotelID.ToString() + "+" + host_number;
                        object oofgs = MemoryCacheHelper.Get(CurrentRoomKongTiao);
                        if (oofgs != null)
                        {
                            KongTiaoAddress = oofgs.ToString();
                        }
                        else
                        {
                            //①获取空调信息
                            HostModal hostModal = HostModalManager.Load(room.HostID, DeviceType.AirConditioner).Where(r => r.Modal.Name != "").FirstOrDefault();
                            if (hostModal != null)
                            {
                                MemoryCacheHelper.SlideSet(CurrentRoomKongTiao, hostModal.Modal.ModalAddress);
                                KongTiaoAddress = hostModal.Modal.ModalAddress;
                            }
                        }

                        //string Key_KKKongTiao = CacheKey.HostInfo_Key_HostNumber + "_" + host_number;
                        //object obj = MemoryCacheHelper.Get(Key_KKKongTiao);
                        //if (obj != null)
                        //{
                        //    hh = obj as Host;
                        //    var QQQ = hh.RoomType.Modals.Where(A => A.RoomType.Equals(DeviceType.AirConditioner) && A.Name != "").FirstOrDefault();
                        //    if (QQQ != null)
                        //    {
                        //        KongTiaoAddress = QQQ.ModalAddress;
                        //    }
                        //}
                        //空调的值
                        string KongTiaoKey = CacheKey.HostModalStatus_Prefix + "_" + hostID + "_" + "007001000";
                        if (!string.IsNullOrEmpty(KongTiaoAddress))
                        {
                            KongTiaoKey = CacheKey.HostModalStatus_Prefix + "_" + hostID + "_" + KongTiaoAddress;
                        }
                        var kongtiao_cache_data = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KongTiaoKey);
                        if (kongtiao_cache_data != null)
                        {
                            var nnn = kongtiao_cache_data.AirConditionData;
                            roomModel.AirStatusName = (nnn.AirStatus == 1 ? HttpContext.InnerLanguage("AirOn") : HttpContext.InnerLanguage("AirOff"));
                            roomModel.RoomTemp = nnn.CurrentTemp;
                            roomModel.SettingTemp = nnn.SettingTemp;
                            roomModel.Mode = nnn.AirStatus == 1 ? nnn.Mode : 0;//如果空调关，则不显示模式
                            roomModel.FanSpeed = nnn.AirStatus == 1 ? nnn.FanSpeed : 0;//如果空调关，则不显示风速
                            roomModel.ValveName = (nnn.Valve == 1 ? HttpContext.InnerLanguage("ValveOn") : HttpContext.InnerLanguage("ValveOff"));//阀门
                        }
                        else
                        {
                            roomModel.AirStatusName = HttpContext.InnerLanguage("AirOff");
                            roomModel.RoomTemp = 0;
                            roomModel.SettingTemp = 0;
                            roomModel.Mode = 0;
                            roomModel.FanSpeed = 0;
                            roomModel.ValveName = HttpContext.InnerLanguage("ValveOff");//阀门
                        }
                        //if (hostModal != null)
                        //{
                        //    roomModel.AirStatusName = (hostModal.Status == 1 ? HttpContext.InnerLanguage("AirOn") : HttpContext.InnerLanguage("AirOff"));
                        //    roomModel.RoomTemp = hostModal.CurrentTemp;
                        //    roomModel.SettingTemp = hostModal.SettingTemp;
                        //    roomModel.Mode = hostModal.Status == 1 ? hostModal.Mode : 0;//如果空调关，则不显示模式
                        //    roomModel.FanSpeed = hostModal.Status == 1 ? hostModal.FanSpeed : 0;//如果空调关，则不显示风速
                        //    roomModel.ValveName = (hostModal.Valve == 1 ? HttpContext.InnerLanguage("ValveOn") : HttpContext.InnerLanguage("ValveOff"));//阀门
                        //}
                        //else
                        //{
                        //    roomModel.AirStatusName = HttpContext.InnerLanguage("AirOff");
                        //    roomModel.RoomTemp = 0;
                        //    roomModel.SettingTemp = 0;
                        //    roomModel.Mode = 0;
                        //    roomModel.FanSpeed = 0;
                        //    roomModel.ValveName = HttpContext.InnerLanguage("ValveOff");//阀门
                        //}
                        //②获取服务信息
                        //var services = HostModalManager.Load(room.HostID, DeviceType.ServiceInfo).Where(r => r.Modal.ActiveIndicator && r.Status == 1);
                        string KKServiceInfo = "ServiceInfo_" + room.HostID;
                        var oobsc = HttpContext.Cache.Get(KKServiceInfo);
                        IList<HostModal> services = null;
                        if (oobsc != null)
                        {
                            services = oobsc as IList<HostModal>;
                        }
                        else
                        {
                            services = HostModalManager.Load(room.HostID, DeviceType.ServiceInfo).Where(r => r.Modal.ActiveIndicator).ToList();
                            HttpContext.Cache.Insert(KKServiceInfo, services, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
                        }
                        roomModel.Services = new List<ServiceModel>();
                        foreach (var service in services)
                        {
                            string ServiceKey = CacheKey.HostModalStatus_Prefix + "_" + hostID + "_" + service.Modal.ModalAddress;
                            var service_cache_data = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(ServiceKey);
                            if (service_cache_data != null)
                            {
                                //之前的门磁服务有的时候会错误判断，使用这个，会准确很高
                                if (service.Modal.ModalAddress.Equals("004000013"))
                                {
                                    roomModel.RoomStatus = room.RoomStatus;
                                    if (service_cache_data.Status == 1)//房门开还是房门关
                                    {
                                        roomModel.RoomStatus += "(" + HttpContext.InnerLanguage("DoorOpen") + ")";//"," + roomModel.LockStatusName +
                                    }
                                    else
                                    {
                                        roomModel.RoomStatus += "(" + HttpContext.InnerLanguage("DoorClose") + ")";//"," + roomModel.LockStatusName +
                                    }
                                }
                            }
                            if (service_cache_data != null && service_cache_data.Status == 1)
                            {
                                roomModel.Services.Add(new ServiceModel
                                {
                                    Status = 1,
                                    Code = service.Modal.ModalAddress,
                                    Name = ReturnNameByLanguage(service.Modal.Name, service.Modal.EnglishName, service.Modal.TWName),
                                    Color = string.IsNullOrEmpty(service.Modal.Color) ? "#080808" : service.Modal.Color
                                });
                            }
                        }
                        //③获取空气质量检测数据
                        if (isAirDetect)
                        {
                            //var airDetects = HostModalManager.Load(room.HostID, DeviceType.AirDetect).Where(r => r.Modal.ActiveIndicator && r.Status == 1);
                            var airDetects = HostModalManager.Load(room.HostID, DeviceType.AirDetect).Where(r => r.Modal.ActiveIndicator && r.Status == 1);
                            roomModel.AirDetects = new List<AirDetectModel>();
                            foreach (var airDetect in airDetects)
                            {
                                string DiZhi = airDetect.Modal.ModalAddress;
                                string ModalKey = CacheKey.HostModalStatus_Prefix + "_" + hostID + "_" + DiZhi;
                                var kongqi_data = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(ModalKey);
                                if (kongqi_data == null || kongqi_data.Status != 1)
                                {
                                    continue;
                                }
                                var airModel = new AirDetectModel();
                                airModel.Name = ReturnNameByLanguage(airDetect.Modal.Name, airDetect.Modal.EnglishName, airDetect.Modal.TWName);
                                string color = "red";
                                switch (airDetect.Modal.ModalAddress)
                                {
                                    case "009000001"://CO2浓度        ppm
                                    case "009001001":
                                        if (kongqi_data.Brightness <= 1000)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness <= 2000)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness <= 5000)
                                        {
                                            color = "yellow";
                                        }
                                        break;
                                    case "009000002"://甲醛浓度        ug/m3     实际显示单位为mg/M3
                                    case "009001002":
                                        if (kongqi_data.Brightness <= 80)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness <= 100)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness <= 500)
                                        {
                                            color = "yellow";
                                        }
                                        break;
                                    case "009000003"://TVOC浓度       ug/m3     实际显示单位为mg/M3
                                    case "009001003":
                                        if (kongqi_data.Brightness <= 160)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness <= 500)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness <= 3000)
                                        {
                                            color = "yellow";
                                        }
                                        break;
                                    case "009000004"://PM2.5浓度      ug/m3
                                    case "009001004":
                                        if (kongqi_data.Brightness <= 35)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness <= 75)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness <= 150)
                                        {
                                            color = "yellow";
                                        }
                                        break;
                                    case "009000005"://PM10浓度      ug/m3
                                    case "009001005":
                                        if (kongqi_data.Brightness <= 50)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness <= 100)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness <= 150)
                                        {
                                            color = "yellow";
                                        }
                                        break;
                                    case "009000006"://温度           度
                                    case "009001006":
                                        if (kongqi_data.Brightness >= 18 && kongqi_data.Brightness <= 28)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness >= 16 && kongqi_data.Brightness < 18 || kongqi_data.Brightness > 28 && kongqi_data.Brightness <= 32)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness >= 12 && kongqi_data.Brightness < 16 || kongqi_data.Brightness > 32 && kongqi_data.Brightness <= 36)
                                        {
                                            color = "yellow";
                                        }
                                        else if (kongqi_data.Brightness < 12 || kongqi_data.Brightness > 36)
                                        {
                                            color = "red";
                                        }
                                        break;
                                    case "009000007"://湿度           %RH
                                    case "009001007":
                                        if (kongqi_data.Brightness >= 40 && kongqi_data.Brightness <= 60)
                                        {
                                            color = "green";
                                        }
                                        else if (kongqi_data.Brightness >= 30 && kongqi_data.Brightness < 40 || kongqi_data.Brightness > 60 && kongqi_data.Brightness <= 80)
                                        {
                                            color = "orange";
                                        }
                                        else if (kongqi_data.Brightness >= 15 && kongqi_data.Brightness < 30 || kongqi_data.Brightness > 80 && kongqi_data.Brightness <= 90)
                                        {
                                            color = "yellow";
                                        }
                                        else if (kongqi_data.Brightness < 15 || kongqi_data.Brightness > 90)
                                        {
                                            color = "red";
                                        }
                                        break;
                                }
                                airModel.Value = string.Format("<font style='color:{0}'>{1}</font>", color, airDetect.Brightness);
                                roomModel.AirDetects.Add(airModel);
                            }
                        }

                        if (string.IsNullOrEmpty(roomModel.Power))
                        {
                            roomModel.Power = "";
                        }
                        floor.Sort = room.GroupSort;
                        rooms.Add(roomModel);
                    });
                    floor.FloorRooms = rooms.OrderBy(r => r.RoomNumber).ThenBy(r => r.ID).ToList();
                    floors.Add(floor);
                });
                return Json(new { IsSuccess = true, Total = total, Data = floors.OrderBy(r => r.Sort) }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 加载客房统计数据
        /// </summary>
        /// 临时 注释 ，返回空值
        /// 2025-07-11
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomStatistics()
        {

            string IP = "";
            string PPP = Request.UserHostAddress;
            string III = Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(III))
            {
                IP = PPP;
            }
            else
            {
                IP = III;
            }
            string[] codename = CurrentHotelName.Split('_');
            string code = codename[0];

            string Account = "";
            object ooo = Session["Account"];
            if (ooo != null)
            {
                Account = ooo.ToString();
            }

            if (!string.IsNullOrEmpty(Account))
            {

                string Key = IP + "@" + Account + "@" + code;
                OnLineUser U = null;
                bool bf = DataTongJi.OnLineUserList_IP.TryGetValue(Key, out U);
                if (bf)
                {
                    U.LastUpdateTime = DateTime.Now;
                }
                else
                {
                    OnLineUser u = new OnLineUser();
                    u.Account = Account;
                    u.IP = IP;
                    u.LastUpdateTime = DateTime.Now;
                    u.HotelCode = code;
                    u.HotelId = CurrentHotelID;
                    DataTongJi.OnLineUserList_IP.TryAdd(Key, u);
                }

                //OnLineUser V = null;
                //bool uv = DataTongJi.OnLineUserList_IP.TryGetValue(Account, out V);
                //if (uv)
                //{
                //    V.LastUpdateTime = DateTime.Now;
                //}
                //else
                //{
                //    OnLineUser u = new OnLineUser();
                //    u.Account = Account;
                //    u.IP = IP;
                //    u.LastUpdateTime = DateTime.Now;
                //    u.HotelCode = code;
                //    u.HotelId = CurrentHotelID;
                //    DataTongJi.OnLineUserList_Account.TryAdd(Account, u);
                //}
            }

            //string KeyFilter1 = "在线Account";
            //RCUHost.RCUHostCommon.tools.LanJieData(KeyFilter1, Q.Value);

            //string KeyFilter2 = "在线IP";
            //RCUHost.RCUHostCommon.tools.LanJieData(KeyFilter2, IP);

            string LieKey = CacheKey.LieECOKey + "_" + CurrentHotelID;
            var LLLData = LieECOManager.LoadAll().Where(A => A.HotelID == CurrentHotelID && A.IsEnable).ToList();
            if (LLLData != null && LLLData.Count > 0)
            {
                CSRedisCacheHelper.Set_Partition<List<LieECO>>(LieKey, LLLData, 1);
            }

            DataTongJi.InvokeCount("LoadRoomStatistics_");
            //string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //if (string.IsNullOrEmpty(ipAddress)) // 如果没有代理，直接获取REMOTE_ADDR
            //{
            //    ipAddress = Request.ServerVariables["REMOTE_ADDR"];
            //}
            //// 如果有代理，取第一个IP（可能是客户端的真实IP）
            //else 
            //{
            //    string[] addresses = ipAddress.Split(',');
            //    if (addresses.Length > 0)
            //    {
            //        ipAddress = addresses[0].Trim();
            //    }
            //}
            //return Json(new { IsSuccess = true, Data = new {} }, JsonRequestBehavior.AllowGet);
            if (Session["CurrentHotelID"] == null)
            {
                return Json(new { IsSuccess = false, Message = "重新登录" });
            }
            try
            {
                IList<object> room = GetRoomStatistics();
                IList<object> services = GetServiceStatistics();//Abnormities = GetServiceAbnormities(),                
                IList<object> peripheral = GetHostFaultStatistics();
                return Json(new { IsSuccess = true, Data = new { Room = room, Services = services, Peripheral = peripheral } }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [Authorize()]
        public ActionResult HeartBeat()
        {

            string IP = "";
            string PPP = Request.UserHostAddress;
            string III = Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(III))
            {
                IP = PPP;
            }
            else
            {
                IP = III;
            }
            if (Session["CurrentHotelID"] == null)
            {
                return Json(new { IsSuccess = false, Message = "重新登录" });
            }
            try
            {
                return Json(new { IsSuccess = true, Data = new { } }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        #region 加载控件数据

        [Authorize]
        public ActionResult LoadDataForRoomStatusCombobox()
        {
            var list = RoomStatusManager.LoadAll();
            var result = list.Select(r => new { r.ID, Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName) }).ToList<object>();
            result.Insert(0, new { ID = 0, Name = HttpContext.InnerLanguage("CheckAll") });
            return Json(result);
        }

        [Authorize]
        public ActionResult LoadRoomStatusForCombobox()
        {
            var result = new List<object>();
            var list = RoomStatusManager.LoadAll().OrderBy(r => r.Sort);
            result.Add(new { ID = 0, Name = HttpContext.InnerLanguage("RoomStatus"), Color = "#FFFFFF" });
            result.AddRange(list.Select(r => new { r.ID, Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName), r.Color }).ToList<object>());
            result.Add(new { ID = 32, Name = HttpContext.InnerLanguage("ConnectedRoom"), Color = "#DDA0DD" });

            return Json(result);
        }

        #endregion

        #endregion

        #region Private Methods

        private object CreateHost(Host r)
        {
            return new
            {
                r.ID,
                r.RoomNumber,
                r.IP,
                r.Status,
                RoomStatusID = r.RoomStatus != null ? r.RoomStatus.ID : 0,
                RoomStatus = r.RoomStatus != null ? r.RoomStatus.Name : "",
                RoomCard = (r.RoomCard != null && r.RoomCard.RoomCardType != null) ? r.RoomCard.RoomCardType.Name : "无人",
                CardUserName = r.RoomCard != null ? r.RoomCard.UserName : "",
                //r.RequestService,
                //r.RequestClear,
                //r.RequestDNDST,
                //r.RequestCheckOut,
                //r.SOS,
                r.DoorLockStatus,
                r.SafeStatus
                //r.CurrentTemp,
                //r.SettingTemp,
                //r.Speed
            };
        }
        /// <summary>
        /// 获取客房统计信息
        /// </summary>
        /// <returns></returns>
        private IList<object> GetRoomStatistics()
        {
            var hosts = HostManager.LoadAll(CurrentHotelID).ToList();
            var roomStatus = RoomStatusManager.LoadAll();

            var query = from host in hosts
                        where host.RoomStatus != null
                        group host by host.RoomStatus into g
                        select new { g.Key.Name, g.Key.EName, g.Key.TWName, Value = g.Count() };

            IList<object> rooms = new List<object>();
            rooms.Add(new { Name = HttpContext.InnerLanguage("All"), Value = hosts.Count });
            foreach (var status in roomStatus)
            {
                var item = query.FirstOrDefault(o => o.Name == status.Name);
                if (item != null)
                {
                    rooms.Add(new
                    {
                        Name = ReturnNameByLanguage(item.Name, item.EName, item.TWName), //(bool)HttpContext.Session["isCN"] ? item.Name : item.EName, 
                        Value = item.Value
                    });
                }
                else
                {
                    rooms.Add(new
                    {
                        Name = ReturnNameByLanguage(status.Name, status.EName, status.TWName), //(bool)HttpContext.Session["isCN"] ? status.Name : status.EName,
                        Value = 0
                    });
                }
            }
            rooms.Add(new { Name = HttpContext.InnerLanguage("Online"), Value = hosts.Where(r => r.Status == true).ToList().Count });//统计在线主机

            return rooms;
        }

        private IList<object> GetHostFaultStatistics()
        {
            IList<object> faults = new List<object>();
            //外设离线
            IList<object[]> lists = RoomServiceManager.LoadCurrentHostFaultStatistics(CurrentHotelID, this.User.Identity.Name, 1);
            string name = HttpContext.InnerLanguage("PeripheralOffline");
            if (lists != null)
            {
                faults.Add(new { Name = name, Value = lists.Count, Color = "#E9967A" });
            }
            else
            {
                faults.Add(new { Name = name, Value = 0, Color = "#E9967A" });
            }
            //外设低电
            lists = RoomServiceManager.LoadCurrentHostFaultStatistics(CurrentHotelID, this.User.Identity.Name, 2);
            name = HttpContext.InnerLanguage("PeripheralLowPower");
            if (lists != null)
            {
                faults.Add(new { Name = name, Value = lists.Count, Color = "#FFE4C4" });
            }
            else
            {
                faults.Add(new { Name = name, Value = 0, Color = "#FFE4C4" });
            }
            return faults;
        }

        private IList<object> GetServiceStatistics()
        {
            IList<object> services = new List<object>();
            DataTable table = RoomServiceManager.LoadCurrentRoomServicesCount(CurrentHotelID, this.User.Identity.Name);
            if (table != null)
            {
                foreach (System.Data.DataRow row in table.Rows)
                {
                    //"Code": "004000001",
                    //"Name": "取电",
                    //"Value": 17,
                    //"Color": "#FF8C69",
                    //"Beep": false
                    string Address = row["Code"].ToString();
                    services.Add(new
                    {
                        Code = row["Code"],
                        Name = ReturnNameByLanguage(row["Name"].ToString(), row["EName"].ToString(), row["TWName"].ToString()),// (bool)Session["isCN"] ? row["Name"] : row["EName"],
                        Value = row["Number"],
                        Color = row["Color"],
                        Beep = row["Beep"]
                    });
                }
            }
            return services;
        }

        //private IList<object> GetServiceAbnormities()
        //{
        //    IList<object> abnormities = new List<object>();
        //    var table = RoomServiceManager.LoadCurrentRoomAbnormitiesCount(CurrentHotelID, User.Identity.Name);
        //    if (table != null)
        //    {
        //        foreach (System.Data.DataRow row in table.Rows)
        //        {
        //            abnormities.Add(new
        //            {
        //                Code = row["Code"],
        //                Name = ReturnNameByLanguage(row["Name"].ToString(), row["EName"].ToString(), row["TWName"].ToString()), //(bool)Session["isCN"] ? row["Name"] : row["EName"],
        //                Value = row["Number"],
        //                Color = row["Color"],
        //                Beep = row["Beep"]
        //            });
        //        }
        //    }
        //    return abnormities;
        //}

        //private ServiceModel GetService(IList<HostModal> services, string modalAddress)
        //{
        //    var serviceModel = new ServiceModel { Status = 2, Code = "", Name = "", Color = "" };
        //    var service = services.FirstOrDefault(r => r.Modal.ModalAddress == modalAddress);
        //    if (service != null)
        //    {
        //        serviceModel = new ServiceModel
        //        {
        //            Status = 1,
        //            Code = service.Modal.ModalAddress,
        //            Name = ReturnNameByLanguage(service.Modal.Name,service.Modal.EnglishName,service.Modal.TWName),
        //            Color = service.Modal.Color != "" ? service.Modal.Color : "#080808"
        //        };
        //        services.Remove(service);
        //    }
        //    return serviceModel;
        //}

        #endregion
    }
}
