using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Service;
using Domain;
using WebSite.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Diagnostics;
using System.Text;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using CommonEntity;
using Common;
using RestSharp;
using System.Configuration;
using RCUHost.Implement;
using Jose;
using System.Web.Caching;
using System.Collections.Concurrent;
using System.Threading;
using RCUHost;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace WebSite.Controllers
{
    public class ApiController : BaseController
    {
        private static long hostBaseCount = Convert.ToInt64(System.Configuration.ConfigurationManager.AppSettings["host_base_count"]);
        private const int AuthorityID = 13;
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ApiController));
        public IHostManager HostManager { get; set; }
        //阿宝添加的
        public IHostUpdateStatusManager HostUpdateStatusManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }
        public ISysHotelGroupManager SysHotelGroupManager { get; set; }
        public IPowerSupplyControlManager PowerSupplyControlManager { get; set; }
        public IHostAirManager HostAirManager { get; set; }
        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }
        public ILightControlManager LightControlManager { get; set; }
        public IHostModalManager HostModalManager { get; set; }
        public IRoomServiceManager RoomServiceManager { get; set; }
        public IAlarmSettingManager AlarmSettingManager { get; set; }
        public IHostModalRecordManager HostModalRecordManager { get; set; }
        public IRoomTypeWXMenusManager RoomTypeWXMenusManager { get; set; }
        public ISysOauth2Manager SysOauth2Manager { get; set; }
        public IRoomTypeManager RoomTypeManager { get; set; }
        public ISysProvinceManager SysProvinceManager { get; set; }
        public IOverviewManager OverviewManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public IHostFaultsManager HostFaultsManager { get; set; }
        public IRoomTypeModalManager RoomTypeModalManager { get; set; }

        public IRoomCardManager RoomCardManagerTest { get; set; }
        public IGroupManager GroupManager { get; set; }
        public IRoomModalManager RoomModalManager { get; set; }

        //新添加的
        public IRoomStatusManager RoomStatusManager { get; set; }
        public IDeviceControlReceiver DeviceControlReceiver { get; set; }

        private string msg = "";
        private int hotelID = 0;

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 验证酒店ID和房号
        /// </summary>
        /// <param name="code"></param>
        /// <param name="creatDate"></param>
        /// <param name="roomNumber"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private Host CheckRoomNumber(string code, string creatDate, ref string msg, ref int hotelID, string roomNumber = "")
        {
            string Key = "GetHotelInfo_" + code + "_" + creatDate;
            var Obj = MemoryCacheHelper.Get(Key);
            SysHotel sysHotel = null;
            if (Obj == null)
            {
                sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
                MemoryCacheHelper.SlideSet(Key, sysHotel, new TimeSpan(0, 5, 0));
            }
            else
            {
                sysHotel = Obj as SysHotel;
            }
            if (sysHotel == null)
            {
                msg = "酒店未知";
                hotelID = 0;
                return null;
            }
            hotelID = sysHotel.ID;
            if (!string.IsNullOrEmpty(roomNumber))
            {
                Host host = null;
                string Key1 = "QueryHostInfo_" + roomNumber + "_" + sysHotel.ID;
                var ooo = MemoryCacheHelper.Get(Key1);
                if (ooo != null)
                {
                    host = ooo as Host;
                }
                else
                {
                    host = HostManager.GetByRoomNumber(roomNumber, sysHotel.ID);
                    MemoryCacheHelper.SlideSet(Key1, host, new TimeSpan(0, 5, 0));
                }

                if (host == null)
                {
                    msg = "房号[" + roomNumber + "]不存在";
                    return null;
                }
                if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                {
                    msg = "房号[" + roomNumber + "]网络异常";
                    return null;
                }
                return host;
            }
            return null;
        }
        /// <summary>
        /// 如果存在取电服务记录，且不是打开状态，则返回false，不可控制设备（除了空调）,不存在取电服务，可以控制
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        private bool CheckGetPower(Host host)
        {
            if (!host.SysHotel.IsVoincePowerOn)
            {
                return true;//不需要取电服务打开即可控制
            }
            string HostNumberOnly = host.HostNumber;
            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + HostNumberOnly;
            object FFK = MemoryCacheHelper.Get(Key);
            if (FFK != null)
            {
                Host NNN = FFK as Host;
                if (NNN.RoomCard != null)
                {
                    return true;//已插卡即可控制
                }
            }
            else
            {
                if (host.RoomCard != null)
                {
                    return true;//已插卡即可控制
                }
            }

            string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000001";
            var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
            if (obj != null)
            {
                HostModal_Cache hhh = obj as HostModal_Cache;
                if (hhh.Status != 1)
                {
                    return false;
                }
            }

            return true;
        }

        public static readonly string mqtt_topic = "blw/webapi/report";
        #region 提供api给第三方平台对接
        /// <summary>
        /// 获取主机状态（如果指定房号roomNumber参数，则提供入住人信息）
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetRCUStatus(string jsonData)
        {
            try
            {
                WebApiInvoke_FenXi("GetRCUStatus");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string code = jData["code"].ToString();
                string room_number = jData["roomNumber"].ToString();
                if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(room_number))
                {
                    return Json(new { IsSuccess = "酒店编码或者房间号不能为空", Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string IP = "";
                string PPP = Request.UserHostAddress;
                string III = Request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrEmpty(III))
                {
                    IP = PPP;
                }
                else
                {
                    IP = III;
                }
                string KKK = "GetRCUStatus_" + IP + "_" + code + "_" + room_number;
                object ooo = MemoryCacheHelper.Get(KKK);
                if (ooo != null)
                {
                    DateTime dt = DateTime.Parse(ooo.ToString());
                    TimeSpan span = DateTime.Now - dt;
                    if (span.TotalSeconds <= 15)
                    {
                        return Json(new { IsSuccess = true, Result = "wait for a moment" }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        string start_timeddd = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        MemoryCacheHelper.Set(KKK, start_timeddd);
                    }
                }
                else
                {
                    string start_timeddd = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    MemoryCacheHelper.Set(KKK, start_timeddd);
                }
            }
            catch (Exception)
            {

            }
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //return Json(new { IsSuccess = false, Result = "接口地址改用(https://boonlive-rcu.com/api/GetRCUStatus)" }, JsonRequestBehavior.AllowGet);
            //System.Threading.Thread.Sleep(100);
            //if (!Common.RateLimiter.TryRequest())
            //{
            //    return Json(new { IsSuccess = false, Result = "Too Many Requests" }, JsonRequestBehavior.AllowGet);
            //}
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                Host host1 = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host1 == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                if (jData["roomNumber"] == null || string.IsNullOrEmpty(jData["roomNumber"].ToString()))
                {
                    return Json(new { IsSuccess = false, Result = "roomNumber房号参数不能为空" }, JsonRequestBehavior.AllowGet);
                }
                string roomNumber = jData["roomNumber"].ToString();
                //logger.Error(string.Format("api获取酒店{0}主机{1}状态列表，来自{2}", jData["code"].ToString(), roomNumber, GetClientIP()));
                List<RoomModel> roomModels = new List<RoomModel>();

                IList<Host> hosts = null;
                string Key = CacheKey.WebAPIGetRCUStatus + "_" + hotelID + "_" + roomNumber;
                object obj = MemoryCacheHelper.Get(Key);
                if (obj != null)
                {
                    hosts = obj as IList<Host>;
                }
                else
                {
                    hosts = HostManager.LoadAll(hotelID, roomNumber).ToList();//OrderBy(r => r.RoomNumber).
                    MemoryCacheHelper.SlideSet(Key, hosts);
                }
                foreach (Host host in hosts)
                {

                    RoomModel roomModel = new RoomModel();
                    roomModel.ID = host.ID;

                    roomModel.HostStatus = host.Status;//主机状态：0离线，1在线
                    roomModel.RoomNumber = host.RoomNumber;//房号
                    if (host.RoomStatus != null)
                    {
                        roomModel.RoomStatus = (Language == Language.CN ? host.RoomStatus.Name : host.RoomStatus.EName);
                    }
                    roomModel.RoomStatus += host.DoorLockStatus ? "(" + HttpContext.InnerLanguage("DoorOpen") + ")" : "(" + HttpContext.InnerLanguage("DoorClose") + ")";//房态和房门状态
                    roomModel.Identity = (host.RoomCard != null && host.RoomCard.RoomCardType != null) ? (Language == Language.CN ? host.RoomCard.RoomCardType.Name : host.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");//身份
                    roomModel.IsConnectingRoom = false;//host.IsConnectingRoom;//是否连通房

                    string k2 = CacheKey.PowerSupply + "_" + host.HostNumber;
                    bool b = CSRedisCacheHelper.ForeverGet<bool>(k2);
                    roomModel.PowerSupply = b;//电源状态


                    string KeyKey = CacheKey.HostInfo_Key_HostNumber + "_" + host.HostNumber;
                    object objobj = MemoryCacheHelper.Get(KeyKey);
                    Host HHH = objobj as Host;
                    if (HHH != null)
                    {
                        string host_number = host.HostNumber;
                        string mac = host.MAC;
                        bool is_online = CSRedisCacheHelper.Contains(host_number, mac);
                        roomModel.HostStatus = is_online;//主机状态：0离线，1在线


                        string kk2 = CacheKey.PowerSupply + "_" + host.HostNumber;
                        bool bb = CSRedisCacheHelper.ForeverGet<bool>(k2);
                        roomModel.PowerSupply = bb;//电源状态
                        #region 暂时丢掉
                        //roomModel.HostStatus = host.Status;//主机状态：0离线，1在线
                        //roomModel.RoomNumber = host.RoomNumber;//房号
                        //if (host.RoomStatus != null)
                        //{
                        //    roomModel.RoomStatus = (Language == Language.CN ? host.RoomStatus.Name : host.RoomStatus.EName);
                        //}
                        //roomModel.RoomStatus += host.DoorLockStatus ? "(" + HttpContext.InnerLanguage("DoorOpen") + ")" : "(" + HttpContext.InnerLanguage("DoorClose") + ")";//房态和房门状态
                        //roomModel.Identity = (host.RoomCard != null && host.RoomCard.RoomCardType != null) ? (Language == Language.CN ? host.RoomCard.RoomCardType.Name : host.RoomCard.RoomCardType.EName) : HttpContext.InnerLanguage("Nobody");//身份
                        //roomModel.IsConnectingRoom = false;//host.IsConnectingRoom;//是否连通房

                        //roomModel.PowerSupply = host.PowerSupply;//电源状态
                        ////空调信息
                        //HostModal hostModal = HostModalManager.Load(host.ID, DeviceType.AirConditioner).Where(r => r.Modal.ActiveIndicator).OrderBy(r => r.Modal.Sort).FirstOrDefault();
                        //if (hostModal != null)
                        //{
                        //    roomModel.AirID = hostModal.Modal.ID;
                        //    roomModel.AirStatus = hostModal.Status;
                        //    roomModel.ModalAddress = hostModal.Modal.ModalAddress;
                        //    roomModel.RoomTemp = hostModal.CurrentTemp;
                        //    roomModel.SettingTemp = hostModal.SettingTemp;
                        //    roomModel.Mode = hostModal.Mode;
                        //    roomModel.FanSpeed = hostModal.FanSpeed;
                        //    roomModel.Valve = (int)hostModal.Valve;
                        //    roomModel.ValveName = hostModal.Valve == 1 ? HttpContext.InnerLanguage("On") : HttpContext.InnerLanguage("Off");//阀门
                        //}
                        //else
                        //{
                        //    roomModel.AirID = 0;
                        //    roomModel.AirStatus = 2;
                        //    roomModel.ModalAddress = "";
                        //    roomModel.RoomTemp = 0;
                        //    roomModel.SettingTemp = 0;
                        //    roomModel.Mode = 0;
                        //    roomModel.FanSpeed = 0;
                        //    roomModel.Valve = 0;
                        //    roomModel.ValveName = HttpContext.InnerLanguage("Off");//阀门
                        //}
                        ////指定服务信息
                        //var services = HostModalManager.Load(host.ID, DeviceType.ServiceInfo).Where(r => r.Modal.ActiveIndicator && r.Status == 1).ToList();//RoomServiceManager.LoadCurrentRoomServices(room.HostID);
                        //roomModel.SOS = GetService(services, "004000008");
                        //roomModel.DND = GetService(services, "004000002");
                        //roomModel.Clean = GetService(services, "004000003");
                        //roomModel.Checkout = GetService(services, "004000006");
                        #endregion
                    }

                    //空调信息
                    HostModal KongTiaoInfoTake = null;
                    string KongInfo = "KongTiaoInfo_" + host.ID;
                    var OOjb = MemoryCacheHelper.Get(KongInfo);
                    if (OOjb != null)
                    {
                        KongTiaoInfoTake = (HostModal)OOjb;
                    }
                    else
                    {
                        KongTiaoInfoTake = HostModalManager.Load(host.ID, DeviceType.AirConditioner).Where(r => r.Modal.ActiveIndicator).OrderBy(r => r.Modal.Sort).FirstOrDefault();
                        MemoryCacheHelper.Set(KongInfo, KongTiaoInfoTake);
                    }

                    string KKey = "";
                    if (KongTiaoInfoTake != null)
                    {
                        KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + KongTiaoInfoTake.Modal.ModalAddress;
                    }
                    else
                    {
                        KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_007001000";
                    }
                    var hostModal = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                    if (hostModal != null)
                    {
                        roomModel.AirID = hostModal.Modal.ID;
                        roomModel.AirStatus = hostModal.Status;
                        roomModel.ModalAddress = hostModal.Modal.ModalAddress;
                        roomModel.RoomTemp = hostModal.AirConditionData.CurrentTemp;
                        roomModel.SettingTemp = hostModal.AirConditionData.SettingTemp;
                        roomModel.Mode = hostModal.AirConditionData.Mode;
                        roomModel.FanSpeed = hostModal.AirConditionData.FanSpeed;
                        roomModel.Valve = (int)hostModal.AirConditionData.Valve;
                        roomModel.ValveName = hostModal.AirConditionData.Valve == 1 ? HttpContext.InnerLanguage("On") : HttpContext.InnerLanguage("Off");//阀门
                    }
                    else
                    {
                        roomModel.AirID = 0;
                        roomModel.AirStatus = 2;
                        roomModel.ModalAddress = "";
                        roomModel.RoomTemp = 0;
                        roomModel.SettingTemp = 0;
                        roomModel.Mode = 0;
                        roomModel.FanSpeed = 0;
                        roomModel.Valve = 0;
                        roomModel.ValveName = HttpContext.InnerLanguage("Off");//阀门
                    }
                    IList<HostModal> services = null;
                    //指定服务信息
                    string ServicesKey = "Services_" + host.ID;
                    object ooo = MemoryCacheHelper.Get(ServicesKey);
                    if (ooo != null)
                    {
                        services = ooo as IList<HostModal>;
                    }
                    else
                    {
                        //services = HostModalManager.Load(host.ID, DeviceType.ServiceInfo).Where(r => r.Modal.ActiveIndicator && r.Status == 1).ToList();//RoomServiceManager.LoadCurrentRoomServices(room.HostID);
                        services = HostModalManager.Load(host.ID, DeviceType.ServiceInfo).Where(r => r.Modal.ActiveIndicator).ToList();//RoomServiceManager.LoadCurrentRoomServices(room.HostID);
                        MemoryCacheHelper.SlideSet(ServicesKey, services);
                    }
                    string SOSKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000008";
                    string DNDKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000002";
                    string CleanKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000003";
                    string CheckOutKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000006";

                    var hostModal1 = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(SOSKey);
                    var hostModal2 = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(DNDKey);
                    var hostModal3 = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(CleanKey);
                    var hostModal4 = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(CheckOutKey);
                    roomModel.SOS = GetService(services, "004000008");
                    roomModel.DND = GetService(services, "004000002");
                    roomModel.Clean = GetService(services, "004000003");
                    roomModel.Checkout = GetService(services, "004000006");
                    if (hostModal1 != null)
                    {
                        roomModel.SOS.Status = hostModal1.Status;
                    }
                    if (hostModal2 != null)
                    {
                        roomModel.DND.Status = hostModal2.Status;
                    }
                    if (hostModal3 != null)
                    {
                        roomModel.Clean.Status = hostModal3.Status;
                    }
                    if (hostModal4 != null)
                    {
                        roomModel.Checkout.Status = hostModal4.Status;
                    }

                    #region 弃用的代码，影响使用
                    //获取当前入住人信息
                    //if (!string.IsNullOrEmpty(roomNumber))
                    //{
                    //    using (syncstatus.syncstatusSoapClient wsClient = new syncstatus.syncstatusSoapClient())
                    //    {
                    //        string phoneNumber = "";
                    //        string xmlString = wsClient.GetRoomCustomerByHotelID(host.SysHotel.ID, roomNumber, ref phoneNumber);
                    //        if (!string.IsNullOrEmpty(xmlString))
                    //        {
                    //            try
                    //            {
                    //                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    //                doc.LoadXml(xmlString);
                    //                foreach (System.Xml.XmlNode node in doc.GetElementsByTagName("interface")[0].ChildNodes)
                    //                {
                    //                    roomModel.Customers.Add(new RoomCustomer()
                    //                    {
                    //                        idtype = node.Attributes["idtype"].Value,
                    //                        idcard = node.Attributes["idcard"].Value,
                    //                        customer = node.Attributes["customer"].Value,
                    //                        sex = node.Attributes["sex"].Value,
                    //                        country = node.Attributes["country"].Value,
                    //                        checkindate = Convert.ToDateTime(node.Attributes["checkindate"].Value),
                    //                        phoneNumber = phoneNumber
                    //                    });
                    //                }
                    //            }
                    //            catch (Exception ex1)
                    //            {
                    //                logger.Error(string.Format("解释酒店({0})客房({1})入住人信息({2})异常)，原因：{3}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, xmlString, ex1.Message));
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion
                    roomModels.Add(roomModel);
                }



                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetRCUStatus");
                return Json(new { IsSuccess = true, Result = roomModels }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取主机状态失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        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 = (Language == Domain.Language.CN) ? service.Modal.Name : service.Modal.EnglishName,
                    Color = service.Modal.Color == "" ? service.Modal.Color : "#080808"
                };
                services.Remove(service);
            }
            return serviceModel;
        }
        /// <summary>
        /// 打开/关闭rcu
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUPower(string jsonData)
        {
            return Json(new { IsSuccess = false, Result = "接口已停用" }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 打开/关闭rcu（授权使用）
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUPowerLicense(string jsonData)
        {

            WebApiInvoke_FenXi("SetRCUPowerLicense");
            //MonitorWebAPI(jsonData, "SetRCUPowerLicense");
            try
            {

                string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                int status = Convert.ToInt16(jData["status"]);//设置状态：1开启，2关闭
                PowerSupplyCtrl power = status == 1 ? PowerSupplyCtrl.Normal : PowerSupplyCtrl.Lock;//实际下位机：0开启，1关闭
                PowerSupplyControlManager.SendCtrl(host, power);
                host.PowerSupply = (power == PowerSupplyCtrl.Normal ? true : false);

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

                HostManager.Update(host);

                string detail = string.Format("{0}客房{1}的主机电源", (status == 1 ? "打开" : "关闭"), roomNumber);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Relay"), detail, true, "api", hotelID);

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "SetRCUPowerLicense");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置电源失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public static string TongJiEnable = ConfigurationManager.AppSettings["tongjiflag"];
        private void TongJi(string jsonData, string start_time, string end_time, JObject jData, string METHOD_Name)
        {
            if (TongJiEnable.Equals("0"))
            {
                return;
            }
            string code = "0000";
            var mmm = jData["code"];
            if (mmm != null)
            {
                code = mmm.ToString();
            }
            string roomnumber = "0000";
            var nnn = jData["roomNumber"];
            if (nnn != null)
            {
                roomnumber = nnn.ToString();
            }
            var t = new Tuple<string, string, string, string, string, string>(jsonData, start_time, end_time, code, roomnumber, METHOD_Name);
            Task.Factory.StartNew((state) =>
            {
                var ttt = state as Tuple<string, string, string, string, string, string>;
                string jt = ttt.Item1;
                string st_t = ttt.Item2;
                string ed_t = ttt.Item3;
                string co = ttt.Item4;
                string rm = ttt.Item5;
                string MN = ttt.Item6;
                MonitorWebAPI(jt, METHOD_Name, st_t, ed_t, co, rm);
            }, t);
        }
        /// <summary>
        /// 获取房间的空调列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>

        //public ActionResult GetRoomAirList_Deprecate(string jsonData)
        public ActionResult GetRoomAirList(string jsonData)
        {
            //return Json(new { IsSuccess = false, Result = "接口修改调整" }, JsonRequestBehavior.AllowGet);
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRoomAirList);
                WebApiInvoke_FenXi("GetRoomAirList");
                string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string code = jData["code"].ToString();
                string cd = jData["creatDate"].ToString();
                string KKK = "GetRoomAirList_" + roomNumber + "_" + code + "_" + cd;
                List<Air> list = new List<Air>();
                var dbdata = HttpContext.Cache.Get(KKK);
                if (dbdata != null)
                {
                    list = dbdata as List<Air>;
                }
                else
                {
                    Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                    if (host == null)
                    {
                        return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                    }
                    IList<HostModal> hostModals = HostModalManager.Load(host.ID, DeviceType.AirConditioner).Where(r => r.Modal.WXActiveIndicator).ToList();
                    if (hostModals == null || hostModals.Count < 1)
                    {
                        return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]未配置空调" }, JsonRequestBehavior.AllowGet);
                    }
                    foreach (HostModal item in hostModals)
                    {
                        Air air = new Air
                        {
                            HostID = item.HostID,
                            ModalAddress = item.Modal.ModalAddress,
                            Name = item.Modal.Name,
                            RoomTypeAirID = item.Modal.ID,
                            Status = item.Status,
                            SettingTemp = item.SettingTemp,
                            CurrentTemp = item.CurrentTemp,
                            Mode = item.Mode,
                            FanSpeed = item.FanSpeed,
                            Valve = item.Valve
                        };
                        list.Add(air);
                    }
                    HttpContext.Cache.Insert(KKK, list, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetRoomAirList");
                //SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("AirConditioningControl"), "获取客房" + roomNumber + "空调信息", true, "api", hotelID);
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取空调失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        private void MonitorWebAPI(string jsonData, string MethodName, string st_time, string end_time, string hotel_code, string RoomNumber)
        {
            try
            {
                string IP = "";
                string PPP = Request.UserHostAddress;
                string III = Request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrEmpty(III))
                {
                    IP = PPP;
                }
                else
                {
                    IP = III;
                }
                WebAPIMonitorData s = new WebAPIMonitorData();
                string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                s.MethodName = MethodName;
                s.InvokStart_Time = st_time;
                s.InvokEnd_Time = end_time;
                s.HotelCode = hotel_code;
                s.RoomNumber = RoomNumber;
                s.RemoteIP = IP;
                s.Parameters = new List<string>() { jsonData };
                SendMQTTData.WebAPI_DataSend<WebAPIMonitorData>(s, mqtt_topic);
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 设置空调
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUAir(string jsonData)
        {
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.SetRCUAir);
                WebApiInvoke_FenXi("SetRCUAir");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string modalAddress = jData["modalAddress"].ToString();//组地址
                var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);
                if (hostModal == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]无效的空调" }, JsonRequestBehavior.AllowGet);
                }
                int status = 0, brightness = 0, temperature = 0, fanSpeed = 0, mode = 0, valve = 0;//0表示不变
                StringBuilder detail = new StringBuilder();
                detail.Append(string.Format("设置客房{0}{1}({2})：", roomNumber, hostModal.Modal.Name, modalAddress));
                if (jData["onOff"] != null)
                {
                    status = int.Parse(jData["onOff"].ToString());//开关：1开，2关
                    detail.Append("状态：" + (status == 1 ? "打开，" : "关闭，"));
                }
                if (jData["temperature"] != null)
                {
                    temperature = int.Parse(jData["temperature"].ToString());//设置温度16~32
                    detail.Append("温度：" + temperature.ToString() + "，");
                }
                if (jData["fanSpeed"] != null)
                {
                    fanSpeed = int.Parse(jData["fanSpeed"].ToString());//风速：0自动，1低速，2中速，3高速
                    switch (fanSpeed)
                    {
                        case 1:
                            detail.Append("风速：" + "低速，");
                            break;
                        case 2:
                            detail.Append("风速：" + "中速，");
                            break;
                        case 3:
                            detail.Append("风速：" + "高速，");
                            break;
                        default:
                            detail.Append("风速：" + "自动，");
                            break;
                    }
                }
                if (jData["mode"] != null)
                {
                    mode = int.Parse(jData["mode"].ToString());//模式：0自动，1制冷，2制热，3送风
                    switch (mode)
                    {
                        case 1:
                            detail.Append("模式：" + "制冷，");
                            break;
                        case 2:
                            detail.Append("模式：" + "制热，");
                            break;
                        case 3:
                            detail.Append("模式：" + "送风，");
                            break;
                        default:
                            detail.Append("模式：" + "自动，");
                            break;
                    }
                }
                if (jData["valve"] != null)
                {
                    valve = int.Parse(jData["valve"].ToString());//阀门：1开，2关
                    detail.Append("阀门：" + (status == 1 ? "打开" : "关闭"));
                }

                HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);

                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("AirConditioningControl"), detail.ToString(), true, "api", hotelID);


                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "SetRCUAir");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置空调失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取房间的场景列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetRoomSceneList(string jsonData)
        {

            Interlocked.Increment(ref WebAPI_TongJi.GetRoomSceneList);
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                WebApiInvoke_FenXi("GetRoomSceneList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string code = jData["code"].ToString();
                string cd = jData["creatDate"].ToString();
                List<SceneState> list = new List<SceneState>();
                string KKK = "GetRoomSceneList_" + code + "_" + roomNumber + "_" + cd;
                var ooo = HttpContext.Cache.Get(KKK);
                if (ooo != null)
                {
                    list = ooo as List<SceneState>;
                }
                else
                {
                    Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                    if (host == null)
                    {
                        return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                    }
                    IList<RoomTypeScene> modals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                    if (modals == null || modals.Count < 1)
                    {
                        return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]未配置场景" }, JsonRequestBehavior.AllowGet);
                    }
                    foreach (var modal in modals)
                    {
                        SceneState sceneState = new SceneState
                        {
                            SceneID = modal.ID,
                            Name = modal.Name,
                            Icon = modal.Icon
                        };
                        list.Add(sceneState);
                    }
                    HttpContext.Cache.Insert(KKK, list, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetRoomSceneList");
                //SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), "获取客房" + roomNumber + "场景信息", true, "api", hotelID);
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取场景失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 设置场景
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUScene(string jsonData)
        {

            Interlocked.Increment(ref WebAPI_TongJi.SetRCUScene);
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                WebApiInvoke_FenXi("SetRCUScene");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                if (!CheckGetPower(host))
                {
                    return Json(new { IsSuccess = false, Result = "非取电状态，不可控制！" }, JsonRequestBehavior.AllowGet);
                }
                string sceneID = jData["sceneID"].ToString();//场景ID：1、2、3
                //string status = jData["status"].ToString();//状态：1开，2关

                RoomTypeScene scene = null;
                string KKK = "SetSceneData_" + sceneID;
                var ooo = HttpContext.Cache.Get(KKK);
                if (ooo != null)
                {
                    scene = ooo as RoomTypeScene;
                }
                else
                {
                    scene = RoomTypeSceneManager.Get(int.Parse(sceneID));
                    if (scene != null)
                    {
                        HttpContext.Cache.Insert(KKK, scene, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                    }
                }
                if (scene == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]无效的场景" }, JsonRequestBehavior.AllowGet);
                }
                //LightControlManager.ApplyScene(host, scene);
                string repeat = Guid.NewGuid().ToString("N");
                for (int i = 0; i < 3; i++)
                {
                    Thread.Sleep(200);
                    // LightControlManager.ApplyScene(host, scene);
                    LightControlManager.ApplyScene_Repeat(repeat, host, scene);
                }

                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房{0}{1}场景", roomNumber, scene.Name), true, "api", hotelID);


                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "SetRCUScene");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置场景失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取房间的灯光列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        //public ActionResult GetRoomLightList_Deprecate(string jsonData)
        public ActionResult GetRoomLightList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //return Json(new { IsSuccess = false, Result = "接口修改调整" }, JsonRequestBehavior.AllowGet);
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRoomLightList);
                WebApiInvoke_FenXi("GetRoomLightList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string code = jData["code"].ToString();
                string cd = jData["creatDate"].ToString();
                Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                IList<Light> list = new List<Light>();

                string KKK = "GetRoomLightList_" + code + "_" + roomNumber + "_" + cd;
                var QQQ = HttpContext.Cache.Get(KKK);
                if (QQQ != null)
                {
                    list = QQQ as IList<Light>;
                }
                else
                {
                    //IList<HostModal> hostModals = HostModalManager.LoadAll().Where(r => (r.Modal.Type == DeviceType.Relay || r.Modal.Type == DeviceType.Dimmer
                    //    || r.Modal.Type == DeviceType.PWMDimmer || r.Modal.Type == DeviceType.Traic || r.Modal.Type == DeviceType.PWMExpand || r.Modal.Type == DeviceType.PBLED)
                    //    && r.HostID == host.ID && r.Modal.ActiveIndicator == true).ToList();
                    IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).ToList();
                    //if ((hostModals1 == null || hostModals1.Count < 1) && (hostModals2 == null || hostModals2.Count < 1))
                    //{
                    //    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]未配置灯光或调光" }, JsonRequestBehavior.AllowGet);
                    //}
                    foreach (HostModal modal in hostModals)
                    {
                        switch (modal.Modal.Type)
                        {
                            case DeviceType.Relay://主机继电器
                            case DeviceType.Dimmer://LED调光
                            case DeviceType.PWMDimmer://PWM调光
                            case DeviceType.PWMExpand://PWM扩展
                            case DeviceType.PBLED:
                            case DeviceType.Traic://可控硅调光
                            case DeviceType.Strip://灯带调光
                            case DeviceType.A9IORelay:
                            case DeviceType.LVout://弱电输出
                            case DeviceType.Expand://扩展继电器
                            case DeviceType.PB20:
                            case DeviceType.PB20_LD:
                            case DeviceType.PB20_LS:
                                Light light = new Light
                                {
                                    Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                                    ModalAddress = modal.Modal.ModalAddress,
                                    Status = modal.Status,
                                    Brightness = modal.Brightness
                                };
                                list.Add(light);
                                break;
                        }
                    }
                    HttpContext.Cache.Insert(KKK, list, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetRoomLightList");
                //SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("LightControl"), "获取客房" + roomNumber + "灯光信息", true, "api", hotelID);
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取灯光失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 设置灯光
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCULight(string jsonData)
        {
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.SetRCULight);
                WebApiInvoke_FenXi("SetRCULight");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                if (!CheckGetPower(host))
                {
                    return Json(new { IsSuccess = false, Result = "非取电状态，不可控制！" }, JsonRequestBehavior.AllowGet);
                }
                string modalAddress = jData["modalAddress"].ToString();//组地址
                int status = Convert.ToInt16(jData["status"].ToString());//状态：1开，2关
                int brightness = Convert.ToInt16(jData["brightness"].ToString());//亮度：0~100

                var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);
                if (hostModal == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]无效的灯光" }, JsonRequestBehavior.AllowGet);
                }

                HostModalManager.SetDevice(host, hostModal, status, brightness);

                string detail = string.Format("{0}客房{1}{2}({3})，亮度{4}", (status == 1 ? "打开" : "关闭"), roomNumber, hostModal.Modal.Name, modalAddress, brightness);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("LightControl"), detail, true, "api", hotelID);

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "SetRCULight");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置灯光失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取房间的窗帘列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        //public ActionResult GetRoomCurtainList_Deprecate(string jsonData)
        public ActionResult GetRoomCurtainList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //return Json(new { IsSuccess = false, Result = "接口修改调整" }, JsonRequestBehavior.AllowGet);
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRoomCurtainList);
                WebApiInvoke_FenXi("GetRCUStatus");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string code = jData["code"].ToString();
                string cd = jData["creatDate"].ToString();
                Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                IList<Curtain> list = new List<Curtain>();
                string KKK = "GetRoomCurtainList_" + code + "_" + roomNumber + "_" + code;
                var data = HttpContext.Cache.Get(KKK);
                if (data != null)
                {
                    list = data as IList<Curtain>;
                }
                else
                {
                    IList<HostModal> hostModals = HostModalManager.Load(host.ID, DeviceType.Curtain).Where(r => r.Modal.WXActiveIndicator).ToList();
                    if (hostModals == null || hostModals.Count < 1)
                    {
                        return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]未配置窗帘" }, JsonRequestBehavior.AllowGet);
                    }
                    foreach (HostModal modal in hostModals)
                    {
                        Curtain curtain = new Curtain
                        {
                            Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                            ModalAddress = modal.Modal.ModalAddress,
                            Status = modal.Status
                        };
                        list.Add(curtain);
                    }
                    HttpContext.Cache.Insert(KKK, list, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetRoomCurtainList");
                //SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("CurtainControl"), "获取客房" + roomNumber + "窗帘信息", true, "api", hotelID);
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取窗帘失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 设置窗帘
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUCurtain(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.SetRCUCurtain);
                WebApiInvoke_FenXi("SetRCUCurtain");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                if (!CheckGetPower(host))
                {
                    return Json(new { IsSuccess = false, Result = "非取电状态，不可控制！" }, JsonRequestBehavior.AllowGet);
                }
                string modalAddress = jData["modalAddress"].ToString();//组地址
                int status = Convert.ToInt16(jData["status"].ToString());//状态：1开，2关，6停止

                var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);
                if (hostModal == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]无效的窗帘" }, JsonRequestBehavior.AllowGet);
                }

                HostModalManager.SetDevice(host, hostModal, status, 0);

                string detail = string.Format("{0}客房{1}{2}({3})", (status == 1 ? "打开" : (status == 6 ? "停止" : "关闭")), roomNumber, hostModal.Modal.Name, modalAddress);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("CurtainControl"), detail, true, "api", hotelID);


                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "SetRCUCurtain");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置窗帘失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                logger.Error(ex.StackTrace);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取房间的背景音乐列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetRoomMusicList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRoomMusicList);
                WebApiInvoke_FenXi("GetRoomMusicList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                IList<HostModal> hostModals = HostModalManager.Load(host.ID, DeviceType.Music).Where(r => r.Modal.WXActiveIndicator).ToList();
                if (hostModals == null || hostModals.Count < 1)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]未配置背景音乐" }, JsonRequestBehavior.AllowGet);
                }
                IList<Music> list = new List<Music>();
                foreach (HostModal modal in hostModals)
                {
                    Music music = new Music
                    {
                        Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                        ModalAddress = modal.Modal.ModalAddress,
                        Status = modal.Status,
                        Brightness = modal.Brightness,
                        Mode = modal.Mode
                    };
                    list.Add(music);
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetRoomMusicList");
                //SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("CurtainControl"), "获取客房" + roomNumber + "背景音乐信息", true, "api", hotelID);
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取窗帘失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 设置背景音乐
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUMusic(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.SetRCUMusic);
                WebApiInvoke_FenXi("SetRCUMusic");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                if (!CheckGetPower(host))
                {
                    return Json(new { IsSuccess = false, Result = "非取电状态，不可控制！" }, JsonRequestBehavior.AllowGet);
                }
                string modalAddress = jData["modalAddress"].ToString();//组地址

                var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);
                if (hostModal == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]无效的背景音乐" }, JsonRequestBehavior.AllowGet);
                }

                int status = 0, brightness = 0, mode = 0;//0表示不变
                StringBuilder detail = new StringBuilder();
                detail.Append(string.Format("设置客房{0}{1}({2})：", roomNumber, hostModal.Modal.Name, modalAddress));
                if (jData["status"] != null)
                {
                    status = Convert.ToInt16(jData["status"].ToString());//状态：1开，2关
                    detail.Append("状态：" + (status == 1 ? "打开，" : "关闭，"));
                }
                if (jData["brightness"] != null)
                {
                    brightness = Convert.ToInt16(jData["brightness"].ToString());//音量：1~10
                    detail.Append("音量：" + brightness + "，");
                }

                if (jData["mode"] != null)
                {
                    mode = int.Parse(jData["mode"].ToString());//模式：0自动，1制冷，2制热，3送风
                    switch (mode)
                    {
                        case 2:
                            detail.Append("模式：" + "暂停");
                            break;
                        case 3:
                            detail.Append("模式：" + "上一曲");
                            break;
                        case 4:
                            detail.Append("模式：" + "下一曲");
                            break;
                        case 5:
                            detail.Append("模式：" + "音量加");
                            break;
                        case 6:
                            detail.Append("模式：" + "音量减");
                            break;
                        default:
                            detail.Append("模式：" + "播放");
                            break;
                    }
                }

                HostModalManager.SetDevice(host, hostModal, status, brightness, 0, 0, mode, 0);
                //string detail = string.Format("{0}客房{1}{2}({3})", (status == 1 ? "打开" : (status == 6 ? "停止" : "关闭")), roomNumber, hostModal.Modal.Name, modalAddress);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("CurtainControl"), detail.ToString(), true, "api", hotelID);


                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "SetRCUMusic");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置窗帘失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取房间的服务列表
        /// 
        /// 
        /// https://pms.boonlive-rcu.com/api/GetRoomServiceList?jsonData={"creatDate":"2023-11-16","roomNumber":"2206","code":"1762"}
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetRoomServiceList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRoomServiceList);
                WebApiInvoke_FenXi("GetRoomServiceList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string code = jData["code"].ToString();
                string cd = jData["creatDate"].ToString();
                Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                IList<Light> list = new List<Light>();

                string KKK = "GetRoomServiceList_" + code + "_" + roomNumber + "_" + cd;
                var data = HttpContext.Cache.Get(KKK);
                if (data != null)
                {
                    list = data as IList<Light>;
                }
                else
                {
                    IList<HostModal> hostModals = HostModalManager.Load(host.ID, DeviceType.ServiceInfo).Where(r => r.Modal.WXActiveIndicator).ToList();
                    if (hostModals == null || hostModals.Count < 1)
                    {
                        return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]未配置服务信息" }, JsonRequestBehavior.AllowGet);
                    }
                    //logger.Error(string.Format("api获取酒店{0}客房{1}服务列表，来自{2}", jData["code"].ToString(), roomNumber, GetClientIP()));
                    foreach (HostModal modal in hostModals)
                    {
                        Light light = new Light
                        {
                            Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                            ModalAddress = modal.Modal.ModalAddress,
                            Status = modal.Status
                        };
                        list.Add(light);
                    }
                    HttpContext.Cache.Insert(KKK, list, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetRoomServiceList");
                //SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SetRoomService"), "获取客房" + roomNumber + "服务信息", true, "api", hotelID);
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取服务失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 设置服务
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetRCUService(string jsonData)
        {
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.SetRCUService);
                WebApiInvoke_FenXi("SetRCUService");
                string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string modalAddress = jData["modalAddress"].ToString();//组地址
                if (!modalAddress.StartsWith("020") && !CheckGetPower(host))//微信锁类型过滤
                {
                    return Json(new { IsSuccess = false, Result = "非取电状态，不可控制！" }, JsonRequestBehavior.AllowGet);
                }
                int status = Convert.ToInt16(jData["status"].ToString());//状态：1开，2关
                int brightness = status == 1 ? 100 : 0; //Convert.ToInt16(jData["brightness"].ToString());//亮度：0~100

                var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);
                if (hostModal == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]无效的服务" }, JsonRequestBehavior.AllowGet);
                }
                switch (modalAddress)
                {
                    case "004000008"://SOS
                    case "004000013"://门磁
                        return Json(new { IsSuccess = false, Result = "该服务(" + modalAddress + ")不可远程控制" }, JsonRequestBehavior.AllowGet);
                }

                HostModalManager.SetDevice(host, hostModal, status, brightness);

                string detail = string.Format("{0}客房{1}{2}({3})服务", (status == 1 ? "打开" : "关闭"), roomNumber, hostModal.Modal.Name, modalAddress);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SetRoomService"), detail, true, "api", hotelID);


                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "SetRCUService");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置服务失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取设备操作记录
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetDeviceOperationLog(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {

                WebApiInvoke_FenXi("GetDeviceOperationLog");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string modalAddress = jData["modalAddress"].ToString();//组地址
                IList<HostModalRecord> result = HostModalRecordManager.LoadByHostID(host.ID, modalAddress);

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetDeviceOperationLog");
                return Json(new { IsSuccess = true, Result = result }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取设备操作记录失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取操作记录
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetOperationLog(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetOperationLog);
                WebApiInvoke_FenXi("GetOperationLog");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string searchDate = "";
                if (jData["searchDate"] != null && jData["searchDate"].ToString() != "")
                {
                    searchDate = Convert.ToDateTime(jData["searchDate"].ToString()).ToString("yyyy-MM-dd");
                }
                IList<SysSystemLogs> logs = SysSystemLogsManager.LoadAll().Where(r => r.HotelID == hotelID && r.Account == "api").ToList();
                if (!string.IsNullOrEmpty(searchDate))
                {
                    logs = logs.Where(r => Convert.ToDateTime(r.Time).ToString("yyyy-MM-dd") == searchDate).ToList();
                }
                logs = logs.OrderByDescending(o => o.Time).ToList();
                IList<object> list = new List<object>();
                foreach (SysSystemLogs log in logs)
                {
                    list.Add(new
                    {
                        Action = log.Action,
                        Detail = log.Detail,
                        Result = log.Result,
                        Account = log.Account,
                        IP = log.IP,
                        Time = Convert.ToDateTime(log.Time).ToString("yyyy-MM-dd HH:mm:ss")
                    });
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetOperationLog");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取操作记录失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取空气质量检测数据
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetAirDetectList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetAirDetectList);
                WebApiInvoke_FenXi("GetAirDetectList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string code = jData["code"].ToString();
                string cd = jData["creatDate"].ToString();
                IList<Light> list = new List<Light>();

                string KKK = "GetAirDetectList_" + code + "_" + roomNumber + "_" + cd;
                var ooo = HttpContext.Cache.Get(KKK);
                if (ooo != null)
                {
                    list = ooo as IList<Light>;
                }
                else
                {
                    Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                    if (host == null)
                    {
                        return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                    }
                    var hostModals = HostModalManager.Load(host.ID, DeviceType.AirDetect).Where(r => r.Modal.WXActiveIndicator);
                    foreach (HostModal modal in hostModals)
                    {
                        Light light = new Light
                        {
                            Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                            ModalAddress = modal.Modal.ModalAddress,
                            Brightness = modal.Brightness
                        };
                        list.Add(light);
                    }
                    HttpContext.Cache.Insert(KKK, list, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0));
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetAirDetectList");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取空气质量检测数据失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }


        public class FaultData
        {
            public bool RCU_Status { get; set; }
            public IEnumerable<object> list { get; set; }
        }
        /// <summary>
        /// 获取主机异常数据
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHostFaultList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetHostFaultList);
                WebApiInvoke_FenXi("GetHostFaultList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                Host host = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, roomNumber);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                var hostFault = HostFaultsManager.LoadHostFault(host.ID);


                string host_number = host.HostNumber;
                string mac = host.MAC;
                bool is_online = CSRedisCacheHelper.Contains(host_number, mac);
                //roomModel.HostStatus = is_online;//主机状态：0离线，1在

                IList<HostModal> AllDeviceData = null;//RoomServiceManager.LoadCurrentRoomServices(room.HostID);

                string Key = "AllDeviceData_" + host.ID.ToString();
                object oos = HttpContext.Cache.Get(Key);
                if (oos != null)
                {
                    AllDeviceData = oos as IList<HostModal>;
                }
                else
                {
                    AllDeviceData = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.ActiveIndicator && r.Modal.Abnormal).ToList();//RoomServiceManager.LoadCurrentRoomServices(room.HostID);
                }


                var list = hostFault.Select((r) =>
                    {
                        return new FFFault
                         {
                             Name = ReturnNameByLanguage(r[0].ToString(), r[1].ToString(), r[2].ToString()),
                             Address = r[7].ToString(),

                             //8
                             AbnormalStatus = r[8].ToString(),
                             StatusDate = Convert.ToDateTime(r[9]).Year < 1900 ? "" : Convert.ToDateTime(r[9]).ToString("yyyy-MM-dd HH:mm:ss"),


                             //10
                             AbnormalElectricQty = r[10].ToString(),
                             ElectricQtyDate = Convert.ToDateTime(r[11]).Year < 1900 ? "" : Convert.ToDateTime(r[11]).ToString("yyyy-MM-dd HH:mm:ss"),

                             // 12
                             Abnormal3 = (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"),

                             //14
                             Abnormal4 = r[14].ToString(),
                             Abnormal4Date = Convert.ToDateTime(r[15]).Year < 1900 ? "" : Convert.ToDateTime(r[15]).ToString("yyyy-MM-dd HH:mm:ss")
                         };
                    });

                List<FFFault> llist = new List<FFFault>();
                foreach (var item1 in AllDeviceData)
                {
                    //如果这个数据在故障表中出现过就代表 他已经出现了故障，就不添加到故障表中
                    bool bl = list.Any(A => A.Address.Equals(item1.Modal.ModalAddress));
                    if (!bl)
                    {
                        FFFault f = new FFFault();
                        f.Name = item1.Modal.Name;
                        f.Address = item1.Modal.ModalAddress;

                        //离线或者在线
                        //没有离线，所以是0
                        f.AbnormalStatus = "0";
                        f.StatusDate = "";

                        //10
                        f.AbnormalElectricQty = "";
                        f.ElectricQtyDate = "";

                        // 12
                        f.Abnormal3 = "";//数据乘以10，单位mA
                        f.Abnormal3Date = "";

                        //14
                        f.Abnormal4 = "";
                        f.Abnormal4Date = "";
                        llist.Add(f);
                    }
                }
                llist.AddRange(list);
                FaultData d = new FaultData();
                d.list = llist;
                d.RCU_Status = is_online;

                return Json(new { IsSuccess = true, Result = d }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取主机异常数据失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        public class FFFault
        {
            public string Name;
            public string Address;

            public string AbnormalStatus;
            public string StatusDate;

            public string AbnormalElectricQty;
            public string ElectricQtyDate;

            public string Abnormal3;
            public string Abnormal3Date;

            public string Abnormal4;
            public string Abnormal4Date;
        }
        /// <summary>
        /// 获取房型及其回路数据
        /// 宝易软件会用到
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetRoomTypeAndModalsList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRoomTypeAndModalsList);
                WebApiInvoke_FenXi("GetRoomTypeAndModalsList");
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                Host host1 = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host1 == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                //阿宝添加的
                //2025-01-02
                //修改原因： 添加 是否删除字段条件
                IList<RoomType> roomTypes = RoomTypeManager.LoadAll().Where(r => r.HotelID == hotelID && !r.IsDeleted).ToList();
                IList<object> list = new List<object>();
                foreach (RoomType roomType in roomTypes)
                {
                    IList<object> modalsList = new List<object>();
                    foreach (RoomTypeModal model in roomType.Modals)
                    {
                        if (model.WXActiveIndicator)
                        {
                            modalsList.Add(new
                            {
                                ID = model.ID,
                                ModalAddress = model.ModalAddress,
                                Name = model.Name,
                                EnglistName = model.EnglishName,
                                TWName = model.TWName,
                                TypeName = Common.Tools.GetDescription(model.Type)
                            });
                        }
                    }
                    list.Add(new
                    {
                        ID = roomType.ID,
                        Code = roomType.Code,
                        Name = roomType.Name,
                        Modals = modalsList
                    });
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetRoomTypeAndModalsList");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取房型及其回路数据失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取指定酒店信息
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHotelInfo(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                SysHotel sysHotel = SysHotelManager.GetByCode(jData["code"].ToString(), Convert.ToDateTime(jData["creatDate"].ToString()));
                if (sysHotel == null)
                {
                    return Json(new { IsSuccess = false, Result = "酒店未知，请核实参数" }, JsonRequestBehavior.AllowGet);
                }
                IList<object> list = new List<object>();
                list.Add(new
                {
                    Code = sysHotel.Code,
                    Name = sysHotel.Name,
                    EName = sysHotel.EName,
                    TWName = sysHotel.TWName,
                    Contact = sysHotel.Contact,
                    Phone = sysHotel.Phone,
                    Address = sysHotel.Address,
                    TVControlUrl = sysHotel.TVControlUrl,
                    TVControlToken = sysHotel.TVControlToken,
                    WelcomeSpeech = sysHotel.WelcomeSpeech,
                    GoodbyeSpeech = sysHotel.GoodbyeSpeech,
                    DeviceStatusPushURL = sysHotel.DeviceStatusPushURL,
                    ValidateDate = sysHotel.ValidateDate,
                    Remark = sysHotel.Remark
                });

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                TongJi(jsonData, start_time, end_time, jData, "GetHotelInfo");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店信息失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取酒店信息失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost()]
        public ActionResult GetHotelIdByCode(string code, string key)
        {
            if (key.Equals("i_love_blw^_^"))
            {
                SysHotel sysHotel = SysHotelManager.GetByCode(code);
                return Json(new { id = sysHotel.ID, createdDate = sysHotel.CreatedDate, welcomeSpeech = sysHotel.WelcomeSpeech }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { id = 0 }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost()]
        public ActionResult GetHotelListByCode(string jsonData)
        {
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                if (jData["key"].ToString() != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                string code = jData["id"].ToString();
                int id = 0;
                int.TryParse(code, out id);
                var hotel = SysHotelManager.LoadAll().Where(r => r.ID == id && !r.IsDeleted).FirstOrDefault();

                string CreatDate = hotel.CreatedDate.ToString("yyyy-MM-dd");
                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHotelList");
                return Json(new { IsSuccess = true, Result = CreatDate }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店列表失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取酒店列表失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取酒店列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHotelList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                if (jData["key"].ToString() != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                var hotels = SysHotelManager.LoadAll().Where(r => !r.IsDeleted).ToList();
                IList<object> list = new List<object>();
                foreach (SysHotel hotel in hotels)
                {
                    list.Add(new
                    {
                        ID = hotel.ID,
                        Code = hotel.Code,
                        Name = hotel.Name,
                        EName = hotel.EName,
                        TWName = hotel.TWName,
                        Contact = hotel.Contact,
                        Phone = hotel.Phone,
                        Address = hotel.Address,
                        ValidateDate = hotel.ValidateDate,
                        CreatDate = hotel.CreatedDate.ToString("yyyy-MM-dd"),
                        Remark = hotel.Remark,
                        Status = hotel.Status,
                        IsApprove = hotel.IsApprove,
                        SysHotelGroupID = hotel.SysHotelGroup == null ? 0 : hotel.SysHotelGroup.ID,
                        SysHotelGroupName = hotel.SysHotelGroup == null ? "" : hotel.SysHotelGroup.Name,
                    });
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHotelList");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店列表失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取酒店列表失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取酒店分组列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHotelGroupList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                if (jData["key"].ToString() != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                var hotelGroups = SysHotelGroupManager.LoadAll().Where(r => !r.IsDeleted).ToList();
                IList<object> list = new List<object>();
                foreach (SysHotelGroup hotelGroup in hotelGroups)
                {
                    list.Add(new
                    {
                        ID = hotelGroup.ID,
                        Name = hotelGroup.Name,
                        ParentID = hotelGroup.Parent == null ? 0 : hotelGroup.Parent.ID,
                        ParentName = hotelGroup.Parent == null ? "" : hotelGroup.Parent.Name,
                        Sort = hotelGroup.Sort
                    });
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHotelGroupList");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店分组列表失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取酒店分组列表失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetUserList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                if (jData["key"].ToString() != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                var users = SysUserManager.LoadAll().Where(r => !r.IsDeleted).ToList();
                IList<object> list = new List<object>();
                foreach (SysUsers user in users)
                {
                    list.Add(new
                    {
                        ID = user.ID,
                        HotelID = user.HotelID,
                        SysHotelGroupID = user.SysHotelGroup == null ? 0 : user.SysHotelGroup.ID,
                        SysHotelGroupName = user.SysHotelGroup == null ? "" : user.SysHotelGroup.Name,
                        GroupID = user.Group == null ? 0 : user.Group.ID,
                        GroupName = user.Group == null ? "" : user.Group.Name,
                        Account = user.Account,
                        Password = user.Password,
                        Password2 = user.Password2,
                        Name = user.Name,
                        RoleID = user.Role == null ? 0 : user.Role.ID,
                        RoleName = user.Role == null ? "" : user.Role.Name,
                        Sex = user.Sex,
                        Phone = user.Phone,
                        Email = user.Email,
                        ActiveIndicator = user.ActiveIndicator,
                        CreatedDate = user.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        Sort = user.Sort,
                        Remark = user.Remark
                    });
                }

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetUserList");
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取用户列表失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取用户列表失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取主机列表
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHostList(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                Host host1 = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host1 == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                IList<Host> hosts = HostManager.LoadAll(hotelID).OrderBy(r => r.RoomNumber).ToList();

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHostList");
                return Json(new { IsSuccess = true, Result = GetHostList(hosts) }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取主机列表失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取主机列表：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取酒店列表 通过GroupId
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHostListWithGroupId(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                Host host1 = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host1 == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string Key = "GetHostListWithGroupId_" + hotelID;
                object obj = MemoryCacheHelper.Get(Key);
                IList<Host> hosts = null;
                if (obj != null)
                {
                    hosts = obj as IList<Host>;
                }
                else
                {
                    hosts = HostManager.LoadAll(hotelID).OrderBy(r => r.RoomNumber).ToList();
                    MemoryCacheHelper.Set(Key, hosts);
                }
                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHostList");
                return Json(new { IsSuccess = true, Result = GetHostListNew(hosts) }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取主机列表失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "获取主机列表：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 根据mac获取主机
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHostByMAC(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                if (jData["key"].ToString() != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                if (string.IsNullOrEmpty(jData["mac"].ToString()))
                {
                    return Json(new { IsSuccess = false, Result = "参数mac不能为空" }, JsonRequestBehavior.AllowGet);
                }
                IList<Host> hosts = HostManager.LoadByMac(jData["mac"].ToString());

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHostByMAC");
                return Json(new { IsSuccess = true, Result = GetHostList(hosts) }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("根据mac获取主机失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "根据mac获取主机失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost()]
        public ActionResult GetHostByMAC_POST()
        {
            try
            {
                string a = Request.Form["key"].ToString();
                //string b = Request.Form["mac"].ToString();
                string rm = Request.Form["roomnumber"].ToString();
                string hotelcode = Request.Form["hotelcode"].ToString();
                if (a != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                if (string.IsNullOrEmpty(hotelcode))
                {
                    return Json(new { IsSuccess = false, Result = "参数hotelcode不能为空" }, JsonRequestBehavior.AllowGet);
                }
                Host hosts = HostManager.GetByRoomNumber(rm, hotelcode);
                var Q = new List<Host>();
                Q.Add(hosts);
                return Json(new { IsSuccess = true, Result = GetHostList_NEW(Q) }, JsonRequestBehavior.AllowGet);
                //return Json(new { IsSuccess = true, Result = hosts }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("根据mac获取主机失败：。原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "根据mac获取主机失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 根据房号和酒店ID获取主机
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHostByRoomNumber(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //Request.InputStream.Position = 0;
            //byte[] reqBody = new byte[Request.InputStream.Length];
            //Request.InputStream.Read(reqBody, 0, reqBody.Length);
            //string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            //if (!string.IsNullOrEmpty(reqData))
            //{
            //    jsonData = reqData;
            //}
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                if (jData["key"].ToString() != "blw_ws@2015")
                {
                    return Json(new { IsSuccess = false, Result = "参数key无效" }, JsonRequestBehavior.AllowGet);
                }
                if (string.IsNullOrEmpty(jData["roomNumber"].ToString()))
                {
                    return Json(new { IsSuccess = false, Result = "参数roomNumber不能为空" }, JsonRequestBehavior.AllowGet);
                }
                if (string.IsNullOrEmpty(jData["hotelID"].ToString()))
                {
                    return Json(new { IsSuccess = false, Result = "参数hotelID不能为空" }, JsonRequestBehavior.AllowGet);
                }
                Host host = HostManager.GetByRoomNumber(jData["roomNumber"].ToString(), Convert.ToInt16(jData["hotelID"].ToString()));
                IList<Host> hosts = new List<Host>();
                hosts.Add(host);

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "GetHostByRoomNumber");
                return Json(new { IsSuccess = true, Result = GetHostList(hosts) }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("根据房号和酒店ID获取主机失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "根据房号和酒店ID获取主机失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 转换输出主机列表
        /// </summary>
        /// <param name="hosts"></param>
        /// <returns></returns>
        private IList<object> GetHostList(IList<Host> hosts)
        {
            IList<object> list = new List<object>();
            foreach (Host host in hosts)
            {
                list.Add(new
                {
                    ID = host.ID,
                    HotelID = host.SysHotel == null ? 0 : host.SysHotel.ID,
                    HotelName = host.SysHotel == null ? "" : host.SysHotel.Name,
                    HostNumber = host.HostNumber,
                    RoomNumber = host.RoomNumber,
                    Status = host.Status,
                    RegisterDate = host.RegisterDate.ToString("yyyy-MM-dd"),
                    RoomStatusID = host.RoomStatus == null ? 0 : host.RoomStatus.ID,
                    RoomStatusName = host.RoomStatus == null ? "" : host.RoomStatus.Name,
                    RoomTypeID = host.RoomType == null ? 0 : host.RoomType.ID,
                    RoomTypeName = host.RoomType == null ? "" : host.RoomType.Name,
                    MAC = host.MAC,
                    MACBindDate = host.MACBindDate == null ? "" : Convert.ToDateTime(host.MACBindDate).ToString("yyyy-MM-dd"),
                    IPType = host.IPType,
                    IP = host.IP,
                    SubnetMask = host.SubnetMask,
                    Gateway = host.Gateway,
                    DNS = host.DNS,
                    Port = host.Port,
                    ServerIP = host.ServerIP,
                    ServerPort = host.ServerPort,
                    Remark = host.Remark,
                    MachineType = host.Model,
                    ConfigurationVersion = host.ConfigVersion,
                    Version = host.Version,
                    LauncherVersion = host.LauncherVersion
                });
            }
            return list;
        }


        private IList<object> GetHostListNew(IList<Host> hosts)
        {
            //string DNDKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000002";
            //string CleanKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000003";
            //string CheckOutKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000006";
            IList<object> list = new List<object>();
            foreach (Host host in hosts)
            {
                string SOSKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000008";
                var hostModal1 = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(SOSKey);
                int status = 0;
                if (hostModal1 != null)
                {
                    status = hostModal1.Status;
                }
                list.Add(new
                {
                    ID = host.ID,
                    HotelID = host.SysHotel == null ? 0 : host.SysHotel.ID,
                    GroupId = host.Group.ID,
                    HotelName = host.SysHotel == null ? "" : host.SysHotel.Name,
                    HostNumber = host.HostNumber,
                    RoomNumber = host.RoomNumber,
                    Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC),
                    SOS_Status = status,
                    RegisterDate = host.RegisterDate.ToString("yyyy-MM-dd"),
                    RoomStatusID = host.RoomStatus == null ? 0 : host.RoomStatus.ID,
                    RoomStatusName = host.RoomStatus == null ? "" : host.RoomStatus.Name,
                    RoomTypeID = host.RoomType == null ? 0 : host.RoomType.ID,
                    RoomTypeName = host.RoomType == null ? "" : host.RoomType.Name,
                    MAC = host.MAC,
                    MACBindDate = host.MACBindDate == null ? "" : Convert.ToDateTime(host.MACBindDate).ToString("yyyy-MM-dd"),
                    IPType = host.IPType,
                    IP = host.IP,
                    SubnetMask = host.SubnetMask,
                    Gateway = host.Gateway,
                    DNS = host.DNS,
                    Port = host.Port,
                    ServerIP = host.ServerIP,
                    ServerPort = host.ServerPort,
                    Remark = host.Remark,
                    MachineType = host.Model,
                    ConfigurationVersion = host.ConfigVersion,
                    Version = host.Version,
                    LauncherVersion = host.LauncherVersion
                });
            }
            return list;
        }

        private IList<object> GetHostList_NEW(IList<Host> hosts)
        {
            IList<object> list = new List<object>();
            foreach (Host host in hosts)
            {
                list.Add(new
                {
                    ID = host.ID,
                    HotelCode = host.SysHotel.Code,
                    HotelID = host.SysHotel == null ? 0 : host.SysHotel.ID,
                    HotelName = host.SysHotel == null ? "" : host.SysHotel.Name,
                    HostNumber = host.HostNumber,
                    RoomNumber = host.RoomNumber,
                    Status = host.Status,
                    RegisterDate = host.RegisterDate.ToString("yyyy-MM-dd"),
                    RoomStatusID = host.RoomStatus == null ? 0 : host.RoomStatus.ID,
                    RoomStatusName = host.RoomStatus == null ? "" : host.RoomStatus.Name,
                    RoomTypeID = host.RoomType == null ? 0 : host.RoomType.ID,
                    RoomTypeName = host.RoomType == null ? "" : host.RoomType.Name,
                    MAC = host.MAC,
                    MACBindDate = host.MACBindDate == null ? "" : Convert.ToDateTime(host.MACBindDate).ToString("yyyy-MM-dd"),
                    IPType = host.IPType,
                    IP = host.IP,
                    SubnetMask = host.SubnetMask,
                    Gateway = host.Gateway,
                    DNS = host.DNS,
                    Port = host.Port,
                    LanIP = host.LanIP,
                    LanPort = host.LanPort,
                    ServerIP = host.ServerIP,
                    ServerPort = host.ServerPort,
                    Remark = host.Remark,
                    TiaoMaoCUID = host.TianMaoCUID,
                    XiaoDuCUID = host.XiaoDuCUID
                });
            }
            return list;
        }
        /// <summary>
        /// 设置或更新主机mac
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SetHostMAC(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string roomNumber = jData["roomNumber"].ToString();
                string mac = jData["mac"].ToString();
                Host host1 = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host1 == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                Host host = HostManager.GetByRoomNumber(roomNumber, hotelID);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = "房号[" + roomNumber + "]不存在" }, JsonRequestBehavior.AllowGet);
                }
                string detail = string.Format("解绑客房({0})主机MAC", roomNumber);
                if (!string.IsNullOrEmpty(mac))
                {
                    IList<Host> hosts = HostManager.LoadByMac(mac);
                    foreach (Host host2 in hosts)
                    {
                        if (host2.ID != host.ID)
                        {
                            return Json(new { IsSuccess = false, Result = string.Format("MAC({0})已绑定在酒店({1})客房({2})下。", mac, host2.SysHotel.Name + host2.SysHotel.Code, host2.RoomNumber) }, JsonRequestBehavior.AllowGet);
                        }
                    }
                    detail = string.Format("绑定客房({0})主机MAC({1})", roomNumber, host.MAC);
                }
                host.MAC = mac;
                host.MACBindDate = DateTime.Now;//更新mac绑定时间
                HostManager.Update(host);

                SaveSystemLog(AuthorityID, "设置主机MAC", detail, true, "api", hotelID);


                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "SetHostMAC");
                return Json(new { IsSuccess = true, Result = string.Format("房号[{0}]{1}成功", roomNumber, string.IsNullOrEmpty(mac) ? "解绑MAC" : "绑定MAC") }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("设置主机MAC失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "设置主机MAC失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 同步房态
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SyncRoomStatus(string jsonData)
        {

            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string hotelCode = jData["hotelCode"].ToString();
                string roomNumber = jData["roomNumber"].ToString();
                Host host = HostManager.GetByRoomNumber(roomNumber, hotelCode);
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Result = string.Format("未找到对应主机(roomNumber:{0},hotelCode:{1})", roomNumber, hotelCode) }, JsonRequestBehavior.AllowGet);
                }
                int roomStatusID = Convert.ToInt16(jData["roomStatusID"]);//设置房态：2出租，4待租，8退房，16空房
                HostManager.ChangeRoomStatus(host, roomStatusID);

                string detail = string.Format("同步客房{0}房态(ID:{1})", roomNumber, roomStatusID);
                SaveSystemLog(AuthorityID, "同步房态", detail, true, "api", hotelID);

                string end_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TongJi(jsonData, start_time, end_time, jData, "SyncRoomStatus");
                return Json(new { IsSuccess = true, Result = "房号[" + roomNumber + "]操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("同步房态失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 提供给腾讯云图调用
        /// <summary>
        /// 酒店分布
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHotelsForTCV()
        {
            ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "https://boonlive-rcu.com");
            try
            {
                IEnumerable<IGrouping<string, SysHotel>> hotelGroup = this.SysHotelManager.LoadAll().GroupBy(r => r.ProvinceCode);
                IList<SysProvince> province = SysProvinceManager.LoadAll();
                IList<object> list = new List<object>();
                foreach (IGrouping<string, SysHotel> item in hotelGroup)
                {
                    if (item.Key != null)
                    {
                        list.Add(new
                        {
                            x = province.Where(r => r.Code == item.Key).FirstOrDefault().Name,
                            y = item.Count(),
                            s = "thermal"
                        });
                    }
                }
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店分布数据失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json("获取酒店分布数据失败：" + ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取主机总数等
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHostsForTCV()
        {
            ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "https://boonlive-rcu.com");
            try
            {
                var hosts = HostManager.LoadAll();
                int onlineCount = hosts.Where(r => r.Status == true).ToList().Count;

                IList<object> list = new List<object>();
                list.Add(new { x = "总数", y = hostBaseCount + hosts.Count });
                list.Add(new { x = "在线", y = hostBaseCount + onlineCount });
                list.Add(new { x = "离线", y = hosts.Count - onlineCount });

                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取主机数据失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json("获取主机数据失败：" + ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 根据状态获取酒店
        /// </summary>
        /// <param name="status">酒店状态：0正式运营，1批量安装，2样板间</param>
        /// <param name="row"></param>
        /// <returns></returns>
        public ActionResult GetHotelsByStatusForTCV(int status, int row)
        {
            ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "https://boonlive-rcu.com");
            try
            {
                var hotels = this.SysHotelManager.LoadAll().Where(r => r.Status == status).Take(row).ToList();
                IList<object> list = new List<object>();
                foreach (SysHotel hotel in hotels)
                {
                    list.Add(new
                    {
                        key1 = hotel.Code,
                        value1 = hotel.Name
                    });
                }
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店数据失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json("获取酒店数据失败：" + ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取存在异常主机
        /// 红外检测逻辑：取电后房间红外5个小时内没触发判断了红外坏
        /// 门磁检查逻辑：房间取电后没有门磁开关信息判断门磁坏
        /// 房间误取电判断：房间两天一直取电不断电判断房间取电不正常
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAbnormalHostsForTCV()
        {
            ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "https://boonlive-rcu.com");
            try
            {
                DataSet dsResult = OverviewManager.LoadHostAbnormalRecordsAll(0);
                IList<object> list = new List<object>();
                foreach (DataRow dr in dsResult.Tables[0].Rows)
                {
                    list.Add(new
                    {
                        key1 = dr["Code"].ToString() + dr["Name"].ToString(),
                        value1 = dr["RoomNumber"].ToString(),
                        value2 = dr["AbnormalName"].ToString()
                    });
                }
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取异常主机数据失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json("获取异常主机数据失败：" + ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 到期提醒
        /// </summary>
        /// <returns></returns>
        public ActionResult GetExpireHotelsForTCV(int row)
        {
            ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "https://boonlive-rcu.com");
            try
            {
                var hotels = this.SysHotelManager.LoadAll().Where(r => r.ValidateDate < DateTime.Now.AddMonths(1)).OrderBy(r => r.ValidateDate).Take(row).ToList();
                IList<object> list = new List<object>();
                foreach (SysHotel hotel in hotels)
                {
                    list.Add(new
                    {
                        key1 = hotel.Code + hotel.Name,
                        value1 = hotel.ValidateDate.ToString("yyyy年M月d日")
                    });
                }
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店到期提醒数据失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json("获取酒店到期提醒数据失败：" + ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 微信小程序调用
        /// <summary>
        /// 微信小程序获取手机号后台：第一步获取session_key
        /// </summary>
        /// <param name="code"></param>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public ActionResult GetSessionKey(string jsonData)
        {
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetSessionKey);
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string code = jData["code"].ToString();
                string appid = jData["appid"].ToString();
                string secret = jData["secret"].ToString();
                string html = string.Empty;
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
                System.IO.Stream ioStream = response.GetResponseStream();
                System.IO.StreamReader sr = new System.IO.StreamReader(ioStream, Encoding.UTF8);
                html = sr.ReadToEnd();
                sr.Close();
                ioStream.Close();
                response.Close();
                JObject jResult = (JObject)JsonConvert.DeserializeObject(html);
                return Json(new { IsSuccess = (jResult["errcode"] == null ? true : false), Result = html }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("小程序获取session_key失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 微信小程序获取手机号后台：第二步解释手机号
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="iv"></param>
        /// <param name="session_key"></param>
        /// <returns></returns>
        public ActionResult GetPhoneNumber(string jsonData)
        {
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetPhoneNumber);
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string encryptedData = jData["encrypted_data"].ToString();
                string iv = jData["iv"].ToString();
                string session_key = jData["session_key"].ToString();
                byte[] encryData = Convert.FromBase64String(encryptedData);
                System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(session_key);
                rijndaelCipher.IV = Convert.FromBase64String(iv);
                rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
                rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);
                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                if (jData["is_gethotelinfo"] == null || !Convert.ToBoolean(jData["is_gethotelinfo"].ToString()))
                {
                    return Json(new { IsSuccess = true, Result = model.phoneNumber }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return GetHotelInfoForWX("{'phone':'" + model.phoneNumber + "'}");
                }
            }
            catch (Exception ex)
            {
                logger.Error("小程序获取手机号失败：" + ex.ToString() + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 通过开房手机号获取对应酒店信息
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult GetHotelInfoForWX(string jsonData)
        {
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetHotelInfoForWX);
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string phone = jData["phone"].ToString();
                if (string.IsNullOrEmpty(phone))
                {
                    return Json(new { IsSuccess = false, Result = "手机号不能为空！" }, JsonRequestBehavior.AllowGet);
                }
                DataTable dtRecord = null;
                using (syncstatus.syncstatusSoapClient wsClient = new syncstatus.syncstatusSoapClient())
                {
                    dtRecord = wsClient.GetCodeAndRoomNumberByPhone(phone);
                    if (dtRecord == null || dtRecord.Rows.Count == 0)
                    {
                        return Json(new { IsSuccess = false, Result = string.Format("该手机号[{0}]未找到当前开房记录！", phone) }, JsonRequestBehavior.AllowGet);
                    }
                    string code = dtRecord.Rows[0]["Code"].ToString();
                    string roomNumber = dtRecord.Rows[0]["RoomNumber"].ToString();
                    SysHotel sysHotel = SysHotelManager.GetByCode(code);
                    if (sysHotel == null)
                    {
                        return Json(new { IsSuccess = false, Result = string.Format("酒店未知，或属于本地部署酒店[code={0}]", code) }, JsonRequestBehavior.AllowGet);
                    }
                    IList<object> list = new List<object>();
                    list.Add(new
                    {
                        code = sysHotel.Code,
                        creatDate = sysHotel.CreatedDate,
                        roomNumber = roomNumber,
                        phone = phone
                    });
                    return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error("获取酒店信息（微信）失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 绿云Opera pms对接
        /// <summary>
        /// 按照绿云Opera PMS文档设计
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult OperaPMSToRCU()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string jsonData = System.Text.Encoding.UTF8.GetString(reqBody);
            //logger.Error("收到Opera数据：" + jsonData);
            try
            {
                OperaPMSRequest request = JsonConvert.DeserializeObject<OperaPMSRequest>(jsonData);//得到PMS请求，ohotel中，集团代码：57173G，酒店代码：57173
                string hotelCode;
                switch (request.hotelCode.ToUpper())
                {
                    case "57173":
                        hotelCode = "1161";
                        break;
                    case "YW-DEV":
                        hotelCode = "1473";
                        break;
                    default:
                        hotelCode = request.hotelCode;
                        break;
                }
                SysHotel hotel = SysHotelManager.GetByCode(hotelCode);
                if (hotel == null)
                {
                    return Json(new { rescode = "0", resDesc = "无效酒店代码：" + request.hotelCode }, JsonRequestBehavior.AllowGet);
                }
                Host host = HostManager.GetByRoomNumber(request.rmno, hotel.ID);
                if (host == null)
                {
                    return Json(new { rescode = "0", resDesc = "无效房号：" + request.rmno }, JsonRequestBehavior.AllowGet);
                }
                if (request.bizType == null)
                {
                    return Json(new { rescode = "0", resDesc = "bizType不能为空" }, JsonRequestBehavior.AllowGet);
                }
                string validate = "8888";//微信验证码，默认身份证后四位
                if (request.idNo != null && request.idNo.Length > 4)
                {
                    validate = request.idNo.Substring(request.idNo.Length - 4);
                }

                switch (request.bizType.ToUpper())
                {
                    case "CHECKIN":
                        HostManager.ChangeRoomStatus(host, 2, validate);//2：出租，4：待租，8：退房，16：空房
                        break;
                    case "CHECKOUT":
                        HostManager.ChangeRoomStatus(host, 8);
                        break;
                    case "RMCHG"://换房：先退房，再开房
                        Host hostOld = HostManager.GetByRoomNumber(request.oldRmno, hotel.ID);
                        if (hostOld == null)
                        {
                            return Json(new { rescode = "0", resDesc = "无效旧房号：" + request.oldRmno }, JsonRequestBehavior.AllowGet);
                        }
                        HostManager.ChangeRoomStatus(hostOld, 8);

                        HostManager.ChangeRoomStatus(host, 2, validate);
                        break;
                    default:
                        HostManager.ChangeRoomStatus(host, 4);//待租
                        break;
                }
                SaveSystemLog(AuthorityID, request.bizType, request.rmno, true, "api", hotel.ID);
                return Json(new { rescode = "200", resDesc = "操作成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("Opera PMS对接RCU失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { rescode = "0", resDesc = "接口处理异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 绿云Opera pms对接
        /// </summary>
        public class OperaPMSRequest
        {
            /// <summary>
            /// 
            /// </summary>
            public DateTime arr { get; set; }
            /// <summary>
            /// 业务点	CHECKIN：入住（多人）CHECKOUT：退房（多人）RMCHG：换房（一人）MASTERCHG:主单信息修改（默认只发送续住）GUESTCHG:客人档案修改（默认只在客人姓名、手机号修改时触发发送）
            /// 注：CHECK-OUT时处理整个房间退房需要判断是否有同住人在住
            /// </summary>
            public string bizType { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public DateTime dep { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> extras { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string firstName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string hotelCode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string hotelGroupCode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string language { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string lastName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string masterId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string profileNum { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string rmno { get; set; }
            /// <summary>
            /// 原房号	换房（RMCHG）的时候才可选择进行发送
            /// </summary>
            public string oldRmno { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public bool share { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string workstationId { get; set; }
            /// <summary>
            /// 证件号
            /// </summary>
            public string idNo { get; set; }

            ///// <summary>
            ///// oHotel中集团代码
            ///// </summary>
            //public string hotelGroupCode { get; set; }
            ///// <summary>
            ///// 集团名称
            ///// </summary>
            ////public string hotelGroupDescript { get; set; }
            ///// <summary>
            ///// oHotel中酒店代码（必需和Opera一致）
            ///// </summary>
            //public string hotelCode { get; set; }
            ///// <summary>
            ///// 酒店名称
            ///// </summary>
            ////public string hotelDescript { get; set; }
            ///// <summary>
            ///// 酒店ID：同一集团下酒店唯一
            ///// </summary>
            ////public long hotelId { get; set; }
            ///// <summary>
            ///// 客人ID：同一酒店下唯一。客人每次入住都会产生一个唯一标识，后面续住（MASTERCHG），退房（CHECKOUT），换房（RMCHG），修改信息（GUESTCHG），这个masterId都是不会变的.Opera订单号（resrvNameId）
            ///// </summary>
            //public long masterId { get; set; }
            ///// <summary>
            ///// 同住人标识：同住客人的Identifier是一致的，如果Identifier不一致，即使前后房号一致也不认为是同住客人。
            ///// </summary>
            ////public long Identifier { get; set; }
            ///// <summary>
            ///// 团队标识	默认为0，标识非团队客人
            ///// </summary>
            ////public long grpAccnt { get; set; }
            ///// <summary>
            ///// 联房标识	相同联房标识的，认为是同行客人
            ///// </summary>
            ////public long linkId { get; set; }
            ///// <summary>
            ///// 业务点	CHECKIN：入住（多人）CHECKOUT：退房（多人）RMCHG：换房（一人）MASTERCHG:主单信息修改（默认只发送续住）GUESTCHG:客人档案修改（默认只在客人姓名、手机号修改时触发发送）
            ///// 注：CHECK-OUT时处理整个房间退房需要判断是否有同住人在住
            ///// </summary>
            //public string bizType { get; set; }
            ///// <summary>
            ///// 全名
            ///// </summary>
            //public string name { get; set; }
            ///// <summary>
            ///// 抵店时间	格式yyyy-MM-dd HH:mm:ss
            ///// </summary>
            //public string arr { get; set; }
            ///// <summary>
            ///// 离店时间	格式yyyy-MM-dd HH:mm:ss
            ///// </summary>
            //public string dep { get; set; }
            ///// <summary>
            ///// 房号	换房操作时，作为新房号使用
            ///// </summary>
            //public string rmno { get; set; }
            ///// <summary>
            ///// 手机号	客人隐私，经过酒店同意才开放
            ///// </summary>
            //public string mobile { get; set; }
            ///// <summary>
            ///// 订单类型（不使用此字段）
            ///// </summary>
            //public string rsvClass { get; set; }
            ///// <summary>
            ///// 名（英文/拼音）
            ///// </summary>
            //public string firstName { get; set; }
            ///// <summary>
            ///// 姓（英文/拼音）
            ///// </summary>
            //public string lastName { get; set; }
            ///// <summary>
            ///// 语种	未做特殊修改情况下：C – 中文，E – 英语，F – 法文，G – 德文，J – 日语，K – 韩文
            ///// </summary>
            //public string language { get; set; }
            ///// <summary>
            ///// 性别	1男/2女
            ///// </summary>
            ////public string sex { get; set; }
            ///// <summary>
            ///// VIP信息（Opera中数据，未作变换）
            ///// </summary>
            //public string vipStatus { get; set; }
            ///// <summary>
            ///// 额外字段（最多10项，字符串列表形式）DefRef1-DefRef10
            ///// </summary>
            //public List<string> extras { get; set; }
            /// <summary>
            /// 证件类型	未做特殊修改情况下：01：身份证，02：临时身份证，14：普通护照（列举3类常用，如需要不常用证件类型，可联系绿云项目经理提供）
            /// </summary>
            //public string idCode { get; set; }
            /// <summary>
            /// 邮箱	客人隐私，经过酒店同意才开放
            /// </summary>
            //public string email { get; set; }
            /// <summary>
            /// 帐户类别	F=散客 G=团队 H=消费帐户
            /// </summary>
            //public string rsvClass { get; set; }
            /// <summary>
            /// 预订人姓名
            /// </summary>
            //public string rsvMan { get; set; }
            /// <summary>
            /// CRS订单号
            /// </summary>
            //public string crsNo { get; set; }
            /// <summary>
            /// 手工单号
            /// </summary>
            //public string rsvNo { get; set; }
            /// <summary>
            /// 房价	酒店隐私，经过酒店同意才开放
            /// </summary>
            //public decimal realRate { get; set; }
            /// <summary>
            /// 业务发生时间	格式yyyy-MM-dd'T'HH:mm:ssZ
            /// </summary>
            //public string date { get; set; }
            /// <summary>
            /// 消费金额	退房（CHECKOUT）的时候才可选择进行发送
            /// </summary>
            //public decimal pay { get; set; }
        }
        #endregion

        #region 若琪音箱对接
        /// <summary>
        /// 若琪对接
        /// </summary>
        /// <returns></returns>
        public ActionResult RokidV2()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.Default.GetString(reqBody);
            try
            {
                Domain.Rokid.Request.RootRequest request = JsonConvert.DeserializeObject<Domain.Rokid.Request.RootRequest>(reqData);

                string token = request.header.authorization.token;
                if (string.IsNullOrEmpty(token))
                {
                    return Json(returnError("token不能为空"), JsonRequestBehavior.AllowGet);
                }
                string hotelCode = token;//.Substring(0, token.IndexOf("BLW"));
                if (token.IndexOf("BLW") > -1)
                {
                    hotelCode = token.Substring(0, token.IndexOf("BLW"));
                }
                SysHotel hotel = SysHotelManager.GetByCode(hotelCode);//根据酒店编码获取酒店
                if (hotel == null)
                {
                    logger.Error("获取指定酒店失败(" + hotelCode + ")");
                    return Json(returnError("获取指定酒店失败(" + hotelCode + ")"), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > hotel.ValidateDate)//酒店已到期
                {
                    return Json(returnError("当前访问酒店已过期"), JsonRequestBehavior.AllowGet);
                }
                switch (request.header.@namespace)
                {
                    case "Rokid.Discovery":
                        {
                            IList<Host> hosts = HostManager.LoadAll(hotel.ID).Where(r => r.Status == true).ToList();
                            List<Domain.Rokid.Discovery.Endpoints> endpoints = new List<Domain.Rokid.Discovery.Endpoints>();
                            foreach (Host host in hosts)
                            {
                                //获取需要控制的场景
                                IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                                foreach (RoomTypeScene scene in sceneModals)
                                {
                                    endpoints.Add(new Domain.Rokid.Discovery.Endpoints
                                    {
                                        endpointId = host.ID.ToString() + "&" + scene.ID.ToString(),
                                        displayType = "scene",
                                        displayName = scene.Name,
                                        recommendRoomName = host.RoomNumber,
                                        recommendHomeName = hotel.Name + "(" + host.RoomNumber + ")",
                                        modelId = "",
                                        additionalInfo = new Domain.Rokid.Discovery.AdditionalInfo { key = "scene" },
                                        capabilities = Domain.Rokid.Discovery.CustomerCapabilities.SwitchCapabilities(),
                                        states = new List<Domain.Rokid.Discovery.States> { new Domain.Rokid.Discovery.States { @interface = "Switch", value = "Off", timeOfSample = DateTime.Now.ToString() } }
                                    });
                                }
                                //获取需要控制的设备信息
                                IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                                foreach (HostModal hostModal in hostModals)
                                {
                                    string displayType = "light";//区分设备种类
                                    List<Domain.Rokid.Discovery.Capabilities> capabilities = Domain.Rokid.Discovery.CustomerCapabilities.SwitchCapabilities();
                                    switch (hostModal.Modal.Type)
                                    {
                                        case DeviceType.Dimmer:
                                        case DeviceType.Traic:
                                        case DeviceType.Strip:
                                        case DeviceType.PWMDimmer:
                                        case DeviceType.PWMExpand:
                                        case DeviceType.PBLED:
                                        case DeviceType.LVout://弱电输出
                                        case DeviceType.PB20:
                                        case DeviceType.PB20_LD:
                                        case DeviceType.PB20_LS:
                                            capabilities = Domain.Rokid.Discovery.CustomerCapabilities.BrightnessCapabilities();
                                            break;
                                        case DeviceType.AirConditioner:
                                            //displayType = "ac";
                                            capabilities = Domain.Rokid.Discovery.CustomerCapabilities.AirCapabilities();
                                            break;
                                        case DeviceType.Curtain:
                                            //displayType = "curtain";
                                            capabilities = Domain.Rokid.Discovery.CustomerCapabilities.MotionSwitchCapabilities();
                                            break;
                                    }
                                    endpoints.Add(new Domain.Rokid.Discovery.Endpoints
                                    {
                                        endpointId = host.ID.ToString() + "&" + hostModal.Modal.ModalAddress,
                                        displayType = displayType,
                                        displayName = hostModal.Modal.Name,
                                        recommendRoomName = host.RoomNumber,
                                        recommendHomeName = hotel.Name + "(" + host.RoomNumber + ")",
                                        modelId = "",
                                        additionalInfo = new Domain.Rokid.Discovery.AdditionalInfo { key = displayType },
                                        capabilities = capabilities,
                                        states = new List<Domain.Rokid.Discovery.States> { new Domain.Rokid.Discovery.States { @interface = "Switch", value = hostModal.Status == 1 ? "On" : "Off", timeOfSample = DateTime.Now.ToString() } }
                                    });
                                }
                            }
                            Domain.Rokid.Discovery.DiscoveryResponse dis = new Domain.Rokid.Discovery.DiscoveryResponse
                            {
                                header = new Domain.Rokid.Discovery.Header
                                {
                                    messageId = request.header.messageId,
                                    @namespace = "Rokid",
                                    name = "DiscoveryResponse",
                                    payloadVersion = "v1"
                                },
                                payload = new Domain.Rokid.Discovery.Payload { endpoints = endpoints }
                            };
                            logger.Error(string.Format("若琪(酒店：{0})本次获取设备数量：{1}", hotel.Code + hotel.Name, dis.payload.endpoints.Count.ToString()));
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(dis),
                                ContentType = "application/json"
                            };
                        }
                    default:
                        {
                            string endpointId = request.endpoint.endpointId;
                            int hostID = Convert.ToInt32(endpointId.Split('&')[0]);
                            Host host = HostManager.Get(hostID);
                            if (host == null)
                            {
                                return Json(returnError("无效的主机,ID=" + hostID.ToString()), JsonRequestBehavior.AllowGet);
                            }
                            if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                            {
                                return Json(returnError("房号[" + host.RoomNumber + "]网络异常"), JsonRequestBehavior.AllowGet);
                            }
                            if (!CheckGetPower(host))
                            {
                                return Json(returnError("房号[" + host.RoomNumber + "]非取电状态，不可控制！"), JsonRequestBehavior.AllowGet);//非取电状态，不可控制！
                            }
                            string modalAddress = endpointId.Split('&')[1];
                            string key = request.endpoint.additionalInfo.key;//区分设备种类
                            string name = request.header.name;
                            List<RoomTypeWXMenus> wxMenus = RoomTypeWXMenusManager.LoadAll(host.RoomType.ID).Where(r => r.ActiveIndicator == true).ToList();
                            //var takePowerModal = HostModalManager.GetByModalAddress(host.ID, "004000001");
                            switch (key)
                            {
                                case "scene"://场景类
                                    //foreach (RoomTypeWXMenus wxMenu in wxMenus)
                                    //{
                                    //    if (wxMenu.Code == "changjing" && wxMenu.TakePower)
                                    //    {
                                    //        if (takePowerModal.Status != 1)
                                    //        {
                                    //            return Json(returnError("房号[" + host.RoomNumber + "]的取电未打开，不可控制"), JsonRequestBehavior.AllowGet);
                                    //        }
                                    //        break;
                                    //    }
                                    //}
                                    //var wxMenu = RoomTypeWXMenusManager.LoadAll(host.RoomType.ID).Where(r => r.Code == "changjing" && r.ActiveIndicator == true).FirstOrDefault();
                                    //if (wxMenu == null)
                                    //{
                                    //    return Json(returnError("房号[" + host.RoomNumber + "]的场景不能控制"), JsonRequestBehavior.AllowGet);
                                    //}
                                    //else if (wxMenu.TakePower)
                                    //{
                                    //    var takePowerModal = HostModalManager.Load(host.ID, DeviceType.ServiceInfo).Where(r => r.Modal.ModalAddress == "004000001").FirstOrDefault();
                                    //    if (takePowerModal.Status != 1)
                                    //    {
                                    //        return Json(returnError("房号[" + host.RoomNumber + "]的取电未打开，不可控制"), JsonRequestBehavior.AllowGet);
                                    //    }
                                    //}
                                    if (!CheckGetPower(host))
                                    {
                                        return Json(new { IsSuccess = false, Result = "非取电状态，不可控制！" }, JsonRequestBehavior.AllowGet);
                                    }
                                    var scene = RoomTypeSceneManager.Get(int.Parse(modalAddress));
                                    if (scene == null)
                                    {
                                        return Json(returnError("房号[" + host.RoomNumber + "]无效的场景,ID=" + modalAddress), JsonRequestBehavior.AllowGet);
                                    }
                                    LightControlManager.ApplyScene(host, scene);
                                    SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, "若琪", host.SysHotel.ID);
                                    break;
                                default:
                                    var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);
                                    if (hostModal == null)
                                    {
                                        return Json(returnError("房号[" + host.RoomNumber + "]无效的设备,ModalAddress=" + modalAddress), JsonRequestBehavior.AllowGet);
                                    }
                                    int status, brightness, temperature, fanSpeed, mode, valve;
                                    status = 1;
                                    brightness = hostModal.Brightness;
                                    temperature = hostModal.SettingTemp;
                                    fanSpeed = hostModal.FanSpeed;
                                    mode = hostModal.Mode;
                                    valve = hostModal.Valve;
                                    switch (name)
                                    {
                                        case "Switch.On"://打开，亮度100
                                        case "Brightness.SetMax":
                                            brightness = 100;
                                            break;
                                        case "Switch.Off"://关闭，亮度0
                                            status = 2;
                                            brightness = 0;
                                            break;
                                        case "Brightness.SetMin"://最小亮度
                                            brightness = 1;
                                            break;
                                        case "Brightness.Set"://设定亮度
                                            brightness = Convert.ToInt16(request.payload.value);
                                            break;
                                        case "Brightness.Adjust"://调节亮度
                                            if (request.payload.delta == -1)
                                            {
                                                brightness++;//下调
                                            }
                                            else
                                            {
                                                brightness--;//上调
                                            }
                                            break;
                                        case "MotionSwitch.Off"://窗帘停下
                                            status = 6;
                                            break;
                                        case "Temperature.Set"://设定温度
                                            int value = Convert.ToInt16(request.payload.value);
                                            if (15 < value && value < 33)
                                            {
                                                temperature = value;
                                            }
                                            break;
                                        case "Temperature.SetMax"://设定最大温度
                                            temperature = 32;
                                            break;
                                        case "Temperature.SetMin"://设定最小温度
                                            temperature = 16;
                                            break;
                                        case "Temperature.Adjust"://调节温度
                                            if (request.payload.delta == -1)
                                            {
                                                temperature = 15;//下调
                                            }
                                            else
                                            {
                                                temperature = 33;//上调
                                            }
                                            break;
                                        case "FanSpeed.Set"://自动风速
                                            fanSpeed = 0;
                                            break;
                                        case "FanSpeed.SetMin"://低风速
                                            fanSpeed = 1;
                                            break;
                                        case "FanSpeed.Adjust"://中风速
                                            fanSpeed = 2;
                                            break;
                                        case "FanSpeed.SetMax"://高风速
                                            fanSpeed = 3;
                                            break;
                                        case "Mode.Auto"://自动模式
                                            mode = 0;
                                            break;
                                        case "Mode.Cool"://制冷模式
                                            mode = 1;
                                            break;
                                        case "Mode.Heat"://制热模式
                                            mode = 2;
                                            break;
                                        case "Mode.Fan"://送风模式
                                            mode = 3;
                                            break;
                                    }
                                    HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                                    string action = "打开";
                                    if (status == 2)
                                    {
                                        action = "关闭";
                                    }
                                    else if (status == 6)
                                    {
                                        action = "暂停";
                                    }
                                    string detail = string.Format("{0}客房{1}{2}({3})", action, host.RoomNumber, hostModal.Modal.Name, modalAddress);
                                    SaveSystemLog(AuthorityID, "设备控制", detail, true, "若琪", host.SysHotel.ID);
                                    break;
                            }
                            //回应状态
                            Domain.Rokid.Control.ControlResponse con = new Domain.Rokid.Control.ControlResponse
                            {
                                header = new Domain.Rokid.Control.Header
                                {
                                    messageId = request.header.messageId,
                                    @namespace = "Rokid",
                                    name = "Response",
                                    payloadVersion = "v1"
                                },
                                endpoint = new Domain.Rokid.Control.Endpoint
                                {
                                    endpointId = endpointId,
                                    states = new List<Domain.Rokid.Control.States>()
                                },
                                payload = new Domain.Rokid.Control.Payload { }
                            };
                            return Json(con, JsonRequestBehavior.AllowGet);
                        }
                }
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("RequestData:{0},error:{1},来自：{2}", reqData, ex.ToString(), GetClientIP()));
                return Json(returnError(ex.Message), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 给若琪返回错误信息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private Domain.Rokid.Error.ErrorResponse returnError(string message)
        {
            Domain.Rokid.Error.ErrorResponse err = new Domain.Rokid.Error.ErrorResponse
            {
                header = new Domain.Rokid.Error.Header
                {
                    messageId = "789-123",
                    @namespace = "Rokid",
                    name = "ErrorResponse",
                    payloadVersion = "v1"
                },
                payload = new Domain.Rokid.Error.Payload
                {
                    name = "E_DRIVER_ERROR",
                    message = message
                }
            };
            return err;
        }
        #endregion

        #region 提供给PDU平台调用
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRCUInfoForPDU(string jsonData)
        {
            try
            {
                Interlocked.Increment(ref WebAPI_TongJi.GetRCUInfoForPDU);
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                Host host1 = CheckRoomNumber(jData["code"].ToString(), jData["creatDate"].ToString(), ref msg, ref hotelID, "");
                if (host1 == null && hotelID == 0)
                {
                    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                }
                string roomNumber = "";
                if (jData["roomNumber"] != null)
                {
                    roomNumber = jData["roomNumber"].ToString();
                }
                IList<Host> hosts = HostManager.LoadAll(hotelID, roomNumber).OrderBy(r => r.RoomNumber).ToList();
                IList<object> list = new List<object>();
                foreach (Host host in hosts)
                {
                    IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.ActiveIndicator).ToList();
                    IList<object> lstModals = new List<object>();
                    foreach (HostModal modal in hostModals)
                    {
                        lstModals.Add(new
                        {
                            Type = Common.Tools.GetDescription(modal.Modal.Type), //回路类型
                            ModalAddress = modal.Modal.ModalAddress, //回路地址
                            Name = modal.Modal.Name//回路名称
                        });
                    }
                    list.Add(new
                    {
                        Code = host.SysHotel.Code,//酒店编码
                        HotelName = host.SysHotel.Name,
                        HostNumber = host.HostNumber,
                        RoomNumber = host.RoomNumber,//房号
                        Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC),//是否在线
                        MAC = host.MAC,//MAC
                        GroupName = host.Group.Name,
                        RoomTypeName = host.RoomType.Name,//房态
                        //IPType = host.IPType,//IP类型：1自动，2手动
                        //IP = host.IP,//IP
                        //Port = host.Port,//端口
                        LanIP = host.LanIP,//局域网IP
                        LanPort = host.LanPort,//局域网端口
                        SubnetMask = host.SubnetMask,//子网掩码
                        Gateway = host.Gateway,//网关
                        DNS = host.DNS,//DNS
                        Version = host.Version,//固件版本
                        ConfigVersion = host.ConfigVersion,//配置版本
                        Model = host.Model,//Model
                        Launcher = host.LauncherVersion,//Launcher版本
                        XiaoDuCUID = host.XiaoDuCUID,//小度cuid
                        TianMaoCUID = host.TianMaoCUID,//天猫精灵cuid
                        TCLCUID = host.TCLCUID,//tcl cuid
                        Modals = lstModals//回路列表（类型、地址、名称）
                    });
                }
                //return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
                object result = new { IsSuccess = true, Result = list };
                return new ContentResult
                {
                    Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(result),
                    ContentType = "application/json"
                };
            }
            catch (Exception ex)
            {
                logger.Error("获取主机状态失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        /// <summary>
        /// 通知后台有新的升级包
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult PublishUpgradePackage(string jsonData)
        {
            return Json(new { IsSuccess = true, Result = "接口调整中" }, JsonRequestBehavior.AllowGet);
            /*try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                int roomTypeID = Convert.ToInt16(jData["roomTypeID"].ToString());//房型ID
                int type = Convert.ToInt16(jData["type"].ToString());//1：固件升级bin或hex，2：配置升级dat
                string version = jData["version"].ToString();//版本号

                logger.Error("收到通知后台有新的升级包：" + jsonData);

                return Json(new { IsSuccess = true, Result = "通知成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("通知后台有新的升级包失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }*/
        }
        /// <summary>
        /// 上报房型回路：每次上报一个房型
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult UploadRoomTypeModal()
        {
            //return Json(new { IsSuccess = true, Result = "接口调整中" }, JsonRequestBehavior.AllowGet);
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            if (string.IsNullOrEmpty(reqData))
            {
                return Json(new { IsSuccess = false, Result = "传递参数不能为空" }, JsonRequestBehavior.AllowGet);
            }
            logger.Error("收到上报房型回路数据：");// + reqData);
            try
            {
                List<RoomTypeModal> lstRTModels = JsonConvert.DeserializeObject<List<RoomTypeModal>>(reqData);
                if (lstRTModels == null || lstRTModels.Count == 0)
                {
                    return Json(new { IsSuccess = false, Result = "上报回路记录为空" }, JsonRequestBehavior.AllowGet);
                }
                /*int roomTypeID = lstRTModels[0].RoomType.ID;
                RoomType rt = RoomTypeManager.Get(roomTypeID);//获取当前房型
                if (rt == null)
                {
                    return Json(new { IsSuccess = false, Result = "未找到对应的房型，ID=" + roomTypeID }, JsonRequestBehavior.AllowGet);
                }
                RoomTypeModalManager.DeleteByRoomTypeID(rt.ID, 1);//先删除该房型下所有宝易上传的回路
                foreach (RoomTypeModal rtModal in lstRTModels)
                {
                    var roomTypeModal = new RoomTypeModal();
                    roomTypeModal.RoomType = rt;//房型对象（提供房型ID即可）
                    roomTypeModal.ModalAddress = rtModal.ModalAddress;//回路地址
                    roomTypeModal.Name = rtModal.Name;//回路名称
                    roomTypeModal.Type = rtModal.Type;//回路类型
                    roomTypeModal.Outlet = rtModal.Outlet;//输出口
                    //roomTypeModal.EnglishName = rtModal.EnglishName;//英文名称
                    //roomTypeModal.TWName = rtModal.TWName;//繁体名称
                    roomTypeModal.Power = rtModal.Power;//功率
                    roomTypeModal.Default = false;
                    roomTypeModal.Subtype = null;
                    roomTypeModal.Sort = 1;
                    roomTypeModal.Color = "";
                    roomTypeModal.ActiveIndicator = true;//新增时默认显示
                    roomTypeModal.WXActiveIndicator = true;//只要显示，微信默认允许控制
                    roomTypeModal.SourceType = 1;//宝易上传
                    RoomTypeModalManager.Save(roomTypeModal);//新增房型下单个回路
                }*/
                return Json(new { IsSuccess = true, Result = "上报成功，总回路数：" + lstRTModels.Count }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("上报房型回路失败。参数：" + reqData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }


        public ActionResult GetAllKTMission()
        {
            List<KongTiaoTimer> kl = HostManager.GetInitializeKTMission();
            return Json(kl, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AirConditionTimer(string jsonData)
        {
            logger.Error("shou dao le shu ju: " + jsonData);
            if (!string.IsNullOrEmpty(jsonData))
            {
                var jf = Newtonsoft.Json.JsonConvert.DeserializeObject<MissionRequestData>(jsonData);
                HostManager.AirConditionTimer_Controller(jf.KT.HotelID, jf.KT.HotelCode, jf.KT.CreateDate, jf.KT.HostID, jf.KT.RoomNo, jf.KT);
            }
            return null;
        }
        /// <summary>
        /// 这个接口可以实现定时任务
        /// 调用任务管理器
        /// 传入以下json 或者 formdat：a
        /// %{"url"=>url,"mission_key" => mission_key,"mission_name"=>mission_name,"cron_exp"=>cron_exp}
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult AirConditionTimerPost()
        {

            byte[] byts = new byte[Request.InputStream.Length];
            Request.InputStream.Read(byts, 0, byts.Length);
            string jsonData = System.Text.Encoding.UTF8.GetString(byts);
            //req = Server.UrlDecode(req);
            logger.Error("shou dao le shu ju: " + jsonData);
            if (!string.IsNullOrEmpty(jsonData))
            {
                var jf = Newtonsoft.Json.JsonConvert.DeserializeObject<MissionRequestData>(jsonData);
                HostManager.AirConditionTimer_Controller(jf.KT.HotelID, jf.KT.HotelCode, jf.KT.CreateDate, jf.KT.HostID, jf.KT.RoomNo, jf.KT);
            }
            return null;
        }

        public ActionResult jiekou_test()
        {
            HttpContext.Cache.Remove("auuuuhfjkdshee");
            HostManager.LoggerTest();//2：出租，4：待租，8：退房，16：空房

            return Json(new { rescode = "200", resDesc = "操作成功" }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 获取节能模式数据
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetECOList()
        {
            var ll = HostManager.Get_ECOList();
            return Json(ll);
        }
        /// <summary>
        /// 节能模式接口
        /// 
        /// 任务管理 系统 在规定时间段内， 每隔一段时间会向这边发送一条指令
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult StartAll_ECO_Mission()
        {
            string hotelid = Request.Form["hotelid"];
            string key = Request.Form["key"];
            HostManager.ECO_Execute(hotelid);
            return Json(new { status = "sucess" });
        }

        public static readonly string AirReport_Address = ConfigurationManager.AppSettings["baojing_airreport_address"];
        public static readonly string baojing_airreport_key = ConfigurationManager.AppSettings["baojing_airreport_key"];

        [HttpPost()]
        public ActionResult GetAirDetectListPost()
        {
            //Task.Factory.StartNew(() =>
            //    {
            //    });

            try
            {
                List<KongQi> listdata = GetPrepareData();

                var QQQ = listdata.GroupBy(A => new { A.HotelID, A.HotelCode, A.RoomNumber, A.CreatDate });

                foreach (var itemKey in QQQ)
                {
                    var item = itemKey.Key;
                    string roomNumber = item.RoomNumber;
                    string code = item.HotelCode;
                    string createDate = item.CreatDate;
                    DateTime dts = DateTime.Parse(createDate);
                    string cd = dts.ToString("yyyy-MM-dd");

                    Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
                    if (host == null)
                    {
                        logger.Error("host not exists hotelcode: " + code + " createDate: " + cd + " roomnumber: " + roomNumber);
                        continue;
                        //return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
                    }
                    if (host != null)
                    {
                        var hostModals = HostModalManager.Load(host.ID, DeviceType.AirDetect).Where(r => r.Modal.WXActiveIndicator);

                        TimeSpan ts = DateTime.Now.ToLocalTime() - new DateTime(1970, 1, 1, 8, 0, 0, 0, DateTimeKind.Utc);
                        string current_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();

                        KongQiReport re = new KongQiReport();
                        re.hotel_code = code;
                        re.room_no = roomNumber;
                        re.time = current_timestamp;

                        string md5key = Tools.MD5Encrypt(baojing_airreport_key);
                        //hotel_code=酒店编码&time=时间戳&key=密钥
                        string sss = string.Format("hotel_code={0}&time={1}&key={2}", code, current_timestamp, md5key);

                        //logger.Error("sss is: " + sss);
                        string sign = Tools.MD5Encrypt(sss).ToLower();
                        re.sign = sign;
                        foreach (HostModal modal in hostModals)
                        {
                            //string Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName);
                            string ModalAddress = modal.Modal.ModalAddress;

                            string status = modal.Brightness.ToString();
                            string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + ModalAddress;
                            var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                            if (obj != null)
                            {
                                HostModal_Cache hhh = obj as HostModal_Cache;
                                status = hhh.Brightness.ToString();
                            }

                            switch (ModalAddress)
                            {
                                case "009000001"://CO2浓度        ppm
                                    re.co2 = status;
                                    break;
                                case "009000002"://甲醛浓度        ug/m3     实际显示单位为mg/M3
                                    re.methanal = status;
                                    break;
                                case "009000003"://TVOC浓度       ug/m3     实际显示单位为mg/M3
                                    re.tvoc = status;
                                    break;
                                case "009000004"://PM2.5浓度      ug/m3
                                    re.pm25 = status;
                                    break;
                                case "009000005"://PM10浓度      ug/m3
                                    re.pm10 = status;
                                    break;
                                case "009000006"://温度           度
                                    re.temperature = status;
                                    break;
                                case "009000007"://湿度           %RH
                                    re.humidness = status;
                                    break;

                                default:
                                    break;
                            }

                        }

                        //list{Name（名称)，ModalAddress（回路 地址），Brightness, Status（对应值）}
                        var client1 = new RestClient(AirReport_Address);
                        var request1 = new RestRequest("/rcu/v1/air", Method.POST);
                        request1.RequestFormat = DataFormat.Json;

                        //string json = Newtonsoft.Json.JsonConvert.SerializeObject(re);
                        //logger.Error("空气质量送了数据：" + AirReport_Address+" data: "+json);

                        request1.AddJsonBody(re);

                        client1.ExecuteAsync(request1, (response) =>
                        {
                            string result = response.Content;
                            //logger.Error("空气质量返回了:"+result);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message + ex.StackTrace);
                //return Json(new { IsSuccess = false, Result = ex.Message }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { IsSuccess = true, Result = "sucess" }, JsonRequestBehavior.AllowGet);

        }

        [HttpPost()]
        public ActionResult GetAirDetectPrepareData()
        {
            List<KongQi> list = GetPrepareData();
            return Json(list);
        }

        private List<KongQi> GetPrepareData()
        {
            string Key = "AirDetectPrepareData";
            List<KongQi> list = new List<KongQi>();
            bool re = CSRedisCacheHelper.Contains(Key);
            if (re)
            {
                list = CSRedisCacheHelper.Get<List<KongQi>>(Key);
            }
            else
            {
                var ddd = SysHotelManager.GetNeedData();
                CSRedisCacheHelper.Set(Key, ddd);
                list = ddd;
            }
            return list;
        }
        /// <summary>
        /// ECO重置 接口
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult ECO_Reset()
        {
            HostManager.Zero_Refresh();
            return Json(new { });
        }


        [HttpPost()]
        public ActionResult webChatLoadHostByRoomType()
        {
            string a = Request.Form["hotelid"].ToString();
            string b = Request.Form["roomTypeID"].ToString();


            int hotelid, roomTypeID = 0;
            int.TryParse(a, out hotelid);
            int.TryParse(b, out roomTypeID);
            object ooobj = Request.Form["roomNumber"];
            IList<object> lists = null;
            if (ooobj != null)
            {
                string c = ooobj.ToString();
                //根据房型获取所有主机ID
                lists = HostManager.LoadHostByRoomTypeChengZiHao(hotelid, roomTypeID, c);
            }
            else
            {
                lists = HostManager.LoadHostByRoomType(hotelid, roomTypeID);
            }

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


            foreach (var list in lists)
            {
                object[] ooo = (object[])list;
                result.Add(new
                {
                    ID = ooo[0],
                    RoomNumber = ooo[2],
                    Status = CSRedisCacheHelper.Contains(ooo[1].ToString(), ooo[3].ToString()),
                    MAC = ooo[3],
                    Model = ooo[5],
                    Launcher = ooo[6],
                    Version = ooo[7],
                    ConfigVersion = ooo[8],
                    UpgradeStatus = ooo[10] == null ? "" : ooo[9],
                    UpgradeTime = ooo[10] == null ? "" : Convert.ToDateTime(ooo[10]).ToString("yyyy-MM-dd HH:mm:ss"),
                    LanIP = ooo[11],
                    LanPort = ooo[12],
                    TypeNumber = ooo[13]
                });
            }


            var LLL = GetShengJiWenJianFileName(hotelid, roomTypeID);
            return Json(new { IsSuccess = true, HostData = result, updateFile = LLL });

        }

        private static string tool_sync_url_base_url = System.Configuration.ConfigurationManager.AppSettings["tool_sync_url_base_url"];
        private List<Dictionary<string, string>> GetShengJiWenJianFileName(int hotelid, int roomTypeID)
        {
            var client1 = new RestClient(tool_sync_url_base_url);
            var request1 = new RestRequest("/Upgrade/GetFileName", Method.POST);

            //注意方法是POST
            //两个参数名字必须是 topic 和payload ，区分大小写的
            request1.AddParameter("hotel_id", hotelid);
            request1.AddParameter("room_type_id", roomTypeID);

            //[
            //    {
            //        "HOTEL_OLD_ID": 98,
            //        "ROOM_TYPE_OLD_ID": 4356,
            //        "CONFIG_BIN": "15_Config-1085-宝来威体验厅-研发部-250109154719.dat",
            //        "App_Cfg_For_L2": "",
            //        "App_Cfg_For_L4": "C1F_A_L4_40_250109_NM.hex",
            //        "Hex_Code_For_L2": "",
            //        "Hex_Code_For_L4": "",
            //        "APPTYPE": "App_Cfg",
            //        "Cfg_Type": "CFG_TYPE_BLV_STUDIO",
            //        "LUNCHER_HEX": ""
            //    }
            //]

            var response = client1.Execute(request1);
            string sss = response.Content;
            var fileNames = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(sss);
            return fileNames;
        }

        [HttpPost()]
        public ActionResult GetUpdatedFile()
        {
            string strroomTypeID = Request.Form["roomTypeID"].ToString();
            int a = 0;
            int.TryParse(strroomTypeID, out a);
            HostUpdateController h = new HostUpdateController();
            return h.GetUpdatedFile(a);
        }


        private static string get_update_url = System.Configuration.ConfigurationManager.AppSettings["get_update_url"];


        #region 微信升级
        /// <summary>
        ///upgradefileName 后缀有要：求 
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult WebChatUpgrade()
        {
            try
            {
                string b = Request.Form["roomTypeID"].ToString();
                if (string.IsNullOrEmpty(b))
                {
                    return Json(new { IsSuccess = false, Data = "roomTypeID不能为空" });
                }

                string host_list_str = Request.Form["hostid_lists"].ToString();
                string fileName = Request.Form["upgradefileName"].ToString();

                if (string.IsNullOrEmpty(host_list_str))
                {
                    return Json(new { IsSuccess = false, Data = "hostid_lists不能为空" });
                }
                ReallyUpgrade(b, host_list_str, fileName);
                return Json(new { IsSuccess = true, Data = "正在升级，请等待……" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Data = ex.Message });
            }
        }

        [HttpPost()]
        public ActionResult WebChatUpgradeTimer()
        {
            try
            {
                //1412
                //固件:BLV-V9 || Launcher_C1F_V04 || C1F_A_L4_31_240723_NM.bin
                //100331-YHF_T
                //YHF_T

                //2438
                //研发测试房型_1
                //固件:BLV-C5 || Launcher_C1F_V04 || C1F_A_L4_41_250605_NM.bin
                string roomTypeID = "1412";
                string host_list_str = "[24540]";
                //string fileName = "C1F_A_L4_41_250704_NM.bin";
                string fileName = "C1F_A_L4_31_240723_NM.bin";

                ReallyUpgrade(roomTypeID, host_list_str, fileName);
                return Json(new { IsSuccess = true, Data = "正在升级，请等待……" });
            }
            catch (Exception ex)
            {
                logger.Error("定时升级出错:" + ex.Message);
                return Json(new { IsSuccess = false, Data = ex.Message });
            }
        }

        private void ReallyUpgrade(string 房型ID, string host_list_str, string fileName)
        {
            int roomTypeID = 0;
            int.TryParse(房型ID, out roomTypeID);

            logger.Error("微信端开始升级: " + fileName + " " + roomTypeID + " host_list: " + host_list_str);
            var host_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(host_list_str);

            //让服务器获取升级文件
            HostUpdateController.GetUpdateFileByRoomTypeID(roomTypeID);

            string lll = JsonConvert.SerializeObject(host_list);
            HostUpdateController hh = new HostUpdateController();
            logger.Error("开始升级: " + fileName + " host_list: " + lll);
            //升级
            hh.ShengJI_NEW(host_list, fileName, HostManager, roomTypeID);
        }

        [HttpPost()]
        public ActionResult QueryUpdateHostProgressBar(string HostIDList)
        {
            try
            {
                var Q = new List<BarData>();
                List<int> LLL = JsonConvert.DeserializeObject<List<int>>(HostIDList);
                foreach (int item in LLL)
                {
                    string Key = CacheKey.UPGradeProgressBar + "_" + item.ToString();
                    var DDD = CSRedisCacheHelper.Get<BarData>(Key);
                    if (DDD != null)
                    {
                        Q.Add(DDD);
                    }
                }
                return Json(new { IsSuccess = true, Response = Q });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("ReleaseUpgradeFailedBecause") + ex.Message });
            }
        }
        [HttpPost()]
        public ActionResult QueryUpdateHostStatus(int HotelID, int roomTypeID)
        {
            try
            {
                var lists = HostManager.LoadHostByRoomType(HotelID, roomTypeID);//ID,HostNumber,RoomNumber,MAC,RoomTypeID,Model,LauncherVersion,Version,ConfigVersion,UpgradeStatus,UpgradeTime
                IList<object> result = new List<object>();
                foreach (var list in lists)
                {
                    result.Add(new
                    {
                        ID = ((object[])list)[0],
                        Status = CSRedisCacheHelper.Contains(((object[])list)[1].ToString(), ((object[])list)[3].ToString()),
                        RoomNumber = ((object[])list)[2],
                        MAC = ((object[])list)[3],
                        //RoomType = host.RoomType.Name,
                        Model = ((object[])list)[5],
                        Launcher = ((object[])list)[6],
                        Version = ((object[])list)[7],
                        ConfigVersion = ((object[])list)[8],
                        UpgradeStatus = ((object[])list)[10] == null ? "" : ((object[])list)[9],
                        UpgradeTime = ((object[])list)[10] == null ? "" : Convert.ToDateTime(((object[])list)[10]).ToString("yyyy-MM-dd HH:mm:ss")
                    });
                }
                var QQQ = result.ToList();
                //QQQ.Sort();
                return Json(new { total = result.Count, rows = QQQ });

                //var statusList = HostUpdateStatusManager.LoadAll().Where(r => r.HostUpdate.ID == hostUpdateID).Select(r => new { id = r.ID, hostID = r.Host.ID, status = r.Status });
                //return Json(new { IsSuccess = true, Data = statusList });
            }
            catch (Exception ex)
            {
                logger.Error(HttpContext.InnerLanguage("ReleaseUpgradeFails"), ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("ReleaseUpgradeFailedBecause") + ex.Message });
            }
        }


        [HttpPost()]
        public ActionResult Upgrade_V2(string roomtype_id, string host_list_str, string fileName)
        {
            int roomTypeID = 0;
            int.TryParse(roomtype_id, out roomTypeID);

            logger.Error("微信端开始升级: " + fileName + " " + roomTypeID + " host_list: " + host_list_str);
            var host_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(host_list_str);

            //不用获取，直接在本地使用
            string lll = JsonConvert.SerializeObject(host_list);
            HostUpdateController hh = new HostUpdateController();
            logger.Error("开始升级: " + fileName + " host_list: " + lll);
            //升级
            return hh.新改造(host_list, fileName, roomTypeID, HostManager);
        }
        #endregion


        #region 监控
        [HttpPost()]
        public ActionResult Monitor_Host_Handle()
        {
            string Key = CacheKey.Key;
            string Data = Request.Form["data"].ToString();
            string AddOrRemove = Request.Form["add_remove"].ToString();

            List<Monitor_Host> lll = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Monitor_Host>>(Data);

            lll.RemoveAll(A => string.IsNullOrEmpty(A.Key_HostNumber));
            var qqq = CSRedisCacheHelper.ForeverGet<List<Monitor_Host>>(Key);

            if (qqq == null)
            {
                var list = new List<Monitor_Host>();
                CSRedisCacheHelper.Forever<List<Monitor_Host>>(Key, list);

            }

            qqq = CSRedisCacheHelper.ForeverGet<List<Monitor_Host>>(Key);

            string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (AddOrRemove.Equals("add"))
            {
                foreach (var item in lll)
                {
                    item.CreateDateTime = ti;
                    //bool bf = qqq.Any(A => A.HotelCode.Equals(item.HotelCode) && item.RoomNumber.Equals(A.RoomNumber));
                    bool bf = qqq.Any(A =>
                        {
                            string AAA = A.HotelCode;
                            string BBB = A.Key_HostNumber;
                            if (!string.IsNullOrEmpty(AAA) && !string.IsNullOrEmpty(BBB))
                            {
                                return AAA.Equals(item.HotelCode) && BBB.Equals(item.Key_HostNumber);
                            }
                            return false;
                        });
                    if (bf == false)
                    {
                        qqq.Add(item);
                    }
                    else
                    {
                        qqq.RemoveAll(A => A.HotelCode.Equals(item.HotelCode) && A.Key_HostNumber.Equals(item.Key_HostNumber));
                        qqq.Add(item);
                    }
                }
                CSRedisCacheHelper.Forever<List<Monitor_Host>>(Key, qqq);
            }
            else if (AddOrRemove.Equals("remove"))
            {
                foreach (var item in lll)
                {
                    string item_h = item.HotelCode;
                    string item_r = item.RoomNumber;
                    string hostnumber = item.Key_HostNumber;

                    if (!string.IsNullOrEmpty(item_h) && !string.IsNullOrEmpty(item_r) && !string.IsNullOrEmpty(hostnumber))
                    {
                        qqq.RemoveAll(A => !string.IsNullOrEmpty(A.HotelCode) && A.HotelCode.Equals(item_h) && !string.IsNullOrEmpty(A.Key_HostNumber) && A.Key_HostNumber.Equals(hostnumber));
                    }
                }
                CSRedisCacheHelper.Forever<List<Monitor_Host>>(Key, qqq);
            }

            return Json(new { IsSuccess = true, Data = "" });
        }

        [HttpPost()]
        public ActionResult GetAll_MonitorHost()
        {
            string Key = CacheKey.Key;
            var qqq = CSRedisCacheHelper.ForeverGet<List<Monitor_Host>>(Key);
            if (qqq == null)
            {
                qqq = new List<Monitor_Host>();
            }
            qqq = qqq.OrderBy(A => A.HotelCode).ToList();
            return Json(qqq);
        }




        [HttpPost()]
        public ActionResult IOT_Monitor_Host_Handle()
        {
            string Key = CacheKey.IOTKey;
            string Data = Request.Form["data"].ToString();
            string AddOrRemove = Request.Form["add_remove"].ToString();

            List<IOT_Monitor_Host> lll = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IOT_Monitor_Host>>(Data);

            var qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);

            if (qqq == null)
            {
                var list = new List<IOT_Monitor_Host>();
                CSRedisCacheHelper.Forever<List<IOT_Monitor_Host>>(Key, list);
            }

            qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);

            string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (AddOrRemove.Equals("add"))
            {
                foreach (var item in lll)
                {
                    item.CreateDateTime = ti;
                    bool bf = qqq.Any(A => A.HotelCode.Equals(item.HotelCode) && item.RoomNumber.Equals(A.RoomNumber));
                    if (bf == false)
                    {
                        qqq.Add(item);
                    }
                    else
                    {
                        qqq.RemoveAll(A => A.HotelCode.Equals(item.HotelCode) && A.RoomNumber.Equals(item.RoomNumber));
                        qqq.Add(item);
                    }
                }
                CSRedisCacheHelper.Forever<List<IOT_Monitor_Host>>(Key, qqq);
            }
            else if (AddOrRemove.Equals("remove"))
            {
                foreach (var item in lll)
                {
                    string item_h = item.HotelCode;
                    string item_r = item.RoomNumber;

                    qqq.RemoveAll(A => A.HotelCode.Equals(item_h) && A.RoomNumber.Equals(item_r));
                }
                CSRedisCacheHelper.Forever<List<IOT_Monitor_Host>>(Key, qqq);
            }

            return Json(new { IsSuccess = true, Data = "" });
        }

        [HttpPost()]
        public ActionResult IOT_GetAll_MonitorHost()
        {
            string Key = CacheKey.IOTKey;
            var qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);
            if (qqq == null)
            {
                qqq = new List<IOT_Monitor_Host>();
            }
            qqq = qqq.OrderBy(A => A.HotelCode).ToList();
            return Json(qqq);
        }

        #endregion
        [HttpPost()]
        public ActionResult RedisTest()
        {
            string Data = Request.Form["data"].ToString();
            string AddOrRemove = Request.Form["add_remove"].ToString();
            CSRedisCacheHelper.Forever<string>(Data, AirReport_Address);
            return Json("hello");
        }

        [HttpPost()]
        public bool CheckGetTakePower()
        {
            int hostid = 0;
            int.TryParse(Request.Form["hostid"].ToString(), out hostid);
            //string hotel_code = "";
            //string createDate = "";
            //string roomNumber = "";

            //hotel_code= Request.Form["code"].ToString();
            //roomNumber= Request.Form["roomNumber"].ToString();
            //createDate= Request.Form["createDate"].ToString();
            //Host host = CheckRoomNumber(hotel_code, createDate, ref msg, ref hotelID, roomNumber);
            //if (host == null)
            //{
            //    return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
            //}

            //DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //Dictionary<string, string> dic = new Dictionary<string, string>();
            HostModal hostModal = HostModalManager.LoadByHostID(hostid).Where(r => r.Modal.ActiveIndicator == true && r.Modal.ModalAddress == "004000001").FirstOrDefault();
            if (hostModal != null && hostModal.Status != 1)
            {
                //DateTime dt = hostModal.UpdateTime.Value;
                //dic.Add("HostID", hostid.ToString());
                //dic.Add("TakeCard_Status", "true");
                //dic.Add("LastDateTime", dt.ToString("yyyy-MM-dd HH:mm:ss"));
                return true;
            }
            else
            {
                return false;
            }
            //return Json(new { IsSuccess = false, Result = dic }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost()]
        public ActionResult SetRoomCard()
        {
            return null;
        }
        public static string FCSLoginUrl = ConfigurationManager.AppSettings["FCSLoginUrl"];
        public static string FCSLoginUserName = ConfigurationManager.AppSettings["FCSLoginUserName"];
        public static string FCSLoginPassWord = ConfigurationManager.AppSettings["FCSLoginPassWord"];

        #region FCS数据推送
        [HttpPost()]
        public ActionResult GetFCSTokenPost()
        {
            try
            {
                var list = SysHotelManager.get_fcs_hotel();
                foreach (var item in list)
                {
                    var code = item.Code;
                    var client1 = new RestClient(FCSLoginUrl);
                    var request1 = new RestRequest("/api/security/authenticate", Method.POST);

                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    User us = new User();
                    us.username = item.FCSLoginUserName;
                    us.password = item.FCSLoginPassWord;
                    us.oauth_id = 1;
                    request1.AddJsonBody(us);

                    var QQQ = client1.Execute(request1);
                    string ddd = QQQ.Content;
                    var FFFA = Newtonsoft.Json.JsonConvert.DeserializeObject<FCS_ReturnInfo>(ddd);

                    string TokenKey = CacheKey.FCSToken + "_" + code;
                    CSRedisCacheHelper.Set_Partition(TokenKey, FFFA, 1);
                }
            }
            catch (Exception)
            {

            }
            return null;
        }



        /// <summary>
        /// 每隔30分钟去查询一下设备是否在线和离线
        /// 
        /// 查询的时候根据locationUUID
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetFCS_RCU_Status()
        {
            try
            {
                var QQQ = SysHotelManager.LoadFCS_PushData();
                foreach (var item in QQQ)
                {
                    var PPP = HostManager.LoadAll().Where(A => A.IsDeleted == false && !string.IsNullOrEmpty(A.FCS_locationUUID)).ToList();
                    foreach (Host itemT in PPP)
                    {
                        //根据酒店hotelcode
                        string code = itemT.SysHotel.Code;
                        string roomno = itemT.RoomNumber;
                        string locationUUID = itemT.FCS_locationUUID;
                        string hostNumber = itemT.HostNumber;
                        string MAC = itemT.MAC;


                        string PropertyUUID = itemT.SysHotel.FCS_PropertyID;

                        string FCS_RCU_Device_Offline = itemT.SysHotel.FCS_RCU_Device_Offline;

                        string FCSLoginUrl = itemT.SysHotel.FCSLoginUrl;
                        string FCSLoginUserName = itemT.SysHotel.FCSLoginUserName;
                        string FCSLoginPassWord = itemT.SysHotel.FCSLoginPassWord;

                        string FCS_Carbon_UUID = itemT.SysHotel.FCS_Carbon_UUID;
                        string FCS_SOS_UUID = itemT.SysHotel.FCS_SOS_UUID;
                        string FCS_Clean_UUID = itemT.SysHotel.FCS_Clean_UUID;

                        string FCS_MenCi_Open = itemT.SysHotel.FCS_MenCi_Open;
                        string FCS_MenCi_Close = itemT.SysHotel.FCS_MenCi_Close;

                        string FCS_RCU_Online = itemT.SysHotel.FCS_RCU_Online;
                        string FCS_RCU_Offline = itemT.SysHotel.FCS_RCU_Offline;


                        var aaa = Common.CSRedisCacheHelper.Contains(Convert.ToString(hostNumber), MAC);
                        string KKK = "GetFCS_RCU_Status_" + hostNumber + "_" + MAC;
                        var Q = CSRedisCacheHelper.Get_Partition<string>(KKK);
                        //如果在线
                        if (aaa)
                        {
                            if (!string.IsNullOrEmpty(Q))
                            {
                                if (Q.Equals("offline"))
                                {

                                    RR.FCS_PushData(FCS_RCU_Online, itemT.FCS_locationUUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, code, roomno);
                                }
                            }
                            else
                            {
                                CSRedisCacheHelper.Set_Partition(KKK, "online");
                                RR.FCS_PushData(FCS_RCU_Online, itemT.FCS_locationUUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, code, roomno);
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(Q))
                            {
                                if (Q.Equals("offline"))
                                {
                                    RR.FCS_PushData(FCS_RCU_Offline, itemT.FCS_locationUUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, code, roomno);
                                }
                            }
                            else
                            {
                                CSRedisCacheHelper.Set_Partition(KKK, "offline");
                                RR.FCS_PushData(FCS_RCU_Offline, itemT.FCS_locationUUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, code, roomno);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
            return null;
        }



        /// <summary>
        /// 获取 FCS 清理触发的 订单表
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetFCSClean_OrderList()
        {
            try
            {

                //string Key = CacheKey.FCSToken;
                //var TokenTakeOut = CSRedisCacheHelper.Get_Partition<FCS_ReturnInfo>(Key, 1);
                //if (TokenTakeOut == null)
                //{
                //    return Json(new { Status = "ok", Message = "NoData" }, JsonRequestBehavior.AllowGet);
                //}
                var dic = CSRedisCacheHelper.HMGetAll(3, CacheKey.FCSOrder);
                foreach (var item in dic)
                {
                    var OrderData = JsonConvert.DeserializeObject<FCS_OrderData>(item.Value);
                    var code = OrderData.HotelCode;
                    var CleanUUID = OrderData.ItemUUID;
                    var HostNUMBER = OrderData.HostNUMBER;
                    var PropertyID = OrderData.PropertyID;
                    var LocationUUID = OrderData.LocationUUID;
                    string vvv = string.Format("= ''{0}''", LocationUUID);
                    QueryFCSOrder ooo = new QueryFCSOrder();
                    ooo.filter = "";
                    ooo.column_filter = new OrderQueryItem() { field = "location_uuid", value = new List<string>() { vvv } };

                    var client1 = new RestClient(FCSLoginUrl);
                    var request1 = new RestRequest("/job/status", Method.POST);



                    string Key = CacheKey.FCSToken + "_" + code;
                    var TokenTakeOut = CSRedisCacheHelper.Get_Partition<FCS_ReturnInfo>(Key, 1);
                    if (TokenTakeOut == null)
                    {
                        continue;
                    }
                    request1.AddHeader("token", TokenTakeOut.data.access_token);
                    request1.AddHeader("property", PropertyID);
                    request1.AddJsonBody(ooo);

                    var QQQ = client1.Execute(request1);
                    string ddd = QQQ.Content;
                    var FFFA = Newtonsoft.Json.JsonConvert.DeserializeObject<QueryOrderResponse>(ddd);
                    if (!string.IsNullOrEmpty(CleanUUID))
                    {
                        if (FFFA != null && FFFA.data != null && FFFA.data.Count > 0)
                        {
                            var D1 = FFFA.data.FirstOrDefault(A => A["item_uuid"].Equals(CleanUUID));
                            if (D1 != null)
                            {
                                string V = "";
                                D1.TryGetValue("job_status", out V);
                                if (V.Equals("cancelled"))
                                {
                                    Host host = new Host();
                                    host.HostNumber = HostNUMBER;
                                    HostModal s = new HostModal();
                                    s.Modal = new RoomTypeModal() { ModalAddress = "004000003", Type = DeviceType.ServiceInfo };
                                    HostModalManager.SetDevice(host, s, 0, 0);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("GetFCSClean_OrderList");
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
            }
            return null;
        }

        #endregion


        #region 创维电视，创维电视接口必须要在Api路径下
        [HttpPost()]
        public ActionResult login()
        {
            ReturnInfo r = new ReturnInfo();
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var user = JsonConvert.DeserializeObject<chuangweilogin>(jsonData);
                var user1 = SysUserManager.Get(user.username, user.password);
                //if (user.username.Equals("chuangwei") && user.password.Equals("123456"))
                if (user1 != null)
                {
                    r = SignKeyCommon.GetTokenData(user.username);
                }
                //if (user != null)
                //{
                //}
                else
                {
                    r.code = 10009;
                    r.msg = "登录失败，用户名或者密码不正确";
                }
            }
            catch (Exception ex)
            {
                r.code = 500;
                r.msg = ex.Message;
            }

            return Json(r, JsonRequestBehavior.AllowGet);
        }

        [HttpPost()]
        public ActionResult refreshToken()
        {
            ReturnInfo Re = new ReturnInfo();
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                JWTData JJJ = null;
                int code = 0;
                string msg = "";
                var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
                if (dic != null)
                {
                    string retoken = dic["refreshToken"];
                    var T = SignKeyCommon.TokenValidate(retoken, out JJJ, out code, out msg);
                    if (T)
                    {
                        Re = SignKeyCommon.GetTokenData(JJJ.username);
                    }
                    else
                    {
                        Re.msg = msg;
                        Re.code = code;
                    }
                }
                else
                {
                    code = 10021;
                    msg = "非法token";
                }

            }
            catch (Exception ex)
            {
                Re.code = 500;
                Re.msg = ex.Message;
            }
            return Json(Re, JsonRequestBehavior.AllowGet);
        }


        #endregion


        #region TCL电视

        [HttpPost()]
        public ActionResult GetTCLLoginToken()
        {
            try
            {
                TCLCommon.GetTCLTV_Token();
            }
            catch (Exception)
            {

            }
            return null; ;
        }
        #endregion
        /// <summary>
        /// 模拟接口
        /// </summary>
        /// <returns></returns>
        public ActionResult ChangeRoomStatus_Test()
        {
            Host host = HostManager.GetByRoomNumber("8888", 1);
            HostManager.ChangeRoomStatus(host, 2);//2：出租，4：待租，8：退房，16：空房

            return Json(new { rescode = "200", resDesc = "操作成功" }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet()]
        public ActionResult LogTest()
        {
            MemoryCacheHelper.Set("UDPPackage_a", "aa", DateTimeOffset.Now.AddSeconds(20));
            return Json(new { rescode = "200" }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost()]
        public ActionResult QueryFaceInfo(int HotelId, int RoomId)
        {
            try
            {
                string Name = "";
                string Key = "FaceInfo_" + RoomId + "_" + hotelID;
                var Obj = MemoryCacheHelper.Get(Key);
                if (Obj != null)
                {
                    Name = Obj.ToString();
                }
                else
                {
                    Host host = HostManager.GetByRoomNumber(RoomId, HotelId);
                    string hg = host.RoomType.Name;
                    MemoryCacheHelper.SlideSet(Key, hg);
                    Name = hg;
                }

                return Json(new { RoomTypeName = Name, resDesc = "查询成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error_msg = ex.Message, resDesc = "查询失败" }, JsonRequestBehavior.AllowGet);
            }
        }


        public static string DayKeyPrefix = "WebApiAnalysis_";
        [HttpPost()]
        public ActionResult GetAllWebApiInvoke_FenXi()
        {
            try
            {
                List<TongJiApiInvokeInfo> list = new List<TongJiApiInvokeInfo>();
                string OldData1 = DateTime.Now.AddDays(0).ToString("yyyy-MM-dd");
                string OldData2 = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                string OldData3 = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
                var q1 = CSRedisCacheHelper.Get_Partition<TongJiApiInvokeInfo>(DayKeyPrefix + OldData1, 1);
                var q2 = CSRedisCacheHelper.Get_Partition<TongJiApiInvokeInfo>(DayKeyPrefix + OldData2, 1);
                var q3 = CSRedisCacheHelper.Get_Partition<TongJiApiInvokeInfo>(DayKeyPrefix + OldData3, 1);
                if (q1 != null)
                {
                    list.Add(q1);
                }
                if (q2 != null)
                {
                    list.Add(q2);
                }
                if (q3 != null)
                {
                    list.Add(q3);
                }
                return Json(new { WebApiInvokeInfo = list, resDesc = "查询成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error_msg = ex.Message, resDesc = "查询失败" }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 这段代码暂时废弃掉，原来找不到 CPU占用100%的时候用，现在找到了，用不到这个接口了
        /// </summary>
        /// <param name="MethodName"></param>
        public static void WebApiInvoke_FenXi(string MethodName)
        {

            //string OldData = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
            //var q = CSRedisCacheHelper.Get_Partition<TongJiApiInvokeInfo>(OldData, 1);
            //if (q != null)
            //{
            //    CSRedisCacheHelper.Del(new string[] { OldData });
            //}
            //string DayKey = DayKeyPrefix + DateTime.Now.ToString("yyyy-MM-dd");
            //int H = DateTime.Now.Hour;
            //var q1 = CSRedisCacheHelper.Get_Partition<TongJiApiInvokeInfo>(DayKey, 1);
            //if (q1 != null)
            //{
            //    string KKK = MethodName + "#" + H;
            //    //0:12 是 0-1点的数据
            //    //1:23 是1-2的数据， 归纳就是 当前小时的数据就是 属于下个小时的数据
            //    int Count = 0;
            //    bool bf = q1.DataList.TryGetValue(KKK, out Count);
            //    if (bf == false)
            //    {
            //        q1.DataList.Add(KKK, 0);
            //    }
            //    else
            //    {
            //        int NewCount = Count + 1;
            //        q1.DataList[KKK] = NewCount;
            //    }
            //    CSRedisCacheHelper.Set_Partition<TongJiApiInvokeInfo>(DayKey, q1, 1);
            //}
            //else
            //{
            //    TongJiApiInvokeInfo t = new TongJiApiInvokeInfo();
            //    t.DataList = new Dictionary<string, int>();
            //    for (int i = 0; i < 24; i++)
            //    {
            //        string KKK = MethodName + "#" + i;
            //        t.DataList.Add(KKK, 0);
            //    }
            //    CSRedisCacheHelper.Set_Partition<TongJiApiInvokeInfo>(DayKey, t, 1);
            //}

        }


        #region 日志系统需要的接口


        public class TempData
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class TempDataA
        {
            public int ID;
            public string Code;
            public string GroupName;
            public string Name;
            public string CreateDate { get; set; }
        }

        public class ResponseData
        {
            public IList<object> OwinFloorGroupList { get; set; }
            public List<TempDataA> HotelListInfo { get; set; }
        }


        [HttpPost()]
        public ActionResult LogSystemlogin()
        {
            NReturnInfo r = new NReturnInfo();
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var user = JsonConvert.DeserializeObject<chuangweilogin>(jsonData);
                var entity = SysUserManager.Get(user.username, user.password);

                if (entity != null)
                {
                    //var Q = entity.Hotels.Select(A => new TempData { Id = A.ID, Name = A.Name });
                    IList<object> result = new List<object>();
                    result.Add(SysHotelGroupManager.CreateGroupTree2(entity.SysHotelGroup));

                    var Q1 = result.FirstOrDefault();
                    if (Q1 != null)
                    {
                        int id = (int)Q1.GetType().GetProperty("ID").GetValue(Q1, null);
                        string KKKey = "LogSystemloginData_" + id.ToString() + "_" + entity.Account;
                        object oooa = HttpContext.Cache.Get(KKKey);
                        if (oooa != null)
                        {
                            r.response = oooa;
                        }
                        else
                        {
                            var DDD = GetData(id, entity.Account);
                            HttpContext.Cache.Add(KKKey, DDD, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                            r.response = DDD;
                        }
                    }
                    else
                    {
                        r.response = new List<object>();
                    }
                    r.isok = true;
                }
                else
                {
                    r.isok = false;
                    r.message = "登录失败，用户名或者密码不正确";
                }
            }
            catch (Exception ex)
            {
                r.isok = false;
                r.message = ex.Message;
            }

            return Json(r, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 新的日志登录系统
        /// 这里的代码，时间紧急。是临时方案，
        /// 考虑不周
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult LogSystemloginNew()
        {
            NReturnInfo r = new NReturnInfo();
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var user = JsonConvert.DeserializeObject<chuangweilogin>(jsonData);
                var entity = SysUserManager.Get(user.username, user.password);

                ResponseData rf = new ResponseData();
                if (entity != null)
                {
                    if (entity.HotelID > 0 && entity.Group == null)//酒店用户没有楼层分组权限
                    {
                        return Json(null, JsonRequestBehavior.AllowGet);
                    }
                    IList<object> groupTree = new List<object>();
                    //如果该用户所在分组同属于当前酒店，则获取该分组下客房，否则获取该酒店下所有客房
                    if (entity.Group != null && entity.Group.HotelID == entity.HotelID)
                    {
                        groupTree.Add(GroupManager.CreateGroupTree2(entity.Group, entity.HotelID));
                    }
                    else
                    {
                        IList<Group> currentGroup = GroupManager.GetGroupList(entity.HotelID);
                        if (currentGroup.Count > 0)
                        {
                            groupTree.Add(GroupManager.CreateGroupTree2(currentGroup[0], entity.HotelID));
                        }
                    }

                    rf.OwinFloorGroupList = groupTree;
                }

                if (entity != null)
                {
                    IList<object> result = new List<object>();
                    result.Add(SysHotelGroupManager.CreateGroupTree2(entity.SysHotelGroup));

                    if (entity.Account.Equals("admin") || entity.Account.Equals("leo") || entity.Account.Equals("blw"))
                    {

                        result.Add(GroupManager.CreateGroupTree2(entity.Group, entity.HotelID));

                        var Q1 = result.FirstOrDefault();
                        if (Q1 != null)
                        {
                            int id = (int)Q1.GetType().GetProperty("ID").GetValue(Q1, null);
                            string KKKey = "LogSystemloginData_" + id.ToString() + "_" + entity.Account;
                            object oooa = HttpContext.Cache.Get(KKKey);
                            if (oooa != null)
                            {
                                rf.HotelListInfo = (List<TempDataA>)oooa;
                                r.response = rf;

                            }
                            else
                            {
                                var DDD = GetData(id, entity.Account);
                                HttpContext.Cache.Add(KKKey, DDD, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                                rf.HotelListInfo = DDD;
                                r.response = rf;
                            }
                        }
                        else
                        {
                            r.response = new List<object>();
                        }
                    }
                    else
                    {

                        string KKKey = "LogSystemloginData_" + entity.Group.ID.ToString() + "_" + entity.Account;
                        object oooa = HttpContext.Cache.Get(KKKey);
                        if (oooa != null)
                        {

                            rf.HotelListInfo = (List<TempDataA>)oooa;
                            r.response = rf;
                        }
                        else
                        {
                            var roomList = HostManager.LoadAll(entity.Group);
                            List<TempDataA> LL = roomList.Select(A => new TempDataA
                                {
                                    Code = A.SysHotel.Code,
                                    CreateDate = A.SysHotel.CreatedDate.ToString("yyyy-MM-dd"),
                                    GroupName = A.SysHotel.SysHotelGroup.Name,
                                    Name = A.SysHotel.Name,
                                    ID = A.SysHotel.ID
                                }).ToList();
                            rf.HotelListInfo = LL;
                            HttpContext.Cache.Add(KKKey, LL, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                            r.response = rf;
                        }
                    }




                    r.isok = true;
                }
                else
                {
                    r.isok = false;
                    r.message = "登录失败，用户名或者密码不正确";
                }
            }
            catch (Exception ex)
            {
                r.isok = false;
                r.message = ex.Message;
            }

            return Json(r, JsonRequestBehavior.AllowGet);
        }



        [HttpPost()]
        public ActionResult GetGroupId()
        {
            NReturnInfo r = new NReturnInfo();
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var user = JsonConvert.DeserializeObject<chuangweilogin>(jsonData);
                var currentUser = SysUserManager.Get(user.username, user.password);

                if (currentUser.HotelID > 0 && currentUser.Group == null)//酒店用户没有楼层分组权限
                {
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
                IList<object> groupTree = new List<object>();
                groupTree.Add(new { id = 0, text = HttpContext.InnerLanguage("HotelFloor") });
                //如果该用户所在分组同属于当前酒店，则获取该分组下客房，否则获取该酒店下所有客房
                if (currentUser.Group != null && currentUser.Group.HotelID == currentUser.HotelID)
                {
                    groupTree.Add(GroupManager.CreateGroupTree2(currentUser.Group, currentUser.HotelID));
                }
                else
                {
                    IList<Group> currentGroup = GroupManager.GetGroupList(currentUser.HotelID);
                    if (currentGroup.Count > 0)
                    {
                        groupTree.Add(GroupManager.CreateGroupTree2(currentGroup[0], currentUser.HotelID));
                    }
                }

                return Json(groupTree, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                r.isok = false;
                r.message = ex.Message;
            }

            return Json(r, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 根据 根节点查询数据信息
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetCurrentHotel(int? groupId)
        {
            IList<SysHotel> hotels = new List<SysHotel>();
            switch (User.Identity.Name.ToLower())
            {
                case "admin":
                case "leo":
                case "blw":
                    hotels = SysHotelManager.LoadAll().Where(r => !r.IsDeleted).ToList();
                    break;
                default:
                    hotels = SysHotelManager.LoadAll().Where(r => r.IsApprove && !r.IsDeleted).ToList();//装载已审核的酒店
                    break;
            }
            if (groupId.HasValue && groupId != 1)//过滤分组
            {
                hotels = hotels.Where(r => r.SysHotelGroup.ID == groupId ||
                    (r.SysHotelGroup.Parent != null && r.SysHotelGroup.Parent.ID == groupId) ||
                    (r.SysHotelGroup.Parent != null && r.SysHotelGroup.Parent.Parent != null && r.SysHotelGroup.Parent.Parent.ID == groupId)).ToList();
            }
            hotels = hotels.OrderByDescending(o => o.ID).ThenBy(o => o.SysHotelGroup.Sort).ToList();
            var hotelData = hotels.Select(r => new
            {
                r.ID,
                r.Code,
                GroupName = SysHotelGroupManager.BuildGroupName(r.SysHotelGroup),
                Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName)
            }).ToList();

            return Json(new { total = hotels.Count, rows = hotelData }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 根据房间号，酒店编号来查询房型信息。
        /// </summary>
        /// <param name="roomnumber"></param>
        /// <param name="hotelcode"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetRoomTypeInfo(string roomnumber, string hotelcode)
        {
            try
            {
                Host host = HostManager.GetByRoomNumber(roomnumber, hotelcode);
                var AA = host.RoomType;

                var G = new { RoomTypeId = AA.ID, RoomTypeName = AA.Name };

                return Json(new { Result = G, resDesc = "查询成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error_msg = ex.Message, resDesc = "查询失败" }, JsonRequestBehavior.AllowGet);
            }
        }


        [HttpGet()]
        public ActionResult GetRoomTypeAndModalsListLog(string jsonData)
        {
            string start_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            try
            {
                JObject jData = (JObject)JsonConvert.DeserializeObject(jsonData);
                string code = jData["code"].ToString();
                SysHotel sysHotel = SysHotelManager.GetByCode(code);
                if (sysHotel == null)
                {
                    msg = "酒店未知";
                    return Json(new { IsSuccess = false, Result = "msg" }, JsonRequestBehavior.AllowGet);
                }
                int hhh = sysHotel.ID;
                IList<RoomType> roomTypes = RoomTypeManager.LoadAll().Where(r => r.HotelID == hhh && !r.IsDeleted).ToList();
                IList<object> list = new List<object>();
                foreach (RoomType roomType in roomTypes)
                {
                    IList<MMM> modalsList = new List<MMM>();
                    foreach (RoomTypeModal model in roomType.Modals)
                    {
                        modalsList.Add(new MMM
                        {
                            ID = model.ID,
                            ModalAddress = model.ModalAddress,
                            Name = model.Name,
                            EnglistName = model.EnglishName,
                            TWName = model.TWName,
                            TypeName = Common.Tools.GetDescription(model.Type),
                            SourceType = model.SourceType,
                            ActiveIndicator = model.ActiveIndicator
                        });
                    }
                    list.Add(new
                    {
                        ID = roomType.ID,
                        Code = roomType.Code,
                        Name = roomType.Name,
                        Modals = modalsList.OrderBy(A => A.ModalAddress)
                    });
                }
                return Json(new { IsSuccess = true, Result = list }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取房型及其回路数据失败。参数：" + jsonData + "，原因：" + ex + "，来自：" + GetClientIP());
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }

        public static string missionsys_address = ConfigurationManager.AppSettings["missionsys_address"];
        /// <summary>
        /// 设置统计的时间
        /// </summary>
        /// <param name="interval_Minutes"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult TongJiTimerIntervalSet(int interval_Minutes)
        {
            try
            {
                RedisTongJiData tq = new RedisTongJiData();
                tq.url = "api/CaiJiData";
                tq.cron_exp = string.Format("*/{0} * * * *", interval_Minutes);
                tq.mission_key = MvcApplication.IntervalKey;
                CSRedisCacheHelper.Forever<RedisTongJiData>(MvcApplication.IntervalKey, tq);

                var client1 = new RestClient(missionsys_address);
                var request1 = new RestRequest("api/declare_mission", Method.POST);
                request1.AddParameter("url", tq.url);
                request1.AddParameter("mission_key", tq.mission_key);
                request1.AddParameter("mission_name", tq.mission_key);
                request1.AddParameter("cron_exp", tq.cron_exp);
                client1.ExecuteAsync(request1, (response) =>
                {
                    string result = response.Content;
                });

                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取统计时间间隔
        /// </summary>
        public ActionResult GetTongJiTimerInterval()
        {

            try
            {
                var DDD = CSRedisCacheHelper.ForeverGet<RedisTongJiData>(MvcApplication.IntervalKey);
                var Time = DDD.cron_exp;
                //var Time = "*/10 * * * *";
                string[] data = Time.Split('/', ' ');

                return Json(new { IsSuccess = true, Result = data[1].ToString() }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }



        #region 隔几包，丢一包
        /// <summary>
        /// 隔几包 丢一包 
        /// </summary>
        /// <param name="LostHz"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult DefineUDPLostDataRate(long LostHz)
        {
            try
            {
                CSRedisCacheHelper.Forever<long>(MvcApplication.UDPLostKey, LostHz);
                //DataTongJi.DefineLostPackage = LostHz;
                //DataTongJi.RecordLostPackage = 0;
                Interlocked.Exchange(ref DataTongJi.DefineLostPackage, LostHz);
                Interlocked.Exchange(ref DataTongJi.RecordLostPackage, 0);
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取UDP丢包速率
        /// 隔几包丢一包
        /// </summary：>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetDefineUDPLostDataRate()
        {
            try
            {
                var Lf = CSRedisCacheHelper.ForeverGet<long>(MvcApplication.UDPLostKey);
                return Json(new { IsSuccess = true, Result = Lf }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion



        #region 超时
        /// <summary>
        /// 获取UDP超时时间
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetDefineUDPLostDataInterval()
        {
            try
            {
                var L = CSRedisCacheHelper.ForeverGet<int>(MvcApplication.UDPLostIntervalKey);
                return Json(new { IsSuccess = true, Result = L }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 间隔多久的数据要丢掉
        /// </summary>
        /// <param name="Interval"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult DefineUDPLostDataInterval(int Interval)
        {
            try
            {
                CSRedisCacheHelper.Forever<int>(MvcApplication.UDPLostIntervalKey, Interval);
                DataTongJi.LostPackage_Interval = Interval;
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        /// <summary>
        /// 有哪些酒店的数据不会被0x19 机制给过滤掉
        /// </summary>
        /// <param name="hotelcode"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult ZeroX19DataSet(string hotelcode)
        {
            try
            {
                var LLL = CSRedisCacheHelper.ForeverGet<List<string>>(MvcApplication.ZeroX19_PassHotelCodeKey);
                if (!LLL.Contains(hotelcode))
                {
                    LLL.Add(hotelcode);
                    CSRedisCacheHelper.Forever<List<string>>(MvcApplication.ZeroX19_PassHotelCodeKey, LLL);
                }
                if (!DataTongJi.ZeroX19_PassHotelCode.Contains(hotelcode))
                {
                    DataTongJi.ZeroX19_PassHotelCode.Add(hotelcode);
                }
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取0x19 起了作用的酒店
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetZeroX19Data()
        {
            try
            {
                var L = CSRedisCacheHelper.ForeverGet<List<string>>(MvcApplication.ZeroX19_PassHotelCodeKey);
                return Json(new { IsSuccess = true, Result = L }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取RCU在线数量
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetRCUOnLine()
        {

            try
            {
                var L = DataTongJi.ONLINERCU;
                var L1 = L.Count.ToString();
                return Json(new { IsSuccess = true, Result = L1 }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取取电开关的在线数量
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetTakeCard_OnLine()
        {

            try
            {
                var L = DataTongJi.TakeCardOnLine;
                var L1 = L.Where(A => A.Value.Status == 0x01).ToList().Count.ToString();
                return Json(new { IsSuccess = true, Result = L1 }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取所有的 黑名单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult GetBlockLWSetData()
        {
            try
            {
                var QQQ = CSRedisCacheHelper.ForeverGet<ConcurrentDictionary<string, ConcurrentBag<string>>>(MvcApplication.BlockLowerMachineKey);
                if (QQQ != null)
                {
                    return Json(new { IsSuccess = true, Result = QQQ }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { IsSuccess = true, Result = QQQ }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 设置下位机黑名单
        /// </summary>
        /// <param name="interval_Minutes"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult BlockLWSet()
        {
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var user = JsonConvert.DeserializeObject<Block_NameList>(jsonData);

                ConcurrentBag<string> L = null;
                string hotelcode = user.HotelCode;
                bool bl = DataTongJi.BlockLowerMachineList.TryGetValue(hotelcode, out L);
                if (bl && L != null)
                {
                    DataTongJi.BlockLowerMachineList.TryRemove(hotelcode, out L);
                }
                else
                {
                    ConcurrentBag<string> USA = new ConcurrentBag<string>(user.HostNumberList);
                    DataTongJi.BlockLowerMachineList.TryAdd(hotelcode, USA);
                }
                CSRedisCacheHelper.Forever<ConcurrentDictionary<string, ConcurrentBag<string>>>(MvcApplication.BlockLowerMachineKey, DataTongJi.BlockLowerMachineList);
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost()]
        public ActionResult BlockLWRemove(string hotelcode)
        {
            try
            {
                ConcurrentBag<string> L = null;
                bool bl = DataTongJi.BlockLowerMachineList.TryGetValue(hotelcode, out L);
                if (bl && L != null)
                {
                    DataTongJi.BlockLowerMachineList.TryRemove(hotelcode, out L);
                }
                CSRedisCacheHelper.Forever<ConcurrentDictionary<string, ConcurrentBag<string>>>(MvcApplication.BlockLowerMachineKey, DataTongJi.BlockLowerMachineList);
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 日志系统采集数据
        /// 由外界来调用
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult CaiJiData(string key, string mission_key)
        {
            try
            {

                long LC1 = Interlocked.Read(ref YUANZI_TongJi.TotalErrorPackageReceiveCount);
                var TotalKey1 = "TotalErrorPackageReceiveCount";
                UDPPackageCount LLL_T1 = null;
                DataTongJi.TotalCount.TryGetValue(TotalKey1, out LLL_T1);
                if (LLL_T1 != null)
                {
                    LLL_T1.Count = LC1;
                }
                else
                {
                    UDPPackageCount u = new UDPPackageCount();
                    u.Count = LC1;
                    DataTongJi.TotalCount.TryAdd(TotalKey1, u);
                }

                long LC = Interlocked.Read(ref YUANZI_TongJi.TotalReceiveCount);
                if (LC <= 60000)
                {
                    Interlocked.Increment(ref MvcApplication.UDPServerErrorCount);
                }
                else
                {
                    Interlocked.Exchange(ref MvcApplication.UDPServerErrorCount, 0);
                }

                long jishu_error = Interlocked.Read(ref MvcApplication.UDPServerErrorCount);
                if (jishu_error >= 3)
                {
                    logger.Error("重启了UDP服务器");
                    Interlocked.Exchange(ref MvcApplication.UDPServerErrorCount, 0);
                    var hostServer = (IHostServer)MvcApplication.cxt.GetObject("RCUHost.HostServer");
                    hostServer.Start();
                }
                var TotalKey = "UDPPackage_TotalRecvPackage";
                UDPPackageCount LLL_T = null;
                DataTongJi.TotalCount.TryGetValue(TotalKey, out LLL_T);
                if (LLL_T != null)
                {
                    LLL_T.Count = LC;
                }
                else
                {
                    UDPPackageCount u = new UDPPackageCount();
                    u.Count = LC;
                    DataTongJi.TotalCount.TryAdd(TotalKey, u);
                }

                var DDD = DataTongJi.TotalCount;
                string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var Y = DDD.ToArray();
                for (int i = 0; i < Y.Length; i++)
                {
                    var item = Y[i];
                    UDPPackageCount t = item.Value;
                    Common.UDPPackage u = new Common.UDPPackage();
                    u.CommandType = item.Key;
                    u.TotalCount = t.Count;
                    u.FenLei = t.FenLei;
                    u.RemoveTime = ti;

                    string mns = Newtonsoft.Json.JsonConvert.SerializeObject(u);
                    CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns);
                    //logger.Error("推送的数据:" + mns);
                }

                var FFF = DataTongJi.CPU_Data;
                if (FFF.Count > 0)
                {
                    var FFF1 = FFF.ToArray();
                    double max_d = FFF1.Max();
                    double min_d = FFF1.Min();
                    double avg_d = FFF1.Average();

                    NewMethod("UDPPackage_CPUMax", ti, max_d);
                    NewMethod("UDPPackage_CPUMin", ti, min_d);
                    NewMethod("UDPPackage_CPUAvg", ti, avg_d);
                }
                var V = DataTongJi.ONLINERCU.ToArray();
                Common.UDPPackage ux = new Common.UDPPackage();
                ux.CommandType = "RCUOnLine";
                ux.TotalCount = V.Length;
                ux.RemoveTime = ti;

                var W = V.GroupBy(A => A.Value.HotelCode);
                var dic = new ConcurrentDictionary<string, long>();
                foreach (var item in W)
                {
                    dic.TryAdd(item.Key, item.Count());
                }
                ux.FenLei = dic;
                string mns1 = Newtonsoft.Json.JsonConvert.SerializeObject(ux);
                CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns1);


                var V0 = DataTongJi.TakeCardOnLine.ToArray();
                var V1 = V0.Where(A => A.Value.Status == 0x01).ToList();
                Common.UDPPackage ux1 = new Common.UDPPackage();
                ux1.CommandType = "TakeCardIn";
                ux1.TotalCount = V1.Count;
                ux1.RemoveTime = ti;

                var W1 = V1.GroupBy(A => A.Value.HotelCode);

                var dic1 = new ConcurrentDictionary<string, long>();
                foreach (var item in W1)
                {
                    dic1.TryAdd(item.Key, item.Count());
                }
                ux1.FenLei = dic1;

                string mns2 = Newtonsoft.Json.JsonConvert.SerializeObject(ux1);
                CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns2);


                //在线用户
                var V3 = DataTongJi.OnLineUserList_IP.ToArray();
                DateTime dtn = DateTime.Now;
                var span = new TimeSpan(0, 1, 0);
                var V4 = V3.Where(A =>
                {
                    if (dtn - A.Value.LastUpdateTime <= span)
                    {
                        return true;
                    }
                    return false;
                }).ToList();

                Common.UDPPackage ux2 = new Common.UDPPackage();
                ux2.CommandType = "在线用户";
                ux2.TotalCount = V4.Count;
                ux2.RemoveTime = ti;

                var dic2 = new ConcurrentDictionary<string, long>();
                foreach (var item in V4)
                {
                    dic2.TryAdd(item.Key, 1);
                }
                ux2.FenLei = dic2;

                var dic3 = new ConcurrentDictionary<string, string>();
                foreach (var item in V4)
                {
                    //string Key = IP + "_" + Account + "_" + code;
                    string[] nnn = item.Key.Split('@');
                    string ip = nnn[0];
                    dic3.TryAdd(ip, "0");
                }
                ux2.ExtraData = dic3;

                string mns3 = Newtonsoft.Json.JsonConvert.SerializeObject(ux2);
                CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns3);


                long l1 = Interlocked.Read(ref WebAPI_TongJi.GetRoomAirList);
                long l2 = Interlocked.Read(ref WebAPI_TongJi.SetRCUAir);
                long l3 = Interlocked.Read(ref WebAPI_TongJi.GetRoomSceneList);
                long l4 = Interlocked.Read(ref WebAPI_TongJi.SetRCUScene);
                long l5 = Interlocked.Read(ref WebAPI_TongJi.GetRoomLightList);
                long l6 = Interlocked.Read(ref WebAPI_TongJi.SetRCULight);
                long l7 = Interlocked.Read(ref WebAPI_TongJi.GetRoomCurtainList);
                long l8 = Interlocked.Read(ref WebAPI_TongJi.SetRCUCurtain);
                long l9 = Interlocked.Read(ref WebAPI_TongJi.GetRoomServiceList);
                long l10 = Interlocked.Read(ref WebAPI_TongJi.SetRCUService);
                long l11 = Interlocked.Read(ref WebAPI_TongJi.GetOperationLog);
                long l12 = Interlocked.Read(ref WebAPI_TongJi.GetRoomMusicList);
                long l13 = Interlocked.Read(ref WebAPI_TongJi.SetRCUMusic);
                long l14 = Interlocked.Read(ref WebAPI_TongJi.GetRCUStatus);
                long l15 = Interlocked.Read(ref WebAPI_TongJi.GetAirDetectList);
                long l16 = Interlocked.Read(ref WebAPI_TongJi.GetHostFaultList);
                long l17 = Interlocked.Read(ref WebAPI_TongJi.GetRoomTypeAndModalsList);
                long l18 = Interlocked.Read(ref WebAPI_TongJi.GetRCUInfoForPDU);
                long l19 = Interlocked.Read(ref WebAPI_TongJi.GetSessionKey);
                long l20 = Interlocked.Read(ref WebAPI_TongJi.GetPhoneNumber);
                long l21 = Interlocked.Read(ref WebAPI_TongJi.GetHotelInfoForWX);

                Dictionary<string, long> dicwebapidata = new Dictionary<string, long>();
                dicwebapidata.Add("GetRoomAirList", l1);
                dicwebapidata.Add("SetRCUAir", l2);
                dicwebapidata.Add("GetRoomSceneList", l3);
                dicwebapidata.Add("SetRCUScene", l4);
                dicwebapidata.Add("GetRoomLightList", l5);
                dicwebapidata.Add("SetRCULight", l6);
                dicwebapidata.Add("GetRoomCurtainList", l7);
                dicwebapidata.Add("SetRCUCurtain", l8);
                dicwebapidata.Add("GetRoomServiceList", l9);
                dicwebapidata.Add("SetRCUService", l10);
                dicwebapidata.Add("GetOperationLog", l11);
                dicwebapidata.Add("GetRoomMusicList", l12);
                dicwebapidata.Add("SetRCUMusic", l13);
                dicwebapidata.Add("GetRCUStatus", l14);
                dicwebapidata.Add("GetAirDetectList", l15);
                dicwebapidata.Add("GetHostFaultList", l16);
                dicwebapidata.Add("GetRoomTypeAndModalsList", l17);
                dicwebapidata.Add("GetRCUInfoForPDU", l18);
                dicwebapidata.Add("GetSessionKey", l19);
                dicwebapidata.Add("GetPhoneNumber", l20);
                dicwebapidata.Add("GetHotelInfoForWX", l21);

                CSRedisCacheHelper.Publish("webapidata_consumer", JsonConvert.SerializeObject(dicwebapidata));


                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomAirList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUAir, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomSceneList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUScene, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomLightList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCULight, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomCurtainList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUCurtain, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomServiceList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUService, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetOperationLog, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomMusicList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUMusic, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRCUStatus, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetAirDetectList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetHostFaultList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomTypeAndModalsList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRCUInfoForPDU, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetSessionKey, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetPhoneNumber, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetHotelInfoForWX, 0);
                //logger.Error("推送的走到这里了");
                //DataTongJi.TotalCount.Clear();
                Interlocked.Exchange(ref YUANZI_TongJi.TotalReceiveCount, 0);
                Interlocked.Exchange(ref YUANZI_TongJi.TotalErrorPackageReceiveCount, 0);
                YUANZI_TongJi.TotalReceiveCount = 0;
                DataTongJi.OnLineUserList_IP = new ConcurrentDictionary<string, OnLineUser>();
                DataTongJi.TotalCount = new System.Collections.Concurrent.ConcurrentDictionary<string, UDPPackageCount>();
                DataTongJi.CPU_Data = new System.Collections.Concurrent.ConcurrentBag<double>();
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("RCU 数量统计出错了:" + ex.Message + ex.StackTrace);
                return Json(new { IsSuccess = false, Result = "fault" }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost()]
        public ActionResult CaiJiDataNew(string key, string mission_key)
        {

            try
            {
                if (string.IsNullOrEmpty(MvcApplication.JianKong_TxtData))
                {
                    string ns = Server.MapPath("~\\grafana\\" + MvcApplication.WanBuJianKongSourceFileName);
                    string getdata = System.IO.File.ReadAllText(ns, Encoding.UTF8);
                    MvcApplication.JianKong_TxtData = getdata;
                }
                string New_Txt = MvcApplication.JianKong_TxtData;
                long LC = Interlocked.Read(ref YUANZI_TongJi.TotalReceiveCount);

                New_Txt = New_Txt.Replace("{0}", LC.ToString());
                var TotalKey = "UDPPackage_TotalRecvPackage";
                UDPPackageCount LLL_T = null;
                DataTongJi.TotalCount.TryGetValue(TotalKey, out LLL_T);
                if (LLL_T != null)
                {
                    LLL_T.Count = LC;
                }
                else
                {
                    UDPPackageCount u = new UDPPackageCount();
                    u.Count = LC;
                    DataTongJi.TotalCount.TryAdd(TotalKey, u);
                }

                UDPPackageCount us1 = new UDPPackageCount();
                us1.Count = 1;
                DataTongJi.TotalCount.TryAdd(TotalKey, us1);

                UDPPackageCount us2 = new UDPPackageCount();
                us2.Count = 1;
                DataTongJi.TotalCount.TryAdd("UDPPackage_Heart", us1);

                var DDD = DataTongJi.TotalCount;
                string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                //UDP_Sent UDPPackage_TotalSendPackage
                New_Txt = NewMethod(New_Txt, DDD, TotalKey, "{1}");

                //RCU_Heart
                New_Txt = NewMethod(New_Txt, DDD, "UDPPackage_Heart", "{5}");

                //RCU_SearchHost
                New_Txt = NewMethod(New_Txt, DDD, "UDPPackage_SearchHost", "{6}");

                //Intercept
                New_Txt = NewMethod(New_Txt, DDD, "UDPPackage_Intercept", "{7}");

                //Energy
                New_Txt = NewMethod(New_Txt, DDD, "UDPPackage_能耗", "{9}");

                //RCU_OE StatusPass
                New_Txt = NewMethod(New_Txt, DDD, "UDPPackage_StatusPass", "{10}");

                //TCL_Ctr
                UDPPackageCount t_d7 = null;
                DDD.TryGetValue("UDPPackage_TianMaoQueryAll", out t_d7);

                UDPPackageCount t_d8 = null;
                DDD.TryGetValue("UDPPackage_TianMaoCONTROL", out t_d8);
                long eee = 0;
                if (t_d7 != null)
                {
                    eee = eee + t_d7.Count;
                }
                if (t_d8 != null)
                {
                    eee = eee + t_d8.Count;
                }
                New_Txt = New_Txt.Replace("{11}", eee.ToString());

                //TianMaoQueryAll
                //TianMaoCONTROL
                UDPPackageCount t_d2 = null;
                DDD.TryGetValue("UDPPackage_TianMaoQueryAll", out t_d2);

                UDPPackageCount t_d3 = null;
                DDD.TryGetValue("UDPPackage_TianMaoCONTROL", out t_d3);
                long ccc = 0;
                if (t_d2 != null)
                {
                    ccc = ccc + t_d2.Count;
                }
                if (t_d3 != null)
                {
                    ccc = ccc + t_d3.Count;
                }

                //TM_Ctr
                New_Txt = New_Txt.Replace("{12}", ccc.ToString());


                //小度精灵统计
                //string KKK = platformName + "Discovery";
                //string KKK = platformName + "Control";
                //XD_Ctr

                UDPPackageCount t_d5 = null;
                DDD.TryGetValue("UDPPackage_小度音箱Discovery", out t_d5);

                UDPPackageCount t_d6 = null;
                DDD.TryGetValue("UDPPackage_小度音箱Control", out t_d6);

                long ddd = 0;
                if (t_d5 != null)
                {
                    ddd = ddd + t_d5.Count;
                }
                if (t_d6 != null)
                {
                    ddd = ddd + t_d6.Count;
                }
                New_Txt = New_Txt.Replace("{13}", ddd.ToString());

                //Hivi_Ctr
                New_Txt = New_Txt.Replace("{14}", "0");

                var Y = DDD.ToArray();
                for (int i = 0; i < Y.Length; i++)
                {
                    var item = Y[i];
                    UDPPackageCount t = item.Value;
                    Common.UDPPackage u = new Common.UDPPackage();
                    u.CommandType = item.Key;
                    u.TotalCount = t.Count;
                    u.FenLei = t.FenLei;
                    u.RemoveTime = ti;

                    string mns = Newtonsoft.Json.JsonConvert.SerializeObject(u);
                    CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns);
                    //logger.Error("推送的数据:" + mns);
                }


                var FFF = DataTongJi.CPU_Data;
                if (FFF.Count > 0)
                {
                    var FFF1 = FFF.ToArray();
                    double max_d = FFF1.Max();
                    double min_d = FFF1.Min();
                    double avg_d = FFF1.Average();

                    NewMethod("UDPPackage_CPUMax", ti, max_d);
                    NewMethod("UDPPackage_CPUMin", ti, min_d);
                    NewMethod("UDPPackage_CPUAvg", ti, avg_d);
                }

                var V = DataTongJi.ONLINERCU.ToArray();

                //RCU_Online
                New_Txt = New_Txt.Replace("{3}", V.Length.ToString());


                Common.UDPPackage ux = new Common.UDPPackage();
                ux.CommandType = "RCUOnLine";
                ux.TotalCount = V.Length;
                ux.RemoveTime = ti;

                var W = V.GroupBy(A => A.Value.HotelCode);
                var dic = new ConcurrentDictionary<string, long>();
                foreach (var item in W)
                {
                    dic.TryAdd(item.Key, item.Count());
                }
                ux.FenLei = dic;
                string mns1 = Newtonsoft.Json.JsonConvert.SerializeObject(ux);
                CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns1);


                var V0 = DataTongJi.TakeCardOnLine.ToArray();
                var V1 = V0.Where(A => A.Value.Status == 0x01).ToList();

                //RCU_TakeCard
                New_Txt = New_Txt.Replace("{4}", V1.Count.ToString());

                Common.UDPPackage ux1 = new Common.UDPPackage();
                ux1.CommandType = "TakeCardIn";
                ux1.TotalCount = V1.Count;
                ux1.RemoveTime = ti;

                var W1 = V1.GroupBy(A => A.Value.HotelCode);

                var dic1 = new ConcurrentDictionary<string, long>();
                foreach (var item in W1)
                {
                    dic1.TryAdd(item.Key, item.Count());
                }
                ux1.FenLei = dic1;

                string mns2 = Newtonsoft.Json.JsonConvert.SerializeObject(ux1);
                CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns2);


                //在线用户
                var V3 = DataTongJi.OnLineUserList_IP.ToArray();
                DateTime dtn = DateTime.Now;
                var span = new TimeSpan(0, 1, 0);
                var V4 = V3.Where(A =>
                {
                    if (dtn - A.Value.LastUpdateTime <= span)
                    {
                        return true;
                    }
                    return false;
                }).ToList();

                //WebUser
                New_Txt = New_Txt.Replace("{8}", V4.Count.ToString());

                Common.UDPPackage ux2 = new Common.UDPPackage();
                ux2.CommandType = "在线用户";
                ux2.TotalCount = V4.Count;
                ux2.RemoveTime = ti;

                var dic2 = new ConcurrentDictionary<string, long>();
                foreach (var item in V4)
                {
                    dic2.TryAdd(item.Key, 1);
                }
                ux2.FenLei = dic2;

                var dic3 = new ConcurrentDictionary<string, string>();
                foreach (var item in V4)
                {
                    //string Key = IP + "_" + Account + "_" + code;
                    string[] nnn = item.Key.Split('@');
                    string ip = nnn[0];
                    dic3.TryAdd(ip, "0");
                }
                ux2.ExtraData = dic3;

                string mns3 = Newtonsoft.Json.JsonConvert.SerializeObject(ux2);
                CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns3);

                long l1 = Interlocked.Read(ref WebAPI_TongJi.GetRoomAirList);
                long l2 = Interlocked.Read(ref WebAPI_TongJi.SetRCUAir);
                long l3 = Interlocked.Read(ref WebAPI_TongJi.GetRoomSceneList);
                long l4 = Interlocked.Read(ref WebAPI_TongJi.SetRCUScene);
                long l5 = Interlocked.Read(ref WebAPI_TongJi.GetRoomLightList);
                long l6 = Interlocked.Read(ref WebAPI_TongJi.SetRCULight);
                long l7 = Interlocked.Read(ref WebAPI_TongJi.GetRoomCurtainList);
                long l8 = Interlocked.Read(ref WebAPI_TongJi.SetRCUCurtain);
                long l9 = Interlocked.Read(ref WebAPI_TongJi.GetRoomServiceList);
                long l10 = Interlocked.Read(ref WebAPI_TongJi.SetRCUService);
                long l11 = Interlocked.Read(ref WebAPI_TongJi.GetOperationLog);
                long l12 = Interlocked.Read(ref WebAPI_TongJi.GetRoomMusicList);
                long l13 = Interlocked.Read(ref WebAPI_TongJi.SetRCUMusic);
                long l14 = Interlocked.Read(ref WebAPI_TongJi.GetRCUStatus);
                long l15 = Interlocked.Read(ref WebAPI_TongJi.GetAirDetectList);
                long l16 = Interlocked.Read(ref WebAPI_TongJi.GetHostFaultList);
                long l17 = Interlocked.Read(ref WebAPI_TongJi.GetRoomTypeAndModalsList);
                long l18 = Interlocked.Read(ref WebAPI_TongJi.GetRCUInfoForPDU);
                long l19 = Interlocked.Read(ref WebAPI_TongJi.GetSessionKey);
                long l20 = Interlocked.Read(ref WebAPI_TongJi.GetPhoneNumber);
                long l21 = Interlocked.Read(ref WebAPI_TongJi.GetHotelInfoForWX);

                Dictionary<string, long> dicwebapidata = new Dictionary<string, long>();
                dicwebapidata.Add("GetRoomAirList", l1);
                dicwebapidata.Add("SetRCUAir", l2);
                dicwebapidata.Add("GetRoomSceneList", l3);
                dicwebapidata.Add("SetRCUScene", l4);
                dicwebapidata.Add("GetRoomLightList", l5);
                dicwebapidata.Add("SetRCULight", l6);
                dicwebapidata.Add("GetRoomCurtainList", l7);
                dicwebapidata.Add("SetRCUCurtain", l8);
                dicwebapidata.Add("GetRoomServiceList", l9);
                dicwebapidata.Add("SetRCUService", l10);
                dicwebapidata.Add("GetOperationLog", l11);
                dicwebapidata.Add("GetRoomMusicList", l12);
                dicwebapidata.Add("SetRCUMusic", l13);
                dicwebapidata.Add("GetRCUStatus", l14);
                dicwebapidata.Add("GetAirDetectList", l15);
                dicwebapidata.Add("GetHostFaultList", l16);
                dicwebapidata.Add("GetRoomTypeAndModalsList", l17);
                dicwebapidata.Add("GetRCUInfoForPDU", l18);
                dicwebapidata.Add("GetSessionKey", l19);
                dicwebapidata.Add("GetPhoneNumber", l20);
                dicwebapidata.Add("GetHotelInfoForWX", l21);

                CSRedisCacheHelper.Publish("webapidata_consumer", JsonConvert.SerializeObject(dicwebapidata));


                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomAirList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUAir, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomSceneList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUScene, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomLightList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCULight, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomCurtainList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUCurtain, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomServiceList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUService, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetOperationLog, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomMusicList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.SetRCUMusic, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRCUStatus, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetAirDetectList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetHostFaultList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRoomTypeAndModalsList, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetRCUInfoForPDU, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetSessionKey, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetPhoneNumber, 0);
                Interlocked.Exchange(ref WebAPI_TongJi.GetHotelInfoForWX, 0);
                //logger.Error("推送的走到这里了");
                //DataTongJi.TotalCount.Clear();
                Interlocked.Exchange(ref YUANZI_TongJi.TotalReceiveCount, 0);
                YUANZI_TongJi.TotalReceiveCount = 0;
                DataTongJi.OnLineUserList_IP = new ConcurrentDictionary<string, OnLineUser>();
                DataTongJi.TotalCount = new System.Collections.Concurrent.ConcurrentDictionary<string, UDPPackageCount>();
                DataTongJi.CPU_Data = new System.Collections.Concurrent.ConcurrentBag<double>();

                //WanBuJianKong(New_Txt);

                string nth = Server.MapPath("~\\grafana\\1.txt");
                //System.IO.File.WriteAllText(nth, New_Txt, Encoding.UTF8);
                WanBuJianKong(New_Txt, nth);

                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("RCU 数量统计出错了:" + ex.Message + ex.StackTrace);
                return Json(new { IsSuccess = false, Result = "fault" }, JsonRequestBehavior.AllowGet);
            }

        }


        [HttpPost()]
        public ActionResult tgs()
        {
            WanBuJianKong("fdfdfdf", "");
            return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
        }
        public static void WanBuJianKong(string Data, string SourceTxt)
        {
            System.IO.File.WriteAllText(SourceTxt, Data, Encoding.UTF8);
            // 如果目标文件存在，先删除
            if (System.IO.File.Exists(MvcApplication.WanBuJianKongTargetFileName))
            {
                System.IO.File.Delete(MvcApplication.WanBuJianKongTargetFileName);
            }

            // 重命名/移动文件
            System.IO.File.Move(SourceTxt, MvcApplication.WanBuJianKongTargetFileName);
        }

        private static string NewMethod(string New_Txt, ConcurrentDictionary<string, UDPPackageCount> DDD, string Key, string ReplaceKey)
        {
            UDPPackageCount t_d1 = null;
            //DDD.TryGetValue("UDPPackage_TotalSendPackage", out t_d1);
            if (DDD.TryGetValue(Key, out t_d1))
            {
                //New_Txt = New_Txt.Replace("{1}", t_d1.Count.ToString());
                New_Txt = New_Txt.Replace(ReplaceKey, t_d1.Count.ToString());
            }
            else
            {
                New_Txt = New_Txt.Replace(ReplaceKey, "0");
            }
            return New_Txt;
        }


        [HttpPost()]
        public ActionResult GetRCUOnLineStatus(string key, string mission_key)
        {
            try
            {
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("RCU 数量统计出错了:" + ex.Message + ex.StackTrace);
                return Json(new { IsSuccess = false, Result = "fault" }, JsonRequestBehavior.AllowGet);
            }

        }


        /// <summary>
        ///  RCU在线情况
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult ClearRCUInfo()
        {
            try
            {
                var Q = DataTongJi.ONLINERCU;
                var DT = DateTime.Now;
                var V = Q.Where(A =>
                    {
                        var DT_E = A.Value.CurrentDateTime;
                        TimeSpan timespan = DT - DT_E;
                        if (timespan.TotalSeconds > 300)
                        {
                            return true;
                        }
                        return false;
                    });
                foreach (var item in V)
                {
                    var IF = item.Key;
                    RCUOnLineExtra N;
                    Q.TryRemove(IF, out N);
                }
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Result = "fault" }, JsonRequestBehavior.AllowGet);
            }
        }


        [HttpPost()]
        public ActionResult TimerTest()
        {
            return null;
        }


        [HttpPost()]
        public ActionResult SendData()
        {
            //HostModalManager.SendData(null,new byte[]{});
            return null;
        }
        private static void NewMethod(string Key, string ti, double data)
        {
            Common.UDPPackage v = new Common.UDPPackage();
            v.CommandType = Key;
            long CPU_MAX = (long)Math.Round(data);
            v.TotalCount = CPU_MAX;
            v.RemoveTime = ti;
            string f1 = Newtonsoft.Json.JsonConvert.SerializeObject(v);
            CSRedisCacheHelper.redis3.Publish("redis-udppackage", f1);
        }


        public class MMM
        {
            public int ID { get; set; }
            public string ModalAddress { get; set; }
            public string Name { get; set; }
            public string EnglistName { get; set; }
            public string TWName { get; set; }
            public string TypeName { get; set; }
            public int SourceType { get; set; }
            public bool ActiveIndicator { get; set; }
        }

        private List<TempDataA> GetData(int groupId, string UserName)
        {
            IList<SysHotel> hotels = new List<SysHotel>();
            switch (UserName)
            {
                case "admin":
                case "leo":
                case "blw":
                    hotels = SysHotelManager.LoadAll().Where(r => !r.IsDeleted).ToList();
                    break;
                default:
                    hotels = SysHotelManager.LoadAll().Where(r => r.IsApprove && !r.IsDeleted).ToList();//装载已审核的酒店
                    break;
            }
            if (groupId != 1)//过滤分组
            {
                hotels = hotels.Where(r => r.SysHotelGroup.ID == groupId ||
                    (r.SysHotelGroup.Parent != null && r.SysHotelGroup.Parent.ID == groupId) ||
                    (r.SysHotelGroup.Parent != null && r.SysHotelGroup.Parent.Parent != null
                    && r.SysHotelGroup.Parent.Parent.ID == groupId)).ToList();

            }
            hotels = hotels.OrderByDescending(o => o.ID).ThenBy(o => o.SysHotelGroup.Sort).ToList();
            //DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            var hotelData = hotels.Select(r => new TempDataA
            {
                ID = r.ID,
                Code = r.Code,
                CreateDate = r.CreatedDate.ToString("yyyy-MM-dd"),
                GroupName = SysHotelGroupManager.BuildGroupName(r.SysHotelGroup),
                Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName)
            }).ToList();
            return hotelData;
        }

        private ActionResult LoadSysHotelGroupTree()
        {
            SysUsers user = SysUserManager.Get(User.Identity.Name);
            if (user.SysHotelGroup == null)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
            //IList<SysHotelGroup> groups = SysHotelGroupManager.LoadAll();
            //return Json(BuildGroupTree(groups, null), JsonRequestBehavior.AllowGet);
            IList<object> result = new List<object>();
            result.Add(SysHotelGroupManager.CreateGroupTree2(user.SysHotelGroup));
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost()]
        public ActionResult GetRCUStatus(string host_number, string mac)
        {

            Interlocked.Increment(ref WebAPI_TongJi.GetRCUStatus);
            try
            {
                bool is_online = CSRedisCacheHelper.Contains(host_number, mac);
                return Json(is_online, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion


        public ActionResult PMS_CheckIn()
        {
            try
            {
                var _client = new syncstatus.syncstatusSoapClient();
                return Json("", JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                throw;
            }
        }



        #region 宝易系统接口

        /// <summary>
        /// 上面有接口 可以获取 房型及其回路信息
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult LoadRoomTypeModalsWithPage(int roomTypeID)
        {
            var roomType = RoomTypeManager.Get(roomTypeID);
            var roomTypeModals = RoomTypeModalManager.LoadAll(roomType, 0).OrderBy(r => r.ModalAddress).ToList();//, deviceType);//获取该房型所有回路
            var roomModals = RoomModalManager.LoadAll().OrderBy(r => r.ModalAddress).ToList();//.Where(r => r.Type == deviceType).ToList();//获取所有默认回路
            foreach (RoomModal rm in roomModals)
            {
                if (roomTypeModals.Where(r => r.ModalAddress == rm.ModalAddress).ToList().Count == 0)//不存在，则新增新的默认回路
                {
                    roomTypeModals.Add(new RoomTypeModal()
                    {
                        ID = 0,
                        RoomType = roomType,
                        ModalAddress = rm.ModalAddress,
                        Outlet = rm.Outlet,
                        Name = rm.Name,
                        EnglishName = "",
                        TWName = "",
                        AliasName = "",
                        Power = rm.Power,
                        LowPower = 0,
                        Default = true,
                        Type = rm.Type,
                        Subtype = null,
                        Sort = rm.Sort,
                        ActiveIndicator = false,
                        OfflineDisplay = false,
                        LowPowerDisplay = false,
                        Beep = false,
                        Abnormal = false,
                        Color = rm.Color,
                        TCLDeviceName = "",
                        MultipleTCLName = "",
                        MultipleGroupID = 0,
                        IsUploadBaoJing = false
                    });
                }
            }
            var result = roomTypeModals//.AsQueryable().OrderBy(sort + " " + order).Skip((page - 1) * rows).Take(rows)
                .Select(r => new
                {
                    r.ID,
                    RoomTypeID = roomTypeID,
                    r.ModalAddress,
                    r.Outlet,
                    r.Name,
                    r.EnglishName,
                    r.TWName,
                    r.AliasName,
                    r.Power,
                    r.LowPower,
                    r.Default,
                    r.Type,
                    TypeName = HttpContext.InnerLanguage(r.Type.ToString()),
                    //Subtype = r.Subtype.HasValue ? HttpContext.InnerLanguage(r.Subtype.ToString()) : "",
                    r.Sort,
                    r.ActiveIndicator,
                    r.OfflineDisplay,
                    r.LowPowerDisplay,
                    r.Beep,
                    r.Abnormal,
                    r.Color,
                    r.TCLDeviceName,
                    r.MultipleTCLName,
                    r.MultipleGroupID,
                    r.IsUploadBaoJing
                });

            //var UUU= JsonConvert.SerializeObject(result);
            var NNN = result.Where(A => A.ActiveIndicator == true).ToList();
            return Json(new { total = result.Count(), rows = NNN });
        }


        /// <summary>
        /// 添加回路
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roomTypeID"></param>
        /// <param name="modalAddress"></param>
        /// <param name="outlet"></param>
        /// <param name="name"></param>
        /// <param name="englishName"></param>
        /// <param name="power"></param>
        /// <param name="twName"></param>
        /// <param name="aliasName"></param>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="color"></param>
        /// <param name="MultipleGroupID"></param>
        /// <param name="MultipleTCLName"></param>
        /// <param name="TCLDeviceName"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult SaveRoomTypeModal()
        {
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var userlist = JsonConvert.DeserializeObject<List<BaoYiModel>>(jsonData);

                var QQQ = userlist.GroupBy(A => A.roomTypeID).Select(A => A.Key);

                int roomTypeID = 0;
                foreach (var item in QQQ)
                {
                    RoomTypeModalManager.DeleteByRoomTypeID(item, 0);
                }
                var roomType = RoomTypeManager.Get(roomTypeID);
                foreach (var item in userlist)
                {
                    var id = item.id;
                    //var roomTypeID = item.roomTypeID;
                    var modalAddress = item.modalAddress; ;
                    var outlet = item.outlet;
                    var name = item.name;
                    var englishName = item.englishName;
                    var power = item.power;
                    var twName = item.twName;
                    var aliasName = item.aliasName;
                    var type = item.type;
                    var sort = item.sort;
                    var color = item.color;

                    var OfflineDisplay = item.OfflineDisplay;

                    var LowPower = item.LowPower;
                    //低电保存显示
                    var LowPowerDisplay = item.LowPowerDisplay;

                    //是否声音报警
                    var Beep = item.Beep;
                    //是否异常判断
                    var Abnormal = item.Abnormal;

                    var MultipleGroupID = item.MultipleGroupID;
                    var MultipleTCLName = item.MultipleTCLName;
                    var TCLDeviceName = item.TCLDeviceName;
                    var WXActiveIndicator = item.WXActiveIndicator;
                    var ActiveIndicator = item.ActiveIndicator;
                    var isuploadbaojing = item.IsUploadBaoJing;

                    var roomTypeModal = new RoomTypeModal();
                    if (id == 0)
                    {
                        //if (roomType == null)
                        //{
                        //    throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoomType"));
                        //}
                        //var modall = RoomTypeModalManager.LoadAll().Where(r => r.RoomType.ID == roomTypeID && r.ModalAddress == modalAddress).ToList();
                        //if (modall != null && modall.Count > 0)
                        //{
                        //    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("LoopAddressExists") });
                        //}
                        roomTypeModal.RoomType = roomType;
                        roomTypeModal.ModalAddress = modalAddress;
                        roomTypeModal.Outlet = outlet;
                        roomTypeModal.Name = name;
                        roomTypeModal.EnglishName = englishName;
                        roomTypeModal.TWName = twName;
                        roomTypeModal.AliasName = aliasName;
                        roomTypeModal.Power = power;
                        roomTypeModal.Default = false;
                        roomTypeModal.Type = type;
                        roomTypeModal.Subtype = null;
                        roomTypeModal.Sort = sort;
                        roomTypeModal.Color = color;
                        roomTypeModal.ActiveIndicator = ActiveIndicator;//新增时默认显示
                        //roomTypeModal.WXActiveIndicator = WXActiveIndicator;//只要显示，微信默认允许控制
                        roomTypeModal.WXActiveIndicator = true;//只要显示，微信默认允许控制
                        roomTypeModal.OfflineDisplay = OfflineDisplay;
                        roomTypeModal.LowPowerDisplay = LowPowerDisplay;
                        roomTypeModal.Beep = Beep;
                        roomTypeModal.Abnormal = Abnormal;



                        roomTypeModal.SourceType = 0;
                        roomTypeModal.MultipleTCLName = MultipleTCLName;
                        roomTypeModal.TCLDeviceName = TCLDeviceName;
                        roomTypeModal.IsUploadBaoJing = isuploadbaojing;
                        int a = 0;
                        int.TryParse(MultipleGroupID, out a);
                        roomTypeModal.MultipleGroupID = a;


                        RoomTypeModalManager.Save(roomTypeModal);//新增房型下单个回路
                    }
                    System.Threading.Tasks.Task.Factory.StartNew<bool>(() => UpdateHostModals(roomTypeModal));//更新主机回路
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }

        /// <summary>
        /// 碳达人 宝易软件
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult SaveRoomTypeModal_CarbonVIP()
        {
            try
            {

                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                var uuu = JsonConvert.DeserializeObject<tandaren_upload>(jsonData);
                int roomtypeid = uuu.roomtype_id;
                var lll = uuu.CarbonVIPList;
                var rlist = RoomTypeModalManager.LoadAll(roomtypeid, 0);
                foreach (var item in lll)
                {
                    var add = item.ModalAddress;
                    var up = item.IsUploadBaoJing;
                    var modal = rlist.FirstOrDefault(A => A.ModalAddress.Equals(add));
                    if (modal != null)
                    {
                        modal.IsUploadBaoJing = up;
                        RoomTypeModalManager.Update(modal);//新增房型下单个回路
                        Task.Factory.StartNew((state) =>
                            {
                                var mmm = (RoomTypeModal)state;
                                UpdateHostModals(mmm);
                            }, modal);//更新主机回路
                    }
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        public class tandaren_upload
        {
            public int roomtype_id { get; set; }
            public List<single_tandaren> CarbonVIPList { get; set; }
        }
        public class single_tandaren
        {
            public string ModalAddress { get; set; }
            public bool IsUploadBaoJing { get; set; }
        }
        public class BaoYiModel
        {
            public int id { get; set; }
            public int roomTypeID { get; set; }
            public string modalAddress { get; set; }
            public string outlet { get; set; }
            public string name { get; set; }
            public string englishName { get; set; }
            public int power { get; set; }
            public string twName { get; set; }
            public string aliasName { get; set; }
            public DeviceType type { get; set; }
            public int sort { get; set; }
            public string color { get; set; }

            public int LowPower { get; set; }
            //离线保存显示
            public bool OfflineDisplay { get; set; }

            /// <summary>
            /// 是否低电显示
            /// </summary>
            public bool LowPowerDisplay { get; set; }

            public bool Beep { get; set; }
            /// <summary>
            /// 是否异常判断
            /// </summary>
            public virtual bool Abnormal { get; set; }



            public bool WXActiveIndicator { get; set; }
            public bool ActiveIndicator { get; set; }
            public string MultipleGroupID { get; set; }
            public string MultipleTCLName { get; set; }
            public string TCLDeviceName { get; set; }
            public bool IsUploadBaoJing { get; set; }
        }

        [HttpPost()]
        public ActionResult JiNanTongPai_Spec()
        {
            try
            {

                var dic = CSRedisCacheHelper.HMGetAll(5, CacheKey.JiNan_TongPai_Spec);
                foreach (var item in dic)
                {
                    var k = item.Key;
                    var v = item.Value;
                    DateTime ti = DateTime.Parse(v);
                    if (k.Contains("_"))
                    {
                        var span = DateTime.Now - ti;
                        if (span.TotalSeconds >= 60 && span.TotalMinutes <= 75)
                        {
                            string[] h_a = k.Split('_');
                            Host host = new Host() { HostNumber = h_a[0], MAC = "" };
                            HostModal hostModal = new HostModal() { Modal = new RoomTypeModal() { ModalAddress = h_a[1], Type = DeviceType.AirConditioner } };
                            HostModalManager.SetDevice(host, hostModal, 0, 0, 0, 0);
                        }
                    }
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }

        [HttpGet()]
        public ActionResult GetAllModelName()
        {
            var t = Enum.GetNames(typeof(Domain.DeviceType));
            return Json(new { IsSuccess = true, Result = t }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除回路
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult RemoveRoomModal()
        {
            try
            {
                string idsstr = Request.Form["ids"];
                int[] ids = Newtonsoft.Json.JsonConvert.DeserializeObject<int[]>(idsstr);
                IList<string> modalList = new List<string>();
                foreach (var id in ids)
                {
                    var modal = RoomTypeModalManager.Get(id);
                    if (modal != null)
                    {
                        List<Host> hosts = HostManager.LoadAll().Where(t => t.RoomType == modal.RoomType).ToList();
                        foreach (Host host in hosts)
                        {
                            HostModalManager.DeteleByRoomTypeModal(host.ID, modal.ID);//先删除主机关联回路
                        }
                        RoomTypeModalManager.Delete(modal);//再删除房型关联回路
                        modalList.Add(Language == Language.CN ? modal.Name : modal.EnglishName);
                    }
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + ex.Message });
            }
        }


        /// <summary>
        /// 更新主机回路
        /// </summary>
        /// <param name="roomTypeModal"></param>
        /// <returns></returns>
        private bool UpdateHostModals(RoomTypeModal roomTypeModal)
        {
            List<Host> hosts = HostManager.LoadAll().Where(t => t.RoomType.ID == roomTypeModal.RoomType.ID).ToList();
            foreach (Host host in hosts)//该房型下所有主机关联回路
            {
                //删除掉上报的
                CSRedisCacheHelper.Del_Partition(CacheKey.DingShiReportData + "_" + host.ID, 3);
                var hostModal = HostModalManager.GetByModalAddress(host.ID, roomTypeModal.ModalAddress);
                if (null == hostModal)
                {
                    HostModalManager.Save(new HostModal { HostID = host.ID, Modal = roomTypeModal, Status = 2, Time = 0, UpdateTime = DateTime.Now });
                }
            }
            return true;
        }
        #endregion

        public ITFTP_SettingMananger TFTPManager { get; set; }
        [HttpPost()]
        public ActionResult TFTPReadSet()
        {
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string body = System.Text.Encoding.UTF8.GetString(byts);
                var qqq = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(body);

                foreach (var item in qqq)
                {
                    string hotelcode = item["hotelcode"].ToString();
                    string hostnumber = item["hostnumber"].ToString();
                    string mac = item["mac"].ToString();
                    HostManager.Send_Query_Data(new byte[] { }, hostnumber, mac);
                }
                TFTP_Set TFG = TFTPManager.GetData(122, 111);
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
            return Json(new { IsSuccess = true, Message = "Success" });
        }

        [HttpPost()]
        public ActionResult TFTPSet_Execute()
        {

            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string body = System.Text.Encoding.UTF8.GetString(byts);

                var item = JsonConvert.DeserializeObject<FTP_JSON>(body);

                var lll = item.host_data;
                foreach (var singleitem in lll)
                {
                    List<byte> list = new List<byte>();
                    if (item.isenable)
                    {
                        list.Add(0xff);
                    }
                    else
                    {
                        list.Add(0x00);
                    }
                    byte[] p1 = BitConverter.GetBytes(item.port);
                    list.AddRange(p1);
                    byte[] p2 = BitConverter.GetBytes(item.lasttime);
                    list.AddRange(p2);

                    byte[] bbb = Encoding.ASCII.GetBytes(item.domain);
                    byte len = (byte)bbb.Length;
                    list.Add(len);
                    list.AddRange(bbb);
                    byte[] bba = list.ToArray();
                    var hostnumber = singleitem.hostnumber;
                    var mac = singleitem.mac;
                    HostManager.Send_Setting_Data(bba, hostnumber, mac);
                }
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }

        #region 设置透传

        /// <summary>
        /// 发送透传数据
        /// </summary>
        /// <param name="hostnumber"></param>
        /// <param name="mac"></param>
        /// <param name="bytelist"></param>
        /// <param name="cmdtype"></param>
        /// <param name="isoriginal"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult SendUDPPackage(string hostnumber, string mac, string bytelist, string cmdtype, bool isoriginal = false)
        {

            try
            {
                //Host hh = HostManager.GetByRoomNumber("1001", "1001");
                bytelist = Tools.DeleteSpaceChar(bytelist);
                byte[] data = Tools.GetBytesFromString(bytelist);
                byte byteValue2 = Byte.Parse(cmdtype, System.Globalization.NumberStyles.HexNumber);
                HostManager.PublishUDPData(hostnumber, mac, data, byteValue2);
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception)
            {
                return Json(new { IsSuccess = true, Message = "Success" });
            }
        }

        /// <summary>
        /// 设置UDP透传房间
        /// </summary>
        /// <param name="hostnumber"></param>
        /// <param name="mac"></param>
        /// <param name="add_or_remove"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult SetTouChuanData(string hostnumber, string mac, string add_or_remove)
        {

            try
            {
                if (add_or_remove.Equals("add"))
                {
                    //加入透传列表
                    CSRedisCacheHelper.HMSet(1, CacheKey.TouChuanKey, hostnumber, hostnumber);
                }
                else if (add_or_remove.Equals("remove"))
                {
                    CSRedisCacheHelper.HDel(1, CacheKey.TouChuanKey, hostnumber);
                }
                else
                {

                }
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception)
            {
                return Json(new { IsSuccess = true, Message = "Success" });
            }
        }
        #endregion


        #region 定时

        /// <summary>
        /// ID和编号的对应关系
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult HostID_HostNumber()
        {
            try
            {
                var qqq = HostManager.LoadAllID_HostNumberMapping();
                var qqq1 = qqq.Select(a => new { a.HostNumber, a.Id }).ToList();


                if (qqq1.Count > 0)
                {
                    foreach (var item in qqq1)
                    {

                        if (!string.IsNullOrEmpty(item.HostNumber))
                        {
                            //CSRedisCacheHelper.HMSet(5, CacheKey.RoomNumber_HostNumber, item.HostNumber, item.RoomNumber);
                            CSRedisCacheHelper.HMSet(5, CacheKey.HostId_HostNumber, item.HostNumber, item.Id);
                        }
                    }
                }
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = "Fault" + ex.Message });
            }
        }

        [HttpPost()]
        public ActionResult RoomNumber_HostNumber()
        {
            try
            {
                var qqq = HostManager.LoadAll_RoomNumberMapping();
                //var qqq1 = qqq.SelectMany(a => new string[] { a.HostNumber, a.RoomNumber }).ToList();
                var qqq2 = qqq.Select(A => new { HostNumber = A.HostNumber, RoomNumber = A.RoomNumber }).ToList();
                foreach (var item in qqq2)
                {
                    if (!string.IsNullOrEmpty(item.HostNumber) && !string.IsNullOrEmpty(item.RoomNumber))
                    {
                        CSRedisCacheHelper.HMSet(5, CacheKey.RoomNumber_HostNumber, item.HostNumber, item.RoomNumber);
                    }
                }
                //if (qqq1.Count > 0)
                //{
                //    CSRedisCacheHelper.HMSet(5, CacheKey.RoomNumber_HostNumber, qqq1);
                //}
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = "Fault" + ex.Message });
            }
        }

        [HttpPost()]
        public ActionResult MQTTHeartBeat()
        {

            try
            {
                if (BLWMQTT.MqttClientGlobal.IsConnected)
                {
                    BLWMQTT.MqttClientGlobal.Publish("blw/mqtt/heartbeat", Encoding.UTF8.GetBytes("hello beat"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                }
                else
                {
                    BLWMQTT.StartMqtt();
                }
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception)
            {
                return Json(new { IsSuccess = false, Message = "Fault" });
            }
        }
        #endregion


        private void SyncRoomStatus(int hotelID, DataRow dr, RoomStatus roomStatus, int flag)
        {
            Task.Factory.StartNew(() =>
            {
                Host host = HostManager.GetByRoomNumber(dr["RoomNumber"].ToString(), hotelID);
                if (host != null)
                {
                    HostManager.ChangeRoomStatus(host, roomStatus);
                    string Key = CacheKey.SyncRoomStatus + "_" + host.HostNumber;
                    RoomStatusRequest ddd = new RoomStatusRequest();
                    ddd.HostNumber = host.HostNumber;
                    ddd.MAC = host.MAC;
                    ddd.Status = roomStatus;
                    CSRedisCacheHelper.Set_PartitionWithForever<RoomStatusRequest>(Key, ddd);
                }
                var _client = new syncstatus.syncstatusSoapClient();
                _client.UpdateCheckInOrOutRecord(dr["Code"].ToString(), Convert.ToInt64(dr["ID"]), flag);//更新已同步状态
            }, System.Threading.CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
        }
        [HttpPost()]
        public ActionResult syncRoomStatusCallback()
        {
            try
            {
                var _client = new syncstatus.syncstatusSoapClient();
                RCUHost.TimingHelper.HostTimingControlHelper.HostTimingControl(DeviceControlReceiver);//定时控制
                DateTime now = DateTime.Now;
                DataSet dsHotel = _client.GetHotelCode();
                foreach (DataRow row in dsHotel.Tables[0].Rows)
                {
                    if (Convert.ToInt16(row["HotelID"]) > 0)
                    {
                        DataSet ds = _client.GetCheckInOrOutRecord(row["Code"].ToString());
                        if (ds != null && ds.Tables.Count > 2 && ds.Tables[3].Rows.Count > 0)
                        {
                            int hotelID = Convert.ToInt16(ds.Tables[3].Rows[0]["HotelID"].ToString());//与PMS同步接口所配置的HotelID
                            if (hotelID > 0)
                            {
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {

                                    var q = RoomStatusManager.Get(2);
                                    SyncRoomStatus(hotelID, dr, q, 0);//更新出租房态
                                }
                                foreach (DataRow dr in ds.Tables[1].Rows)
                                {
                                    var q = RoomStatusManager.Get(8);
                                    SyncRoomStatus(hotelID, dr, q, 1);//更新退房房态
                                }
                                foreach (DataRow dr in ds.Tables[2].Rows)
                                {
                                    var q = RoomStatusManager.Get(4);
                                    SyncRoomStatus(hotelID, dr, q, 2);//更新待租房态
                                }
                            }
                        }
                    }
                }
                return Json(new { IsSuccess = true, Message = "Success" });
            }
            catch (Exception ex)
            {
                logger.Error("定时同步房态异常。原因：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }



        /// <summary>
        /// 凌晨定时
        /// </summary>
        /// <param name="interval_Minutes"></param>
        ///  key=123456789&mission_key=#{mission_key}
        /// <returns></returns>
        [HttpPost()]
        public ActionResult LingChenECO(string key, string mission_key)
        {
            try
            {
                string[] data = mission_key.Split('_');
                string code = data[1];
                string time = data[2];
                string[] wendu = CSRedisCacheHelper.HMGet<string>(5, MvcApplication.LingChenECO_IntervalKey, code + "#" + time);
                HostManager.TimerECO(code, int.Parse(wendu[0]));
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost()]
        public ActionResult RestartUDPServer(string key)
        {
            try
            {
                if (key.Equals("blw^_^wlb"))
                {
                    var hostServer = (IHostServer)MvcApplication.cxt.GetObject("RCUHost.HostServer");
                    hostServer.Start();
                }
                return Json(new { IsSuccess = true, Result = "success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return Json(new { IsSuccess = false, Result = "操作异常：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

    }
    public class NReturnInfo
    {
        public bool isok { set; get; } // 是否成功，true成功
        public string message { set; get; } // 传递接口信息，or报错信息
        public int status { set; get; } // 服务器报错信息，正确为200，错误404/500等
        public object response { set; get; } // 获取到的信息本体，若报错则为null
    }

    public class chuangweilogin
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    public class TongJiApiInvokeInfo
    {
        public Dictionary<string, int> DataList { get; set; }
    }
    public class TimeSplitData
    {
        public string ShiJianDuan_Key { get; set; }
        public int Count { get; set; }
    }
}
