using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Dao;
using Domain;
using RCUHost.Protocols;
using System.Collections;
using CommonEntity;
using RestSharp;
using Newtonsoft.Json.Linq;
using System.Configuration;
using Microsoft.IO;

namespace RCUHost.Implement
{
    public class RoomStatusReceiver : GenericReceiverBase, IRoomStatusReceiver
    {
        //private static readonly RecyclableMemoryStreamManager manager = new RecyclableMemoryStreamManager();
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RoomStatusReceiver));
        //private ConcurrentDictionary<string, Status> roomsStatus = new ConcurrentDictionary<string, Status>();
        public IHostRepository HostRepository { get; set; }
        public IHostModalRepository HostModalRepository { get; set; }
        public IHostModalRecordRepository HostModalRecordRepository { get; set; }
        public IHostFaultsRepository HostFaultsRepository { get; set; }
        public IHostFaultRecordsRepository HostFaultRecordsRepository { get; set; }
        public IHostSceneRepository HostSceneRepository { get; set; }
        public IRoomTypeSceneRepository RoomTypeSceneRepository { get; set; }
        public ISysOauth2Repository SysOauth2Repository { get; set; }
        public IRoomCardRepository RoomCardRepository { get; set; }
        public IRoomCardTypeRepository RoomCardTypeRepository { get; set; }
        public IHotelSeasonRepository HotelSeasonRepository { get; set; }
        public IHotelAirControlRepository HotelAirControlRepository { get; set; }
        public IDeviceControlReceiver DeviceControlReceiver { get; set; }


        //阿宝添加的
        public ICarbonScene_SetRepository CarbonScene_SetRepository { get; set; }
        public ILieECORepository ILieECORepository { get; set; }

        public static string PoolOverFlowKey = "PoolOverFlowKey";
        public static string TakeCardReportFlowKey = "TakeCardReportFlowKey";

        //StringBuilder sb = new StringBuilder();
        public override void Process(ReceiverContext context)
        {

            StepTongJi.SendInfo(4, "Task内部开始执行", context.MessageID, context.IsMonitor);
            string HostNumberOnly = context.SystemHeader.Value.HostNumber.ToString();
            string hotelcode = context.SystemHeader.Value.HostNumber.ToHotelCode().ToString();

            #region 如果超过2秒就不再处理了
            //string ShiJianLanJie = CacheKey.SyncTimeIntercept + "_" + HostNumberOnly;
            //object VVV = MemoryCacheHelper.Get(ShiJianLanJie);
            //if (VVV == null)
            //{
            //    string hotelCode = context.SystemHeader.Value.HostNumber.ToHotelCode().ToString();//获取酒店编码
            //    string RegisterKey1 = "RoomStatusTimeOutDrop";
            //    RCUHost.RCUHostCommon.tools.LanJieData(RegisterKey1, hotelCode);
            //    return;
            //}

            //回复
            //Reply(context);
            #endregion

            Host host = null;
            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + HostNumberOnly;
            string Key_Same1 = CacheKey.RoomStatus_Prefix + "_" + HostNumberOnly;
            object obj = MemoryCacheHelper.Get(Key);
            if (obj != null)
            {
                host = obj as Host;
            }
            else
            {
                Host host_O = HostRepository.GetByHostNumber(HostNumberOnly);
                MemoryCacheHelper.SlideSet(Key, host_O);
                MemoryCacheHelper.SlideSet(Key_Same1, host_O);
                host = host_O;
            }
            if (host != null)
            {
                if (host.SysHotel.IsNewVersionProtocol)
                {
                    NewVersionHexData ns = new NewVersionHexData();
                    ns.CmdType = 0x01;
                    ns.HotelCode = hotelcode;
                    ns.HostNumber = HostNumberOnly;
                    ns.RemoteEndPoint = context.RemoteEndPoint.ToString();
                    ns.CurrentTime = DateTime.Now;
                    ns.HexData = Tools.ByteToString(context.Data);

                    CSRedisCacheHelper.Publish("redis-rcu-registerdata", Newtonsoft.Json.JsonConvert.SerializeObject(ns));
                }
            }

            string k1 = CacheKey.HostFrameNo + "_" + HostNumberOnly;
            string k2 = CacheKey.PowerSupply + "_" + HostNumberOnly;
            string k3 = CacheKey.LockVoltage + "_" + HostNumberOnly;
            string k4 = CacheKey.HostTemp + "_" + HostNumberOnly;
            ushort fff = CSRedisCacheHelper.ForeverGet<ushort>(k1);
            if (host == null) { return; }

            if (context.SystemHeader.Value.FrameNo != 65535 && context.SystemHeader.Value.FrameNo == fff)
            {
                //return;
            }

            try
            {
                int offset = StructConverter.SizeOf(context.SystemHeader);
                int length = context.Data.Length - offset - 2;

                //using (var stream = manager.GetStream())
                //{
                //stream.Write(context.Data, offset, length);
                //}
                using (MemoryStream stream = new MemoryStream(context.Data, offset, length))
                {
                    bool isTriggerWelcomeMsg = true;
                    Status status = DecodeRoomStatus_NEW(stream, HostNumberOnly, out isTriggerWelcomeMsg, host.SysHotel.Code, host.RoomNumber);
                    if (status != null)
                    {
                        #region 放进缓存来处理
                        //host.FrameNo = context.SystemHeader.Value.FrameNo;
                        //host.PowerSupply = !status.SysLock;//电源锁定（0正常，1锁定）//host.RoomCard.ID = status.CardType;//房卡：已修改到房卡上报协议                            
                        //host.LockVoltage = status.ElecQty;//门锁电量
                        //host.HostTemp = status.HostTemp;//主机温度
                        //HostRepository.SetHostInfo(host);
                        #endregion

                        CSRedisCacheHelper.Forever<ushort>(k1, context.SystemHeader.Value.FrameNo);
                        CSRedisCacheHelper.Forever<bool>(k2, !status.SysLock);
                        CSRedisCacheHelper.Forever<float>(k3, status.ElecQty);
                        CSRedisCacheHelper.Forever<byte>(k4, status.HostTemp);

                        StepTongJi.SendInfo(4.1, "设置Host库信息", context.MessageID, context.IsMonitor);

                        if (status.Devices != null && status.Devices.Count > 0)
                        {
                            var LLL = status.Devices.OrderBy(A => A.Key);
                            var KKK1 = LLL.Select(A => A.Key);
                            var KKK2 = LLL.Select(A => A.Value.StatusReceiver.ToString("00"));
                            var VVV1 = string.Join("", KKK1);
                            var VVV2 = string.Join("", KKK2);
                            //sb.Clear();
                            //sb.Append(VVV1);
                            //sb.Append(VVV2);
                            //string nnn = sb.ToString();
                            //来一个数据，把所有的地址拼接起来
                            string YiJingChuLiGuo = CacheKey.AllReadyDealWith0E_Prefix + "_" + HostNumberOnly;
                            MemoryCacheHelper.Delete(YiJingChuLiGuo);
                            ProcessModal_NEW_NEW(host, status.Devices, isTriggerWelcomeMsg, context.MessageID, context.IsMonitor, context.Data, status);//更新灯光及其他回路状态
                            string nnn = VVV1 + VVV2;
                            if (!string.IsNullOrEmpty(nnn))
                            {
                                MemoryCacheHelper.Set(YiJingChuLiGuo, nnn, DateTimeOffset.Now.AddMinutes(30));
                            }
                        }

                        if (status.Faults != null && status.Faults.Count > 0)
                        {
                            ProcessFaults(host, status.Faults);//处理故障
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                logger.Error(string.Format("更新酒店({0})客房({1})状态数据出错。", host.SysHotel.ID, host.RoomNumber), ex);
            }
        }

        public static string welKey = "redis-triggerwelcome_change";

        public SomeDeviceExistsData HostDataTake(ReceiverContext context)
        {
            string HostNumberOnly = context.SystemHeader.Value.HostNumber.ToString();
            string Key = CacheKey.RoomStatus_Prefix + "_" + HostNumberOnly;
            SomeDeviceExistsData host = CSRedisCacheHelper.Get_Partition<SomeDeviceExistsData>(Key);
            if (host != null)
            {

            }
            else
            {
                Host host_O = HostRepository.GetByHostNumber(HostNumberOnly);

                SomeDeviceExistsData h = new SomeDeviceExistsData();
                h.IP = host_O.IP;
                h.MAC = host_O.MAC;
                h.HostNUMBER = HostNumberOnly;
                h.HostID = host_O.ID;
                h.HotelCode = host_O.SysHotel.Code;
                h.HotelID = host_O.SysHotel.ID;
                h.RoomTypeID = host_O.RoomType.ID;
                h.RoomNumber = host_O.RoomNumber;
                h.FrameNo = host_O.FrameNo;
                h.DeviceStatusPushURL = host_O.SysHotel.DeviceStatusPushURL;
                h.FaultPushURL = host_O.SysHotel.FaultPushURL;
                h.XiaoDuCUID = host_O.XiaoDuCUID;
                h.TianMaoCUID = host_O.TianMaoCUID;
                h.WelcomeSpeech = host_O.SysHotel.WelcomeSpeech;
                h.GoodbyeSpeech = host_O.SysHotel.GoodbyeSpeech;

                h.RoomCardData = host_O.RoomCard;
                h.RoomStatus = host_O.RoomStatus;

                CSRedisCacheHelper.Set_Partition<SomeDeviceExistsData>(Key, h);
                host = h;
            }
            return host;
        }

        public static string Missionsys_Address = ConfigurationManager.AppSettings["missionsys_address"];
        public static string MQTTInfo_report_url = ConfigurationManager.AppSettings["debug_log_report_url"].ToString();

        private void ProcessModal_NEW_NEW(Host host, ConcurrentDictionary<string, Device> devices, bool IsTriggerWelcomeMsg, string ContextMessageId, bool ismonitor, byte[] OriginalByteList, Status yuanshidata)
        {
            string UUID = "9dc6a0ee-dcf1-4385-b05f-09cb463838cd";
            UUID = host.FCS_locationUUID;
            string PropertyUUID = host.SysHotel.FCS_PropertyID;

            string FCS_RCU_Device_Offline = host.SysHotel.FCS_RCU_Device_Offline;

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

            string FCS_Carbon_UUID = host.SysHotel.FCS_Carbon_UUID;
            string FCS_SOS_UUID = host.SysHotel.FCS_SOS_UUID;
            string FCS_Clean_UUID = host.SysHotel.FCS_Clean_UUID;
            string FCS_TouSu_UUID = host.SysHotel.FCS_TouSu_UUID;

            string FCS_MenCi_Open = host.SysHotel.FCS_MenCi_Open;
            string FCS_MenCi_Close = host.SysHotel.FCS_MenCi_Close;

            string FCS_RCU_Online = host.SysHotel.FCS_RCU_Online;
            string FCS_RCU_Offline = host.SysHotel.FCS_RCU_Offline;



            string HOSTNUMBER = host.HostNumber;
            string HOST_MAC = host.MAC;
            string HOTEL_CODE = host.SysHotel.Code;
            string ROOMNUMBER = host.RoomNumber;
            DateTime now = DateTime.Now;
            bool isInsert = false;

            StepTongJi.SendInfo(4.3, "Task开始执行设备信息处理", ContextMessageId, ismonitor);

            List<ts_deviceitem> shebei_changeaction_list = new List<ts_deviceitem>();
            List<ts_faultitem> exception_list = new List<ts_faultitem>();
            //StringBuilder sbSQL;
            foreach (var device in devices)
            {

                //代码太复杂 没看懂
                //碳达人，可以直接判断 设备类型即可
                //sbSQL = new StringBuilder();
                int status = 1;//状态：1开，2关
                if (device.Value.Address.Split('.').Length > 2)//处理指令场景
                {
                    #region 处理场景
                    try
                    {
                        //sbSQL.Append("UPDATE tb_HostScene SET ");
                        var hostScene = HostSceneRepository.Get(host.ID, device.Value.Address);
                        if (hostScene == null)
                        {
                            var roomTypeScene = RoomTypeSceneRepository.Get(host.RoomType.ID, device.Value.Address);
                            if (roomTypeScene == null) { continue; }
                            isInsert = true;
                            hostScene = new HostScene() { HostID = host.RoomType.ID, Scene = roomTypeScene, Status = 2, Time = 0, UpdateTime = now };
                        }
                        //处理回路当天开启时长
                        status = device.Value.StatusReceiver & 0x00FF;
                        switch (status)
                        {
                            case 2://回路关闭
                                if (hostScene.Status != 2)
                                {
                                    if (hostScene.UpdateTime.HasValue)
                                    {
                                        hostScene.Time += Convert.ToInt32((now - hostScene.UpdateTime.Value).TotalMinutes);
                                        //sbSQL.Append("Time=" + hostScene.Time + ",");
                                    }
                                    hostScene.UpdateTime = now;
                                    //sbSQL.Append("UpdateTime=GETDATE(),");
                                }
                                break;
                            default://回路开启
                                if (hostScene.Status == 2)
                                {
                                    hostScene.UpdateTime = now;
                                    //sbSQL.Append("UpdateTime=GETDATE(),");
                                }
                                break;
                        }
                        hostScene.Status = status;
                        //sbSQL.Append("Status=" + status);
                        if (isInsert)
                        {
                            isInsert = false;
                            HostSceneRepository.Save(hostScene);
                        }
                        else
                        {
                            //sbSQL.Append(" WHERE HostID=" + hostScene.HostID + " AND RoomTypeSceneID=" + hostScene.Scene.ID);
                            HostSceneRepository.Update(hostScene);//sbSQL.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("ProcessModal_NEW_NEW: " + ex.Message);
                    }
                    #endregion
                }
                else
                {
                    //sbSQL.Append("UPDATE tb_HostModal SET ");
                    //标记状态：
                    //0关闭设备，
                    //1打开设备且当前设备处于关闭状态，
                    //2打开设备且当前设备处于打开状态
                    int flag = 2;

                    //P4：设备执行状态
                    //0x01:设置节能状态
                    //0x02:设置全局亮度节能
                    //0x03:设定温度节能

                    //P5 设备内容
                    //Bit4~7：节能关触发来源
                    //0x00:无效
                    //0x01:亮度 不符合节能
                    //0x02:温度 不符合节能

                    //Bit0~3：节能状态
                    //0x01:开
                    //0x02:关

                    //说明是碳达人
                    #region 碳达人
                    if (device.Key.StartsWith("054"))
                    {
                        try
                        {
                            //里面包含了P4和P5
                            var iii = device.Value.StatusReceiver;

                            byte[] bbbddd = BitConverter.GetBytes(iii);
                            byte[] bba = new byte[] { bbbddd[1] };
                            BitArray bitArray = new BitArray(bba);

                            //这个是状态
                            var qqq1 = bitArray.Cast<bool>().Take(4).ToArray();

                            //这个是触发来源
                            var qqq2 = bitArray.Cast<bool>().Skip(4).Take(4).ToArray();

                            //节能状态
                            byte hhhg1 = Tools.CombineBitsToByte(qqq1[3], qqq1[2], qqq1[1], qqq1[0]);

                            //节能关触发来源
                            byte hhhg2 = Tools.CombineBitsToByte(qqq2[3], qqq2[2], qqq2[1], qqq2[0]);

                            string st = "";
                            string current_status = "";

                            if (hhhg1 == 0x01)
                            {
                                current_status = "open";
                            }
                            else if (hhhg1 == 0x02)
                            {
                                current_status = "close";
                            }
                            else
                            {
                                current_status = "unknow";
                            }
                            if (hhhg2 == 0x01)
                            {
                                st = "brightness";
                            }
                            else if (hhhg2 == 0x02)
                            {
                                st = "temperature";
                            }
                            else
                            {

                            }

                            //int hostid = host.ID;
                            //StringBuilder sb = new StringBuilder();
                            //sb.Append(CacheKey.CarbonVIP_Prefix);
                            //sb.Append("_");
                            //sb.Append(hostid.ToString());
                            //string Key = sb.ToString();
                            //CSRedisCacheHelper.Set<string>(Key, current_status);
                            //var data = CSRedisCacheHelper.Get<string>(Key);
                            //if (!string.IsNullOrEmpty(data))
                            //{
                            //    if (!current_status.Equals(data))
                            //    {
                            //        CarbonDataSend(host, hhhg1);
                            //    }
                            //}
                            //else
                            //{
                            //    CarbonDataSend(host, hhhg1);
                            //}

                            CarbonDataSend(host, hhhg1);
                            var nfc = CarbonScene_SetRepository.GetDataBy(host.ID);


                            if (nfc != null)
                            {
                                nfc.HostID = host.ID;
                                nfc.TriggerSource = st;
                                nfc.Status = current_status;
                                nfc.CreateTime = DateTime.Now.ToLocalTime();
                                CarbonScene_SetRepository.UpdateData(nfc);
                            }
                            else
                            {
                                CarbonScene ccc = new CarbonScene();
                                ccc.HostID = host.ID;
                                ccc.TriggerSource = st;
                                ccc.Status = current_status;
                                ccc.CreateTime = DateTime.Now.ToLocalTime();
                                CarbonScene_SetRepository.Add(ccc);
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error("CarbonVIP: " + ex.Message);
                            logger.Error(ex.StackTrace);
                        }

                    }

                    #endregion

                    #region 处理回路

                    //如果找不到直接返回
                    string FKey1 = CacheKey.HostModalStatus_BoolFilterPrefix + "_" + host.ID + "_" + device.Value.Address;
                    var ExistsFlag = CSRedisCacheHelper.Get_Partition<int>(FKey1);
                    if (ExistsFlag != 0)
                    {
                        continue;
                    }

                    string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + device.Value.Address;


                    var hostModal = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                    if (hostModal != null)
                    {

                    }
                    else
                    {
                        //这里有点问题，如果一个Model删除了，又更新了，那它的ID就变了。但是内存中记录的没变，所以这里会出问题
                        var hostModal_old = HostModalRepository.Get(host.ID, device.Value.Address);
                        if (hostModal_old != null)
                        {
                            HostModal_Cache c = new HostModal_Cache();
                            c.HostID = hostModal_old.HostID;
                            c.ModalType = hostModal_old.Modal.Type;
                            c.AirConditionData = new AirConditionData();
                            c.Modal = new RoomTypeModalCache()
                            {
                                RoomTypeID = hostModal_old.Modal.RoomType.ID,
                                ID = hostModal_old.Modal.ID,
                                Name = hostModal_old.Modal.Name,
                                ModalAddress = hostModal_old.Modal.ModalAddress,
                                ActiveIndicator = hostModal_old.Modal.ActiveIndicator,
                                Sort = hostModal_old.Modal.Sort
                            };
                            hostModal = c;
                        }
                        else
                        {
                            hostModal = null;
                        }
                    }

                    if (hostModal != null)
                    {
                        switch (hostModal.ModalType)
                        {
                            case DeviceType.Dimmer://LED
                            case DeviceType.Strip://灯带
                            case DeviceType.Traic://可控硅
                            case DeviceType.PWMDimmer://PWM调光
                            case DeviceType.PWMExpand://PWM扩展
                            case DeviceType.PBLED://PB LED
                            case DeviceType.LVout://弱电输出
                            case DeviceType.PB20:
                            case DeviceType.PB20_LD:
                            case DeviceType.PB20_LS:
                                #region 处理逻辑
                                int brightness = device.Value.StatusReceiver >> 8;
                                if (hostModal.Brightness != brightness)//调光类型：亮度从0到100，且设备有变化时才去更改状态
                                {
                                    if (brightness == 0)//设备关
                                    {
                                        flag = 0;
                                        hostModal.Status = 2;
                                        hostModal.Brightness = 0;


                                        //MemoryModal.Status = 2;
                                        //MemoryModal.Brightness = 0;
                                        //sbSQL.Append("Status=2,Brightness=0,");
                                    }
                                    else
                                    {
                                        flag = hostModal.Status != 1 ? 1 : 2;//如果原来不是打开状态，才创建新的回路记录
                                        hostModal.Status = 1;
                                        hostModal.Brightness = brightness;

                                        //MemoryModal.Status = 1;
                                        //MemoryModal.Brightness = brightness;
                                        //sbSQL.Append("Status=1,Brightness=" + hostModal.Brightness + ",");
                                    }
                                }
                                #endregion
                                break;
                            case DeviceType.AirDetect://空气质量检测
                                hostModal.Status = 1;
                                hostModal.Brightness = device.Value.StatusReceiver;
                                break;
                            case DeviceType.Relay://主机继电器
                            case DeviceType.Expand://扩展继电器
                            case DeviceType.ServiceInfo://服务信息
                            case DeviceType.SwitchExpand://开关扩展
                            case DeviceType.A9IORelay://A9IO继电器
                            case DeviceType.CardPower://取电
                            case DeviceType.Curtain://窗帘
                            case DeviceType.InFrared://红外感应
                                #region 红外 SOS 清理 等服务信息
                                status = device.Value.StatusReceiver & 0x00FF;

                                string code = host.SysHotel.Code;
                                if (device.Value.Address.Equals("004000008"))
                                {
                                    Dictionary<string, string> dica = new Dictionary<string, string>();
                                    string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    dica.Add("hotelcode", host.SysHotel.Code);
                                    dica.Add("roomnum", host.RoomNumber);
                                    dica.Add("devicetype", "sos");
                                    dica.Add("triggertime", ti);
                                    dica.Add("status", status.ToString());
                                    string str = Newtonsoft.Json.JsonConvert.SerializeObject(dica);
                                    //var client1 = new RestClient(MQTTInfo_report_url);
                                    //var request1 = new RestRequest("/", Method.POST);
                                    ////注意方法是POST
                                    ////两个参数名字必须是 topic 和payload ，区分大小写的
                                    //request1.AddParameter("topic", "blw/sos/report/"+code);
                                    //request1.AddParameter("payload", str);
                                    //logger.Error("publish sos data,"+code+","+host.RoomNumber);
                                    //client1.ExecuteAsync(request1, (response) => { });
                                    BLWMQTT.MQTTPublishData("blw/sos/report/" + code, str);
                                }
                                try
                                {
                                    if (status == 1)//设备开
                                    {
                                        #region 如果是睡眠模式就息屏
                                        //息屏是：1 
                                        //创维电视
                                        if (host.SysHotel.IsUseSkyworthTV)
                                        {
                                            string hotelcode = host.SysHotel.Code;
                                            string roomnum = host.RoomNumber;

                                            //睡眠息屏是1
                                            if (hostModal.Modal.Name.Equals("睡眠息屏"))
                                            {
                                                logger.Error("SkyWorthTV send data");
                                                SkyWorth.Invoke(hotelcode, host.RoomNumber, host.SysHotel.SkyworthTVauthCode, 1);
                                            }

                                            //呼叫前台
                                            if (host.SysHotel.Code == "1003")
                                            {
                                                if (hostModal.Modal.ModalAddress.Equals("004000023"))
                                                {
                                                    logger.Error("呼叫前台");

                                                    SkyWorth.Invoke(hotelcode, host.RoomNumber, host.SysHotel.SkyworthTVauthCode, 4);
                                                }
                                            }
                                        }
                                        //TCL电视
                                        if (host.SysHotel.IsUseTCLTV)
                                        {

                                            string hotelcode = host.SysHotel.Code;
                                            string roomnum = host.RoomNumber;
                                            string TCLcuid = host.TCLCUID;
                                            string skillid = host.TCLSkillID;

                                            //如果是息屏
                                            //004000022
                                            //if (hostModal.Modal.Name.Equals("睡眠息屏"))
                                            //{
                                            //}
                                            if (device.Value.Address.Equals("004000022"))
                                            {
                                                TCLCommon.SendData(hotelcode, roomnum, TCLcuid, skillid, "SLEEP");
                                            }

                                            //呼叫前台
                                            if (hostModal.Modal.ModalAddress.Equals("004000023"))
                                            {
                                                TCLCommon.SendData(hotelcode, roomnum, TCLcuid, skillid, "SIP");
                                            }
                                            //if (hotelcode.Equals("1085"))
                                            //{
                                            //    if (hostModal.Modal.ModalAddress.Equals("004000023"))
                                            //    {
                                            //        TCLCommon.SendData(hotelcode, roomnum, TCLcuid, skillid, "ROMANTIC");
                                            //    }
                                            //}

                                              string ebell_rtsp = host.EBell_RSTP;
                                              int du = host.EBell_TV_duration;
                                            if (hostModal.Modal.ModalAddress.Equals("004000021"))
                                            {
                                                Dictionary<string, string> ddd = new Dictionary<string, string>();
                                                if (!string.IsNullOrEmpty(ebell_rtsp))
                                                {
                                                    ddd.Add("url", ebell_rtsp);
                                                    ddd.Add("display_duration", du.ToString());
                                                }

                                                TCLCommon.SendData(hotelcode, roomnum, TCLcuid, skillid, "DOORBELL", 0, ddd);
                                            }
                                        }
                                        #endregion

                                        #region 设备开
                                        if (hostModal.Status != 1)//设备有变化时才去更改状态
                                        {

                                            flag = 1;
                                            hostModal.Status = 1;
                                            hostModal.Brightness = 100;

                                            //FCS推送
                                            //SOS
                                            if (hostModal.Modal.ModalAddress.Equals("004000008"))
                                            {
                                                //SOS推送
                                                RR.FCS_PushData(FCS_SOS_UUID, UUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, HOTEL_CODE, ROOMNUMBER);
                                            }
                                            //清理
                                            if (hostModal.Modal.ModalAddress.Equals("004000003"))
                                            {
                                                //一个房间的清理在5分钟之内 只能按一次 开的状态
                                                string CleanTrigger = CacheKey.CleanFCS_TriggerCount + "_" + HOSTNUMBER;
                                                int str = CSRedisCacheHelper.Get_Partition<int>(CleanTrigger);

                                                //没有数据才能使用
                                                if (str == 0)
                                                {
                                                    RR.FCS_PushData(FCS_Clean_UUID, UUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, HOTEL_CODE, ROOMNUMBER, "", HOSTNUMBER);
                                                }
                                            }
                                            if (hostModal.Modal.ModalAddress.Equals("004000004"))
                                            {
                                                //一键投诉推送
                                                RR.FCS_PushData(FCS_TouSu_UUID, UUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, HOTEL_CODE, ROOMNUMBER);
                                            }
                                        }

                                        #endregion
                                    }
                                    else//设备关
                                    {
                                        if (hostModal.Status != status)//设备有变化时才去更改状态，窗帘6是停，其他是关
                                        {
                                            flag = 0;
                                        }

                                        //清理
                                        if (hostModal.Modal.ModalAddress.Equals("004000003"))
                                        {
                                            //通过LocationUUID确定订单号
                                            string OrderUUID = CSRedisCacheHelper.Get_Partition<string>(CacheKey.FCSRoom_Mapping_Order + "_" + UUID, 3);
                                            RR.FCS_CancelOrderJob(UUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, HOTEL_CODE, ROOMNUMBER, OrderUUID);

                                            //删除定单 通过LocationUUID
                                            CSRedisCacheHelper.Del_Partition(CacheKey.FCSRoom_Mapping_Order + "_" + UUID, 3);
                                        }

                                        hostModal.Status = status;
                                        hostModal.Brightness = 0;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    logger.Error("取电数据有异常： " + host.SysHotel.Code + "," + host.RoomNumber + " Msg:" + ex.Message + ex.StackTrace);
                                }
                                CSRedisCacheHelper.Set_Partition<HostModal_Cache>(KKey, hostModal);
                                #endregion

                                #region 取电，门磁
                                switch (hostModal.Modal.ModalAddress)
                                {
                                    case "004000013"://门磁
                                        #region 门磁
                                        bool doorLockStatus = status == 1 ? true : false;
                                        if (host.DoorLockStatus != doorLockStatus)
                                        {
                                            host.DoorLockStatus = doorLockStatus;

                                            //FCS推送
                                            //门磁
                                            if (doorLockStatus)
                                            {
                                                RR.FCS_PushData(FCS_MenCi_Open, UUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, HOTEL_CODE, ROOMNUMBER);
                                            }
                                            else
                                            {
                                                RR.FCS_PushData(FCS_MenCi_Close, UUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, HOTEL_CODE, ROOMNUMBER);
                                            }
                                            HostRepository.SetDoorLockStatus(host, doorLockStatus);
                                        }
                                        #endregion
                                        break;
                                    case "004000001"://取电
                                        #region 取电开关

                                        #region 这个逻辑可能会用到
                                        //0关闭设备，
                                        //1打开设备且当前设备处于关闭状态，
                                        //取电
                                        //CommonEntity.DataTongJi.MTakeCardData t = new DataTongJi.MTakeCardData();
                                        //t.HostNUMBER = HOSTNUMBER;
                                        //t.HotelCode = HOTEL_CODE;
                                        //t.Status = Convert.ToByte(device.Value.StatusReceiver);
                                        //t.LastUpdateTime = DateTime.Now;
                                        ////不管是断电还是取电都要记录
                                        //if (flag == 1||flag==0)
                                        //{
                                        //    string sss = Newtonsoft.Json.JsonConvert.SerializeObject(t);
                                        //    CSRedisCacheHelper.Publish("redis-takecard_change", sss);
                                        //}
                                        //断电
                                        //if (flag == 0)
                                        //{
                                        //    string sss = Newtonsoft.Json.JsonConvert.SerializeObject(t);
                                        //    CSRedisCacheHelper.Publish("redis-takecard_change", sss);
                                        //}
                                        #endregion
                                        //拨卡操作
                                        if (flag == 0 && host.RoomCard != null)
                                        {
                                            host.RoomCard = null;
                                            HostRepository.SetRoomCard(host, null);//拔卡操作
                                        }
                                        else if (flag == 1 && host.RoomCard == null)
                                        {

                                            //CSRedisCacheHelper.HMSet(CacheKey.TakeCardOnLine,host.SysHotel.Code+"###"+ host.RoomNumber);
                                            RoomCardType roomCardType = null;

                                            #region 获取有人房卡类型
                                            string MemoryCardKey = "MemoryRoomCardPrefix_1";
                                            object ooo = MemoryCacheHelper.Get(MemoryCardKey);
                                            if (ooo != null)
                                            {
                                                roomCardType = ooo as RoomCardType;
                                            }
                                            else
                                            {
                                                roomCardType = RoomCardTypeRepository.Get(1);//获取有人房卡类型
                                                MemoryCacheHelper.SlideSet(MemoryCardKey, roomCardType);
                                            }
                                            #endregion

                                            #region 获取当前酒店独属 这个房间的卡
                                            RoomCard roomCard = null;
                                            string GetRoomCardBy = "GetRoomCardBy_" + roomCardType.ID + "_" + host.SysHotel.ID;
                                            object ooo1 = MemoryCacheHelper.Get(GetRoomCardBy);
                                            if (ooo1 != null)
                                            {
                                                roomCard = ooo as RoomCard;
                                            }
                                            else
                                            {
                                                roomCard = RoomCardRepository.Get(roomCardType, host.SysHotel.ID);
                                                if (roomCard != null)
                                                {
                                                    MemoryCacheHelper.Set(GetRoomCardBy, roomCard);
                                                }
                                            }
                                            #endregion

                                            if (roomCard == null)//如果该房卡类型未创建记录，自动创建
                                            {
                                                roomCard = new RoomCard();
                                                roomCard.CardNumber = "1";
                                                roomCard.RoomCardType = roomCardType;
                                                roomCard.HotelID = host.SysHotel.ID;
                                                RoomCardRepository.Save(roomCard);
                                            }
                                            host.RoomCard = roomCard;
                                            HostRepository.SetRoomCard(host, roomCard);//插卡操作
                                        }

                                        #region 语音机器人
                                        if (flag != 2)//取电或断电时处理
                                        {

                                            bool not_trigger = false;
                                            string key = PoolOverFlowKey + "_" + host.HostNumber;
                                            object data19 = MemoryCacheHelper.Get(key);
                                            if (data19 != null)
                                            {
                                                not_trigger = true;
                                            }
                                            if (IsTriggerWelcomeMsg == false)
                                            {
                                                not_trigger = true;
                                            }

                                            bool SmartIsDisable = SmartRobotDisable(host);
                                            //如果没有禁用
                                            if (SmartIsDisable == false && not_trigger == false)
                                            {
                                                //1、如果有绑定小度，小度处理
                                                if (!string.IsNullOrEmpty(host.XiaoDuCUID))
                                                {
                                                    string accessToken1 = SysOauth2Repository.GetXiaoDuToken();
                                                    if (!string.IsNullOrEmpty(accessToken1))
                                                    {
                                                        if (flag == 1 && !string.IsNullOrEmpty(host.SysHotel.WelcomeSpeech))//取电打开时，播放欢迎词
                                                        {

                                                            var ttt = new Tuple<string, Host>(accessToken1, host);
                                                            Task.Factory.StartNew((state) =>
                                                            {
                                                                var tuple_a = state as Tuple<string, Host>;
                                                                string accessToken = tuple_a.Item1;
                                                                var a = tuple_a.Item2;

                                                                var myarray = a.XiaoDuCUID.Split(',');
                                                                var a1 = a.SysHotel.WelcomeSpeech;
                                                                var a2 = a.SysHotel.Code;
                                                                var a3 = a.RoomNumber;

                                                                //foreach (string cuid in host.XiaoDuCUID.Split(','))//多个小度英文逗号隔开
                                                                foreach (string cuid in myarray)//多个小度英文逗号隔开
                                                                {
                                                                    //XiaoDuOperation.UploadWebhook(accessToken, cuid, host.SysHotel.WelcomeSpeech, host.SysHotel.Code, host.RoomNumber);
                                                                    XiaoDuOperation.UploadWebhook(accessToken, cuid, a1, a2, a3);

                                                                    Interface3Log w1 = new Interface3Log();
                                                                    w1.HotelCode = a2;
                                                                    w1.RoomNumber = a3;
                                                                    w1.TriggerTime = DateTime.Now;
                                                                    w1.CommandType = ChangLiangValue.XiaoDu;

                                                                    WelcomeAction w2 = new WelcomeAction();
                                                                    w2.VoiceDeviceClass = "小度";
                                                                    w2.CUID = cuid;
                                                                    w2.CommandType = "欢迎词";
                                                                    w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(w2) };

                                                                    var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                                                                    CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
                                                                }
                                                            }, ttt);
                                                        }
                                                        else if (flag == 0)
                                                        {
                                                            if (host.SysHotel.IsPowerOffResetXiaoDu)//断电重置小度
                                                            {

                                                                var ttt = new Tuple<string, Host>(accessToken1, host);
                                                                Task.Factory.StartNew((state) =>
                                                                {

                                                                    var tuple_a = state as Tuple<string, Host>;
                                                                    string accessToken = tuple_a.Item1;
                                                                    var a = tuple_a.Item2;

                                                                    var myarray = a.XiaoDuCUID.Split(',');
                                                                    var a1 = a.SysHotel.WelcomeSpeech;
                                                                    var a2 = a.SysHotel.Code;
                                                                    var a3 = a.RoomNumber;
                                                                    //foreach (string cuid in host.XiaoDuCUID.Split(','))//多个小度英文逗号隔开
                                                                    foreach (string cuid in myarray)//多个小度英文逗号隔开
                                                                    {
                                                                        //XiaoDuOperation.PostWebRequestToXiaoDu(accessToken, cuid, new XiaoDuParamJson() { method = "reset" }, host.SysHotel.Code, host.RoomNumber);//重置小度
                                                                        XiaoDuOperation.PostWebRequestToXiaoDu(accessToken, cuid, new XiaoDuParamJson() { method = "reset" }, a2, a3);//重置小度

                                                                        Interface3Log w1 = new Interface3Log();
                                                                        w1.HotelCode = a2;
                                                                        w1.RoomNumber = a3;
                                                                        w1.TriggerTime = DateTime.Now;
                                                                        w1.CommandType = ChangLiangValue.XiaoDu;

                                                                        WelcomeAction w2 = new WelcomeAction();
                                                                        w2.VoiceDeviceClass = "小度";
                                                                        w2.CUID = cuid;
                                                                        w2.CommandType = "断电重置";
                                                                        //w1.ActionData = new HttpActionData() { RequestData = w2 };
                                                                        w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(w2) };

                                                                        var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                                                                        CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
                                                                    }
                                                                }, ttt);
                                                            }
                                                            else if (!string.IsNullOrEmpty(host.SysHotel.GoodbyeSpeech))//断电，播放离房提示
                                                            {

                                                                var ttt = new Tuple<string, Host>(accessToken1, host);
                                                                Task.Factory.StartNew((state) =>
                                                                {
                                                                    var tuple_a = state as Tuple<string, Host>;
                                                                    string accessToken = tuple_a.Item1;
                                                                    var a = tuple_a.Item2;
                                                                    var myarray = a.XiaoDuCUID.Split(',');
                                                                    var a1 = a.SysHotel.GoodbyeSpeech;
                                                                    var a2 = a.SysHotel.Code;
                                                                    var a3 = a.RoomNumber;
                                                                    //foreach (string cuid in host.XiaoDuCUID.Split(','))//多个小度英文逗号隔开
                                                                    foreach (string cuid in myarray)//多个小度英文逗号隔开
                                                                    {
                                                                        //XiaoDuOperation.UploadWebhook(accessToken, cuid, host.SysHotel.GoodbyeSpeech, host.SysHotel.Code, host.RoomNumber);
                                                                        XiaoDuOperation.UploadWebhook(accessToken, cuid, a1, a2, a3);

                                                                        Interface3Log w1 = new Interface3Log();
                                                                        w1.HotelCode = a2;
                                                                        w1.RoomNumber = a3;
                                                                        w1.TriggerTime = DateTime.Now;
                                                                        w1.CommandType = ChangLiangValue.XiaoDu;

                                                                        WelcomeAction w2 = new WelcomeAction();
                                                                        w2.VoiceDeviceClass = "小度";
                                                                        w2.CUID = cuid;
                                                                        w2.CommandType = "欢送词";

                                                                        w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(w2) };
                                                                        //w1.ActionData = new HttpActionData() { RequestData = w2 };

                                                                        var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                                                                        CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
                                                                    }
                                                                }, ttt);
                                                            }
                                                        }
                                                    }
                                                }

                                                //2、如果有绑定天猫精灵，天猫精灵处理
                                                if (!string.IsNullOrEmpty(host.TianMaoCUID))
                                                {
                                                    if (flag == 1 && !string.IsNullOrEmpty(host.SysHotel.WelcomeSpeech))//取电打开时，播放欢迎词
                                                    {
                                                        if (host.SysHotel.Code.Equals("1197"))
                                                        {
                                                            logger.Error("天猫机器人调用：取电Flag= " + flag + ", 房间号：" + host.RoomNumber);
                                                        }
                                                        else
                                                        {
                                                            Task.Factory.StartNew((state) =>
                                                            {
                                                                var hhh = state as Host;
                                                                var a = hhh.TianMaoCUID.Split(',');

                                                                var b = hhh.SysHotel.WelcomeSpeech;
                                                                string bb = hhh.SysHotel.WelcomeBGM;
                                                                //if (!string.IsNullOrEmpty(bb))
                                                                //{
                                                                //    bb = "https://www.boonlive-rcu.com/welcomebgm/" + bb;
                                                                //}
                                                                var c = hhh.SysHotel.Code;
                                                                var d = hhh.RoomNumber;
                                                                var hotelid = hhh.SysHotel.ID;

                                                                foreach (string cuid in a)//多个英文逗号隔开
                                                                {
                                                                    //if (!string.IsNullOrEmpty(bb))
                                                                    //{
                                                                    //    TianMaoOperation.PostWebRequestToTianMao("PushWelcome",
                                                                    //        Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = cuid.Split('&')[0], RoomNo = cuid.Split('&')[1], WelcomeText = b, MusicUrl = bb }), c, d);//通知天猫精灵播放欢迎词
                                                                    //}
                                                                    //else
                                                                    //{
                                                                    //    TianMaoOperation.PostWebRequestToTianMao("PushWelcome",
                                                                    //        Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = cuid.Split('&')[0], RoomNo = cuid.Split('&')[1], WelcomeText = b }), c, d);//通知天猫精灵播放欢迎词
                                                                    //}
                                                                    if (!string.IsNullOrEmpty(bb))
                                                                    {
                                                                        string ffg = "https://www.boonlive-rcu.com/welcomebgm/" + bb;
                                                                        TianMaoOperation.PostWebRequestToTianMao("PushWelcome",
                                                                             Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = cuid.Split('&')[0], RoomNo = cuid.Split('&')[1], WelcomeText = b, WelcomeMusicUrl = ffg }), c, d);//通知天猫精灵播放欢迎词
                                                                    }
                                                                    else
                                                                    {
                                                                        TianMaoOperation.PostWebRequestToTianMao("PushWelcome",
                                                                            Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = cuid.Split('&')[0], RoomNo = cuid.Split('&')[1], WelcomeText = b }), c, d);//通知天猫精灵播放欢迎词
                                                                    }


                                                                    Interface3Log w1 = new Interface3Log();
                                                                    w1.HotelCode = c;
                                                                    w1.RoomNumber = d;
                                                                    w1.TriggerTime = DateTime.Now;
                                                                    w1.CommandType = ChangLiangValue.TianMao;

                                                                    WelcomeAction w2 = new WelcomeAction();
                                                                    w2.VoiceDeviceClass = "天猫";
                                                                    w2.CUID = cuid;
                                                                    w2.CommandType = "欢送词";


                                                                    w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(w2) };
                                                                    //w1.ActionData = new HttpActionData() { RequestData = w2 };

                                                                    var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                                                                    CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
                                                                }
                                                            }, host);
                                                        }
                                                    }
                                                    else if (flag == 0)
                                                    {
                                                        if (host.SysHotel.IsPowerOffResetXiaoDu)//断电重置
                                                        {
                                                            Task.Factory.StartNew((state) =>
                                                            {
                                                                var hhh = state as Host;
                                                                var a = hhh.TianMaoCUID.Split(',');
                                                                var b = hhh.SysHotel.WelcomeSpeech;
                                                                var c = hhh.SysHotel.Code;
                                                                var d = hhh.RoomNumber;
                                                                foreach (string cuid in a)//多个英文逗号隔开
                                                                {

                                                                    string c1 = cuid.Split('&')[0];
                                                                    string c2 = cuid.Split('&')[1];
                                                                    if (!string.IsNullOrEmpty(c1) && !string.IsNullOrEmpty(c2))
                                                                    {
                                                                        TianMaoOperation.PostWebRequestToTianMao("CheckoutWithAK",
                                                                            Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = c1, RoomNo = c2 }), c, d);//重置天猫精灵
                                                                    }

                                                                    Interface3Log w1 = new Interface3Log();
                                                                    w1.HotelCode = c;
                                                                    w1.RoomNumber = d;
                                                                    w1.TriggerTime = DateTime.Now;
                                                                    w1.CommandType = ChangLiangValue.TianMao;

                                                                    WelcomeAction w2 = new WelcomeAction();
                                                                    w2.VoiceDeviceClass = "天猫";
                                                                    w2.CUID = cuid;
                                                                    w2.CommandType = "断电重置";


                                                                    w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(w2) };
                                                                    //w1.ActionData = new HttpActionData() { RequestData = w2 };

                                                                    var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                                                                    CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
                                                                }
                                                            }, host);
                                                        }
                                                        else if (!string.IsNullOrEmpty(host.SysHotel.GoodbyeSpeech))//取电关闭时，播放离房提示
                                                        {
                                                            Task.Factory.StartNew((state) =>
                                                            {
                                                                var hhh = state as Host;
                                                                var a = hhh.TianMaoCUID.Split(',');

                                                                var b = hhh.SysHotel.GoodbyeSpeech;
                                                                var c = hhh.SysHotel.Code;
                                                                var d = hhh.RoomNumber;
                                                                //foreach (string cuid in host.TianMaoCUID.Split(','))//多个英文逗号隔开
                                                                //{
                                                                //    TianMaoOperation.PostWebRequestToTianMao("PushWelcome",
                                                                //        Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = cuid.Split('&')[0], RoomNo = cuid.Split('&')[1], WelcomeText = host.SysHotel.GoodbyeSpeech }), host.SysHotel.Code, host.RoomNumber);//通知天猫精灵播放离房提示
                                                                //}

                                                                foreach (string cuid in a)//多个英文逗号隔开
                                                                {
                                                                    TianMaoOperation.PostWebRequestToTianMao("PushWelcome",
                                                                        Newtonsoft.Json.JsonConvert.SerializeObject(new
                                                                        {
                                                                            HotelId = cuid.Split('&')[0],
                                                                            RoomNo = cuid.Split('&')[1],
                                                                            WelcomeText = b
                                                                        }), c, d);//通知天猫精灵播放离房提示

                                                                    Interface3Log w1 = new Interface3Log();
                                                                    w1.HotelCode = c;
                                                                    w1.RoomNumber = d;
                                                                    w1.TriggerTime = DateTime.Now;
                                                                    w1.CommandType = ChangLiangValue.TianMao;


                                                                    WelcomeAction w2 = new WelcomeAction();
                                                                    w2.VoiceDeviceClass = "天猫";
                                                                    w2.CUID = cuid;
                                                                    w2.CommandType = "欢送词";

                                                                    w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(w2) };
                                                                    //w1.ActionData = new HttpActionData() { RequestData = w2 };
                                                                    var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                                                                    CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);
                                                                }
                                                            }, host);
                                                        }
                                                    }
                                                }
                                            }

                                            //3、取电或断电时季节空调处理
                                            HotelSeason hotelSeason = null;
                                            string KKKAAA = "Season_" + host.SysHotel.ID;
                                            string KongZhi = "Season_WuKong" + host.SysHotel.ID;
                                            object ShiFouWeiKong = MemoryCacheHelper.Get(KongZhi);
                                            int bf = 1;
                                            if (ShiFouWeiKong != null)
                                            {
                                                bf = (int)ShiFouWeiKong;
                                            }
                                            if (bf == 0)
                                            {
                                                var UIO = MemoryCacheHelper.Get(KKKAAA);
                                                if (UIO != null)
                                                {
                                                    hotelSeason = (HotelSeason)UIO;
                                                }
                                                else
                                                {
                                                    hotelSeason = HotelSeasonRepository.LoadByHotelID(host.SysHotel.ID);//获取该酒店下季节设置记录
                                                    if (hotelSeason != null)
                                                    {
                                                        MemoryCacheHelper.Set(KongZhi, 0, DateTimeOffset.Now.AddMinutes(20));
                                                        MemoryCacheHelper.Set(KKKAAA, hotelSeason, DateTimeOffset.Now.AddMinutes(20));
                                                    }
                                                    else
                                                    {
                                                        MemoryCacheHelper.Set(KongZhi, 1, DateTimeOffset.Now.AddMinutes(20));
                                                    }
                                                }
                                            }
                                            else
                                            {

                                                hotelSeason = HotelSeasonRepository.LoadByHotelID(host.SysHotel.ID);//获取该酒店下季节设置记录
                                                if (hotelSeason != null)
                                                {
                                                    MemoryCacheHelper.Set(KongZhi, 0, DateTimeOffset.Now.AddMinutes(20));
                                                    MemoryCacheHelper.Set(KKKAAA, hotelSeason, DateTimeOffset.Now.AddMinutes(20));
                                                }
                                                else
                                                {
                                                    MemoryCacheHelper.Set(KongZhi, 1, DateTimeOffset.Now.AddMinutes(20));
                                                }
                                            }

                                            if (hotelSeason != null)
                                            {
                                                int conditonType = (flag == 1 ? 2 : 3);
                                                List<HotelAirControl> list = HotelAirControlRepository.LoadAll(host.SysHotel.ID, conditonType, true);
                                                List<HostModal> hostModals = HostModalRepository.LoadByHostID(host.ID).Where(r => r.Modal.Type == DeviceType.AirConditioner && r.Modal.ActiveIndicator).ToList();//获取启用的空调回路
                                                if (list.Count > 0 && hostModals.Count > 0)
                                                {
                                                    System.Reflection.PropertyInfo[] properties = typeof(HotelSeason).GetProperties();//获取所有属性
                                                    foreach (HotelAirControl item in list)
                                                    {
                                                        foreach (System.Reflection.PropertyInfo prop in properties)//遍历属性
                                                        {
                                                            if (prop.Name == "Month" + DateTime.Now.Month.ToString() && Convert.ToInt16(prop.GetValue(hotelSeason, null)) == item.Season)//当前月份所属该季节，则发送命令给rcu设置空调
                                                            {
                                                                System.Threading.Thread.Sleep(item.DelayTime * 1000);//延迟执行

                                                                var D2 = item;
                                                                foreach (HostModal hostModal1 in hostModals)
                                                                {
                                                                    Device device1 = new Device();
                                                                    device1.Address = hostModal1.Modal.ModalAddress;
                                                                    device1.AddressType = AddressType.DeviceAddress;
                                                                    device1.Type = DeviceType.AirConditioner;
                                                                    device1.Status = (byte)D2.Status;
                                                                    device1.Brightness = 0;
                                                                    device1.Temperature = (byte)D2.SettingTemp;
                                                                    device1.FanSpeed = (byte)D2.FanSpeed;
                                                                    device1.Mode = (byte)D2.Mode;
                                                                    device1.Valve = 0;
                                                                    device1.AirExecMode = (D2.Status << 14) + (D2.Mode << 12) + (D2.FanSpeed << 10) + (0 << 8) + D2.SettingTemp;//空调执行方式和内容
                                                                    //这里只需要host的mac和number或者 ip
                                                                    DeviceControlReceiver.Send(host, device1);
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        #endregion
                                        #endregion
                                        break;
                                }
                                break;
                                #endregion
                            case DeviceType.CarbonVIP: //碳达人
                                #region Carbon
                                var iii = device.Value.StatusReceiver;

                                byte[] bbbddd = BitConverter.GetBytes(iii);
                                byte[] bba = new byte[] { bbbddd[1] };
                                BitArray bitArray = new BitArray(bba);

                                //这个是状态
                                var qqq1 = bitArray.Cast<bool>().Take(4).ToArray();

                                //节能状态
                                byte hhhg1 = Tools.CombineBitsToByte(qqq1[3], qqq1[2], qqq1[1], qqq1[0]);

                                //open
                                if (hhhg1 == 0x01)
                                {
                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        //sbSQL.Append("Status=1,Brightness=100,");
                                        //MemoryModal.Status = 1;
                                    }
                                }
                                //close
                                else if (hhhg1 == 0x02)
                                {
                                    if (hostModal.Status != status)//设备有变化时才去更改状态，窗帘6是停，其他是关
                                    {
                                        flag = 0;
                                        hostModal.Status = status;

                                        //MemoryModal.Status = status;
                                    }
                                }
                                else
                                {

                                }
                                break;
                                #endregion
                            case DeviceType.AirConditioner://空调
                                #region 空调
                                //BitArray bit = new BitArray(device.Value.StatusReceiver);
                                ushort StatusReceiver = device.Value.StatusReceiver;
                                status = device.Value.StatusReceiver >> 15;//开关
                                int mode = (device.Value.StatusReceiver >> 13) & 0x03;//模式
                                int fanSpeed = (device.Value.StatusReceiver >> 11) & 0x03;//风速
                                int valve = (device.Value.StatusReceiver >> 10) & 0x01;//阀门
                                int temperature = (device.Value.StatusReceiver >> 5) & 0x1F;//设定温度
                                int currentTemp = device.Value.StatusReceiver & 0x01F;//当前温度（室内温度）

                                //status = StatusReceiver >> 15;//开关
                                //int mode = (StatusReceiver >> 12) & 0x03;//模式
                                //int fanSpeed = (StatusReceiver >> 11) & 0x03;//风速
                                //int valve = (StatusReceiver >> 10) & 0x01;//阀门
                                //int temperature = (StatusReceiver >> 5) & 0x1F;//设定温度
                                //int currentTemp = StatusReceiver & 0x01F;//当前温度（室内温度）

                                if (status == 1)//设备开
                                {
                                    string ADDDDD = device.Value.Address;
                                    string Key = CacheKey.KongTiaoAlert + "_" + HOSTNUMBER + "_" + ADDDDD;
                                    AirConditionAlert alert_d = new AirConditionAlert();
                                    alert_d.HostNumber = HOSTNUMBER;
                                    alert_d.HotelCode = HOTEL_CODE;
                                    alert_d.DeviceAddress = ADDDDD;
                                    alert_d.SetTemperature = temperature;
                                    alert_d.CurrentTemperature = currentTemp;
                                    alert_d.UpdateDateTime = DateTime.Now;
                                    //if (temperature != currentTemp)
                                    //{
                                    //    var take_air = CSRedisCacheHelper.Get_Partition<AirConditionAlert>(Key);
                                    //    if (!take_air.Equals(default(AirConditionAlert)))
                                    //    {
                                    //        // 结构体为空（即所有字段都为默认值）
                                    //    }
                                    //    else
                                    //    {
                                    //        CSRedisCacheHelper.Set_PartitionWithTime(Key, alert_d, 30);
                                    //    }
                                    //}
                                    //else
                                    //{
                                    //    CSRedisCacheHelper.Del_Partition(Key);
                                    //}


                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        hostModal.Brightness = 100;
                                        //sbSQL.Append("Status=1,Brightness=100,");

                                        //MemoryModal.Status = 1;
                                        //MemoryModal.Brightness = 100;
                                    }
                                    //如果设备状态为开 
                                    //而且当前房间 插卡
                                    //如果设置有 延时关闭就产生条任务
                                    string TakeCardKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000001";
                                    int id = host.SysHotel.ID;
                                    int hostid = host.ID;
                                    string hotelcode = host.SysHotel.Code;
                                    string roomnum = host.RoomNumber;
                                    string LieKey = CacheKey.LieECOKey + "_" + id;
                                    var CardStatus = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(TakeCardKey);
                                    if (CardStatus != null)
                                    {
                                        int SStatus = CardStatus.Status;
                                        //如果取电为开
                                        if (SStatus == 1)
                                        {
                                            List<LieECO> list = null;
                                            var takedata = CSRedisCacheHelper.Get_Partition<List<LieECO>>(LieKey, 1);
                                            if (takedata != null)
                                            {
                                                list = takedata;
                                            }
                                            if (list != null && list.Count > 0)
                                            {
                                                //获取时间
                                                foreach (LieECO item in list)
                                                {
                                                    string st = item.StartTime;
                                                    string et = item.EndTime;
                                                    var st1 = st.Split(':');
                                                    int hh = 0;
                                                    int.TryParse(st1[0], out hh);
                                                    int mm = 0;
                                                    int.TryParse(st1[1], out mm);

                                                    var et1 = et.Split(':');
                                                    int hh1 = 0;
                                                    int.TryParse(et1[0], out hh1);
                                                    int mm1 = 0;
                                                    int.TryParse(et1[1], out mm1);


                                                    var n = DateTime.Now;
                                                    int y = n.Year;
                                                    int m = n.Month;
                                                    int d = n.Day;

                                                    var st2 = new DateTime(y, m, d, hh, mm, 0);
                                                    var et2 = new DateTime(y, m, d, hh1, mm1, 0);

                                                    if (DateTime.Now >= st2 && DateTime.Now <= et2)
                                                    {
                                                        int delay = item.DelayTime;
                                                        //string LieECOTaskKey = CacheKey.LieECOTask + "_" + System.Guid.NewGuid().ToString("N");
                                                        string LieECOTaskKey = CacheKey.LieECOTask + "_" + hotelcode + "_" + roomnum;

                                                        int finallyV = temperature;
                                                        if (item.AbsEnable)
                                                        {
                                                            int ABSV = item.AbsValue;
                                                            finallyV = ABSV;
                                                        }
                                                        if (item.RelativeEnable)
                                                        {
                                                            int ReaV = item.RelativeValue;
                                                            //如果内存中取出的设定温度和 当前温控器的设定温度不一致，说明设置温度有变化
                                                            if (hostModal.AirConditionData.SettingTemp != temperature)
                                                            {
                                                                if (mode == 1)
                                                                {
                                                                    //如果是制冷 ，那就将温度调高一些
                                                                    finallyV = temperature + ReaV;
                                                                    //设置温度也要变化，不然会一直变
                                                                }
                                                                else if (mode == 2)
                                                                {
                                                                    //如果是制热就不用管
                                                                    finallyV = temperature - ReaV;
                                                                }
                                                                else
                                                                {
                                                                    finallyV = temperature;
                                                                }
                                                                temperature = finallyV;
                                                            }
                                                        }
                                                        LieECOTaskExtra LE = new LieECOTaskExtra();
                                                        LE.MissionKey = LieECOTaskKey;
                                                        LE.HostNUMBER = HOSTNUMBER;
                                                        LE.MAC = HOST_MAC;
                                                        LE.FanSpeed = fanSpeed;
                                                        LE.Mode = mode;
                                                        LE.ModalAddress = device.Value.Address;
                                                        LE.SetTemperatureValue = finallyV;
                                                        CSRedisCacheHelper.Set_Partition<LieECOTaskExtra>(LieECOTaskKey, LE, 1);

                                                        string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                        KongTiaoTimer k = new KongTiaoTimer();
                                                        k.HotelID = id;
                                                        k.HostID = hostid;
                                                        k.HotelCode = hotelcode;
                                                        k.RoomNo = roomnum;
                                                        k.MissonKey = LieECOTaskKey;
                                                        k.IsCancel = 0;
                                                        k.CreateTime = ti;
                                                        k.StartTime = ti;
                                                        k.EndTime = DateTime.Now.AddMinutes(delay).ToString("yyyy-MM-dd HH:mm:ss");
                                                        k.CreateDate = DateTime.Now.ToString("yyyy-MM-dd");

                                                        MissionRequestData UUA = new MissionRequestData();
                                                        UUA.DelayTimer = delay;
                                                        UUA.KT = k;

                                                        string jsstr = Newtonsoft.Json.JsonConvert.SerializeObject(UUA);

                                                        //给 任务管理系统 发送消息
                                                        var client1 = new RestClient(Missionsys_Address);
                                                        var request1 = new RestRequest("api/index", Method.POST);

                                                        logger.Error("ECO系统发送了数据：" + jsstr + Missionsys_Address + "API/Index");

                                                        request1.AddParameter("jsonData", jsstr);

                                                        client1.ExecuteAsync(request1, (response) => { });
                                                    }

                                                }
                                            }
                                        }
                                    }

                                }
                                else//设备关
                                {
                                    if (hostModal.Status != 2)//设备有变化时才去更改状态
                                    {
                                        flag = 0;
                                        hostModal.Status = 2;
                                        hostModal.Brightness = 0;
                                        //sbSQL.Append("Status=2,Brightness=0,");

                                        //MemoryModal.Status = 2;
                                        //MemoryModal.Brightness = 0;
                                    }
                                }
                                hostModal.AirConditionData.AirStatus = status;
                                hostModal.AirConditionData.Mode = mode;
                                hostModal.AirConditionData.FanSpeed = fanSpeed;
                                hostModal.AirConditionData.Valve = valve == 1 ? 1 : 2;
                                hostModal.AirConditionData.UpdateTime = now;

                                //MemoryModal.Mode = mode;
                                //MemoryModal.FanSpeed = fanSpeed;
                                //MemoryModal.Valve = valve == 1 ? 1 : 2;

                                if (temperature == 0 || temperature > 32)
                                {
                                    hostModal.AirConditionData.SettingTemp = 32;
                                    //MemoryModal.SettingTemp = 32;
                                }
                                else if (temperature < 16)
                                {
                                    hostModal.AirConditionData.SettingTemp = 16;

                                    //MemoryModal.SettingTemp = 16;
                                }
                                else
                                {
                                    hostModal.AirConditionData.SettingTemp = temperature;

                                    //MemoryModal.SettingTemp = temperature;
                                }
                                //hostModal.SettingTemp = temperature == 0 ? 32 : temperature;
                                //sbSQL.Append("SettingTemp=" + hostModal.SettingTemp + ",");
                                if (currentTemp == 0 || currentTemp > 32)
                                {
                                    hostModal.AirConditionData.CurrentTemp = 32;

                                    //MemoryModal.CurrentTemp = 32;
                                }
                                else if (currentTemp < 16)
                                {
                                    hostModal.AirConditionData.CurrentTemp = 16;

                                    //MemoryModal.CurrentTemp = 16;
                                }
                                else
                                {
                                    hostModal.AirConditionData.CurrentTemp = currentTemp;

                                    //MemoryModal.CurrentTemp = currentTemp;
                                }
                                //hostModal.CurrentTemp = currentTemp == 0 ? 32 : currentTemp;
                                //sbSQL.Append("CurrentTemp=" + hostModal.CurrentTemp + ",");
                                break;
                                #endregion
                            case DeviceType.FloorHot://地暖
                                #region 地暖
                                status = (device.Value.StatusReceiver >> 15) & 0x01;//开关
                                mode = (device.Value.StatusReceiver >> 13) & 0x03;//模式
                                valve = (device.Value.StatusReceiver >> 12) & 0x01;//阀门
                                temperature = (device.Value.StatusReceiver >> 6) & 0x3F;//设定温度
                                currentTemp = device.Value.StatusReceiver & 0x03F;//当前温度（室内温度）
                                if (status == 1)//设备开
                                {
                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        hostModal.Brightness = 100;
                                        //sbSQL.Append("Status=1,Brightness=100,");

                                        //MemoryModal.Status = 1;
                                        //MemoryModal.Brightness = 100;
                                    }
                                }
                                else//设备关
                                {
                                    if (hostModal.Status != 2)//设备有变化时才去更改状态
                                    {
                                        flag = 0;
                                        hostModal.Status = 2;
                                        hostModal.Brightness = 0;
                                        //sbSQL.Append("Status=2,Brightness=0,");

                                        //MemoryModal.Status = 2;
                                        //MemoryModal.Brightness = 0;
                                    }
                                }
                                hostModal.AirConditionData.SettingTemp = temperature == 0 ? 32 : temperature;
                                //sbSQL.Append("SettingTemp=" + hostModal.SettingTemp + ",");
                                hostModal.AirConditionData.Mode = mode;
                                //sbSQL.Append("Mode=" + hostModal.Mode + ",");
                                hostModal.AirConditionData.Valve = valve == 1 ? 1 : 2;
                                //sbSQL.Append("Valve=" + hostModal.Valve + ",");
                                hostModal.AirConditionData.CurrentTemp = currentTemp == 0 ? 32 : currentTemp;

                                //sbSQL.Append("CurrentTemp=" + hostModal.CurrentTemp + ",");


                                //MemoryModal.SettingTemp = temperature == 0 ? 32 : temperature;
                                //MemoryModal.Mode = mode;
                                //MemoryModal.Valve = valve == 1 ? 1 : 2;
                                //MemoryModal.CurrentTemp = currentTemp == 0 ? 32 : currentTemp;
                                #endregion
                                break;
                            #region 下面的暂时不关心
                            case DeviceType.TV://电视
                                status = device.Value.StatusReceiver & 0x00FF;
                                if (status == 1)//设备开
                                {
                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        hostModal.Brightness = 100;
                                        //sbSQL.Append("Status=1,Brightness=100,");

                                        //MemoryModal.Status = 1;
                                        //MemoryModal.Brightness = 100;
                                    }
                                }
                                else//设备关
                                {
                                    if (hostModal.Status != status)//设备有变化时才去更改状态，窗帘6是停，其他是关
                                    {
                                        flag = 0;
                                        hostModal.Status = status;
                                        hostModal.Brightness = 0;
                                        //sbSQL.Append("Status=" + status + ",Brightness=0,");

                                        //MemoryModal.Status = status;
                                        //MemoryModal.Brightness = 0;
                                    }
                                }
                                break;
                            case DeviceType.Music://音乐
                                status = device.Value.StatusReceiver & 0x00FF;//开关
                                brightness = (device.Value.StatusReceiver >> 12) & 0x0F;//音量
                                mode = (device.Value.StatusReceiver >> 8) & 0x0F;//选项
                                if (status == 1)//设备开
                                {
                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        //sbSQL.Append("Status=1,");

                                        //MemoryModal.Status = 1;
                                    }
                                    hostModal.Brightness = brightness;

                                    //MemoryModal.Brightness = brightness;
                                    //sbSQL.Append("Brightness=" + hostModal.Brightness + ",");
                                }
                                else//设备关
                                {
                                    if (hostModal.Status != 2)//设备有变化时才去更改状态
                                    {
                                        flag = 0;
                                        hostModal.Status = 2;
                                        hostModal.Brightness = 0;
                                        //sbSQL.Append("Status=2,Brightness=0,");

                                        //MemoryModal.Status = 2;
                                        //MemoryModal.Brightness = 0;
                                    }
                                }
                                hostModal.AirConditionData.Mode = mode;
                                //sbSQL.Append("Mode=" + hostModal.Mode + ",");
                                //MemoryModal.Mode = mode;
                                break;
                            case DeviceType.WXLock://微信锁
                                status = device.Value.StatusReceiver & 0x00FF;
                                if (status == 1)//设备开
                                {
                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        //sbSQL.Append("Status=1,");

                                        //MemoryModal.Status = 1;
                                    }
                                }
                                else//设备关
                                {
                                    if (hostModal.Status != 2)//设备有变化时才去更改状态
                                    {
                                        flag = 0;
                                        hostModal.Status = 2;
                                        //sbSQL.Append("Status=2,");

                                        //MemoryModal.Status = 2;
                                    }
                                }
                                //更新主机主表
                                if (hostModal.Modal.Sort == 1)//.ModalAddress == "020001000")
                                {
                                    if (host.LockStatus != status)
                                    {
                                        HostRepository.SetLockStatus(host, status); ;
                                    }
                                }
                                break;
                            case DeviceType.ColorTemp://色温                                
                                #region 色温
                                status = device.Value.StatusReceiver & 0x00FF;
                                brightness = device.Value.StatusReceiver >> 8;//亮度或者色温
                                if (status == 1)//设备开
                                {
                                    if (hostModal.Status != 1)//设备有变化时才去更改状态
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        hostModal.Brightness = brightness;
                                        //sbSQL.Append("Status=1,Brightness=100,");

                                        //MemoryModal.Status = 1;
                                        //MemoryModal.Brightness = brightness;
                                    }
                                }
                                else//设备关
                                {
                                    if (status == 3)
                                    {
                                        flag = 1;
                                        hostModal.Status = 1;
                                        hostModal.AirConditionData.SettingTemp = brightness;//更新色温


                                        //MemoryModal.Status = 1;
                                        //MemoryModal.SettingTemp = brightness;
                                    }
                                    else if (hostModal.Status != status)//设备有变化时才去更改状态，窗帘6是停，其他是关
                                    {
                                        flag = 0;
                                        hostModal.Status = status;
                                        hostModal.Brightness = brightness;
                                        //sbSQL.Append("Status=" + status + ",Brightness=0,");

                                        //MemoryModal.Status = status;
                                        //MemoryModal.Brightness = brightness;
                                    }
                                }
                                break;
                                #endregion
                            #endregion
                        }
                        #region 这里

                        CSRedisCacheHelper.Set_Partition<HostModal_Cache>(KKey, hostModal);

                        //只有服务信息才会入库
                        bool isonly_serviceinfo = true;
                        //if (hostModal.ModalType == DeviceType.ServiceInfo)
                        if (isonly_serviceinfo)
                        {

                            HostModal FinallyData = new HostModal();
                            FinallyData.HostID = hostModal.HostID;
                            FinallyData.Status = hostModal.Status;
                            FinallyData.Brightness = hostModal.Brightness;
                            FinallyData.CurrentTemp = hostModal.AirConditionData.CurrentTemp;
                            FinallyData.FanSpeed = hostModal.AirConditionData.FanSpeed;
                            FinallyData.Mode = hostModal.AirConditionData.Mode;
                            FinallyData.SettingTemp = hostModal.AirConditionData.SettingTemp;
                            FinallyData.UpdateTime = hostModal.UpdateTime;
                            FinallyData.Valve = hostModal.AirConditionData.Valve;

                            FinallyData.Modal = new RoomTypeModal()
                            {
                                ID = hostModal.Modal.ID,
                                Name = hostModal.Modal.Name,
                                ModalAddress = hostModal.Modal.ModalAddress,
                                ActiveIndicator = hostModal.Modal.ActiveIndicator,
                                Sort = hostModal.Modal.Sort
                            };
                            FinallyData.Modal.RoomType = new RoomType()
                            {
                                ID = hostModal.Modal.RoomTypeID
                            };
                            FinallyData.Modal.ID = hostModal.Modal.ID;
                            FinallyData.UpdateTime = now;

                            #region 有可能有异常
                            try
                            {
                                HostModalRecord hostModalRecord;
                                switch (flag)
                                {
                                    case 0://0关闭设备
                                        if (hostModal.UpdateTime.HasValue)
                                        {
                                            hostModal.Time += Convert.ToInt32((now - hostModal.UpdateTime.Value).TotalMinutes);
                                        }
                                        hostModal.UpdateTime = now;
                                        FinallyData.UpdateTime = now;
                                        //阿宝添加内存
                                        try
                                        {
                                            HostModalRepository.Update(FinallyData);//sbSQL.ToString());
                                        }
                                        catch (Exception)
                                        {
                                            logger.Error(FinallyData.HostID + ":" + host.SysHotel.Code + " " + hostModal.Modal.ModalAddress);
                                        }
                                        //CSRedisCacheHelper.Set_Partition<HostModal_Cache>(KKey, hostModal);
                                        if (hostModal.Modal.ActiveIndicator)//处理回路状态记录，只记录启用的回路 add by wuzhuihui 20190918
                                        {
                                            hostModalRecord = new HostModalRecord();
                                            hostModalRecord.HostID = host.ID;
                                            hostModalRecord.RoomNumber = host.RoomNumber;
                                            hostModalRecord.RoomTypeID = host.RoomType.ID;
                                            hostModalRecord.RoomTypeModalID = hostModal.Modal.ID;
                                            hostModalRecord.ModalAddress = hostModal.Modal.ModalAddress;
                                            hostModalRecord.StartTime = now;
                                            hostModalRecord.Status = 2;
                                            try
                                            {
                                                HostModalRecordRepository.Save(hostModalRecord);
                                            }
                                            catch (Exception)
                                            {

                                            }
                                        }
                                        break;
                                    case 1://1打开设备且当前设备处于关闭状态
                                        hostModal.UpdateTime = now;
                                        FinallyData.UpdateTime = now;
                                        //阿宝这里修改
                                        try
                                        {
                                            HostModalRepository.Update(FinallyData);//sbSQL.ToString());
                                        }
                                        catch (Exception ex)
                                        {
                                            logger.Error(FinallyData.HostID + ":" + host.SysHotel.Code + " " + hostModal.Modal.ModalAddress);
                                        }
                                        //CSRedisCacheHelper.Set_Partition<HostModal_Cache>(KKey, hostModal);
                                        if (hostModal.Modal.ActiveIndicator)//处理回路状态记录，只记录启用的回路 add by wuzhuihui 20190918
                                        {
                                            hostModalRecord = new HostModalRecord();
                                            hostModalRecord.HostID = host.ID;
                                            hostModalRecord.RoomNumber = host.RoomNumber;
                                            hostModalRecord.RoomTypeID = host.RoomType.ID;
                                            hostModalRecord.RoomTypeModalID = hostModal.Modal.ID;
                                            hostModalRecord.ModalAddress = hostModal.Modal.ModalAddress;
                                            hostModalRecord.StartTime = now;
                                            hostModalRecord.Status = 1;
                                            try
                                            {
                                                HostModalRecordRepository.Save(hostModalRecord);
                                            }
                                            catch (Exception)
                                            {

                                            }
                                        }
                                        break;
                                    case 2://2打开设备且当前设备处于打开状态
                                        hostModal.UpdateTime = now;
                                        FinallyData.UpdateTime = now;
                                        try
                                        {
                                            HostModalRepository.Update(FinallyData);
                                        }
                                        catch (Exception ex)
                                        {
                                            logger.Error(FinallyData.HostID + ":" + host.SysHotel.Code + " " + hostModal.Modal.ModalAddress);
                                        }
                                        //CSRedisCacheHelper.Set_Partition<HostModal_Cache>(KKey, hostModal);
                                        break;
                                }

                                string StatusKey = "RoomStatus_ServerInfo";
                                RCUHost.RCUHostCommon.tools.LanJieData(StatusKey, HOTEL_CODE);
                                CSRedisCacheHelper.Set_Partition<HostModal_Cache>(KKey, hostModal);
                            }
                            catch (Exception ex)
                            {
                                logger.Error("数据处理error: " + ex.Message);
                                logger.Error(FinallyData.HostID + ":" + host.SysHotel.Code + " " + hostModal.Modal.ModalAddress);
                            }
                            #endregion

                        }
                        else
                        {
                            string StatusKey = "RoomStatus_NoWriteDb";
                            RCUHost.RCUHostCommon.tools.LanJieData(StatusKey, HOTEL_CODE);
                        }
                        #endregion


                        //0关闭设备，
                        //1打开设备且当前设备处于关闭状态，
                        //2打开设备且当前设备处于打开状态
                        if (flag == 0 || flag == 1)
                        {

                            ts_deviceitem t1 = new ts_deviceitem();

                            string dizhi = device.Value.Address;
                            t1.dev_type = short.Parse(dizhi.Substring(0, 3));
                            t1.dev_addr = short.Parse(dizhi.Substring(3, 3));
                            t1.dev_loop = short.Parse(dizhi.Substring(6, 3));
                            t1.dev_data = device.Value.StatusReceiver;
                            shebei_changeaction_list.Add(t1);
                        }
                        #region 当设备或服务状态发生变化时，推送给指定的第三方接口
                        if ((flag == 0 || flag == 1) && (!string.IsNullOrEmpty(host.SysHotel.DeviceStatusPushURL)))
                        {

                            if (host.SysHotel.DeviceStatusPushURL.ToLower().IndexOf("wangjile") > -1)//freego过滤
                            {
                                switch (hostModal.Modal.ModalAddress)
                                {
                                    case "004000001"://取电
                                    case "004000002"://勿扰
                                    case "004000003"://清理
                                    case "004000008"://sos
                                        break;
                                    default://其他不上报
                                        continue;
                                }
                            }
                            //阿宝修改的,下面 BUG，有多个设备上报的话，就会出问题
                            Tuple<Host, HostModal_Cache> tup = new Tuple<Host, HostModal_Cache>(host, hostModal);
                            Task.Factory.StartNew((tupobj) =>
                            {
                                Tuple<Host, HostModal_Cache> ttt = tupobj as Tuple<Host, HostModal_Cache>;
                                XuanZhuResponse resp = new XuanZhuResponse();
                                resp.code = ttt.Item1.SysHotel.Code;
                                resp.roomNumber = ttt.Item1.RoomNumber;
                                resp.address = ttt.Item2.Modal.ModalAddress;
                                resp.name = ttt.Item2.Modal.Name;
                                resp.status = ttt.Item2.Status;
                                if (resp.status == 1)
                                {
                                    resp.brightness = ttt.Item2.Brightness;
                                    resp.currentTemp = ttt.Item2.AirConditionData.CurrentTemp;
                                    resp.settingTemp = ttt.Item2.AirConditionData.SettingTemp;
                                    resp.mode = ttt.Item2.AirConditionData.Mode;
                                    resp.fanSpeed = ttt.Item2.AirConditionData.FanSpeed;
                                    resp.valve = ttt.Item2.AirConditionData.Valve;
                                }
                                else
                                {
                                    resp.brightness = 0;
                                    resp.currentTemp = 0;
                                    resp.settingTemp = 0;
                                    resp.mode = 0;
                                    resp.fanSpeed = 0;
                                    resp.valve = 0;
                                }

                                MyHttp.SendHttpData(ttt.Item1.SysHotel.DeviceStatusPushURL, resp);
                            }, tup);

                        }



                        #endregion


                        var codesss = host.SysHotel.Code;
                        #region kafka队列
                        if (XuanZhuHotelData.dataArray.Contains(int.Parse(codesss)))
                        {
                            XuanZhuRequest resp1 = new XuanZhuRequest();
                            resp1.code = host.SysHotel.Code + "@" + host.SysHotel.CreatedDate.ToString("yyyy-MM-dd");
                            resp1.roomNumber = host.RoomNumber;
                            resp1.devicetype = hostModal.ModalType.ToString();
                            resp1.address = hostModal.Modal.ModalAddress;
                            resp1.name = hostModal.Modal.Name;
                            resp1.status = hostModal.Status;
                            if (resp1.status == 1)
                            {
                                resp1.brightness = hostModal.Brightness;
                                resp1.currentTemp = hostModal.AirConditionData.CurrentTemp;
                                resp1.settingTemp = hostModal.AirConditionData.SettingTemp;
                                resp1.mode = hostModal.AirConditionData.Mode;
                                resp1.fanSpeed = hostModal.AirConditionData.FanSpeed;
                                resp1.valve = hostModal.AirConditionData.Valve;
                            }
                            else
                            {
                                resp1.brightness = 0;
                                resp1.currentTemp = 0;
                                resp1.settingTemp = 0;
                                resp1.mode = 0;
                                resp1.fanSpeed = 0;
                                resp1.valve = 0;
                            }
                            var str111 = Newtonsoft.Json.JsonConvert.SerializeObject(resp1);
                            CSRedisCacheHelper.Publish("Redis-XuanZhuKafka", str111);
                        }
                        #endregion

                    }
                    else
                    {
                        string NoKey = CacheKey.HostModalStatus_BoolFilterPrefix + "_" + host.ID + "_" + device.Value.Address;
                        //var expiredata = new Random().Next(10, 50);
                        CSRedisCacheHelper.Set_PartitionWithTime<int>(NoKey, 1, 30);
                        //logger.Error("内存和数据库都不见这条数据：" + KKey);
                    }
                    #endregion
                }
            }

            #region 新版本日志队列

            byte[] OriginalByte = OriginalByteList;
            DeviceActionData d1 = new DeviceActionData();
            d1.ts_ms = Tools.GetUnixTime();
            d1.hotel_id = HOTEL_CODE;
            d1.room_id = ROOMNUMBER;
            d1.device_id = HOSTNUMBER;
            d1.frame_id = frameNo;
            d1.cmd_word = "0E";
            d1.udp_raw = OriginalByte;
            d1.direction = "上报";


            if (yuanshidata.SysLock)
            {
                d1.sys_lock_status = 1;
            }
            else
            {
                d1.sys_lock_status = 2;
            }


            if (yuanshidata.Faults != null && yuanshidata.Faults.Count > 0)
            {
                var F1 = yuanshidata.Faults;
                foreach (var item in F1)
                {
                    string dizhi = item.Value.FaultNo;
                    ts_faultitem t1 = new ts_faultitem();
                    t1.dev_type = short.Parse(dizhi.Substring(0, 3));
                    t1.dev_addr = short.Parse(dizhi.Substring(3, 3));
                    t1.dev_loop = short.Parse(dizhi.Substring(6, 3));
                    t1.error_type = item.Value.Type;
                    t1.error_data = item.Value.Data;
                    exception_list.Add(t1);
                }
            }

            d1.device_list = shebei_changeaction_list;
            d1.fault_list = exception_list;
            d1.report_count = shebei_changeaction_list.Count;
            d1.fault_count = exception_list.Count;

            string sss111 = Newtonsoft.Json.JsonConvert.SerializeObject(d1);
            CSRedisCacheHelper.Publish("redis-0X36-0X0F", sss111);
            #endregion

            StepTongJi.SendInfo(5, "Task中的设备处理代码执行完毕", ContextMessageId, ismonitor);
            devices.Clear();
        }

        /// <summary>
        /// 是否在固定时段内禁用语音机器人
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        private static bool SmartRobotDisable(Host host)
        {
            if (string.IsNullOrEmpty(host.DisableStartTime) || string.IsNullOrEmpty(host.DisableEndTime))
            {
                return false;
            }
            string et = host.DisableEndTime;
            string st = host.DisableStartTime;
            string[] st_a = st.Split(':');
            string[] et_a = et.Split(':');

            int h_st = int.Parse(st_a[0]);
            int M_st = int.Parse(st_a[1]);

            int h_et = int.Parse(et_a[0]);
            int M_et = int.Parse(et_a[1]);

            int y = DateTime.Now.Year;
            int m = DateTime.Now.Month;
            int d = DateTime.Now.Day;
            int hh = DateTime.Now.Hour;
            int mm = DateTime.Now.Minute;
            int ss = DateTime.Now.Second;
            var t1 = new DateTime(y, m, d, h_st, M_st, ss);
            var t2 = new DateTime(y, m, d, h_et, M_et, ss);

            bool ShiJian = false;
            //正常逻辑
            if (t2 >= t1)
            {
                var ti = DateTime.Now;
                //如果当前时间大于 起 小于 至，就代表 确实是 禁用
                if (ti >= t1 && ti <= t2)
                {
                    ShiJian = true;
                }
            }
            else
            {
                var ti = DateTime.Now;
                var zero_ti = new DateTime(y, m, d, 23, 59, 59);
                var zero_ti_0 = new DateTime(y, m, d, 0, 0, 0);
                //var t3 = t2.AddDays(1);

                //如果当前时间 小于0点
                //或者说 当前时间 大于 
                if ((ti > t1 && ti < zero_ti) || ti >= zero_ti_0 && ti <= t2)
                {
                    ShiJian = true;
                }
            }

            bool dis = host.IsWelcomeDisableTime;
            return dis && ShiJian;
        }

        /// <summary>
        /// 碳达人发送数据
        /// </summary>
        /// <param name="host"></param>
        /// <param name="hhhg1"></param>
        private static void CarbonDataSend(Host host, byte hhhg1)
        {

            string PropertyUUID = host.SysHotel.FCS_PropertyID;

            string FCS_RCU_Device_Offline = host.SysHotel.FCS_RCU_Device_Offline;

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

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

            string FCS_MenCi_Open = host.SysHotel.FCS_MenCi_Open;
            string FCS_MenCi_Close = host.SysHotel.FCS_MenCi_Close;

            string FCS_RCU_Online = host.SysHotel.FCS_RCU_Online;
            string FCS_RCU_Offline = host.SysHotel.FCS_RCU_Offline;
            RR.FCS_PushData(FCS_Carbon_UUID, host.FCS_locationUUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, host.SysHotel.Code, host.RoomNumber);

            if (!string.IsNullOrEmpty(host.SysHotel.DeviceStatusPushURL))
            {
                Tuple<Host, byte> tup = new Tuple<Host, byte>(host, hhhg1);
                Task.Factory.StartNew((tupobj) =>
                {
                    Tuple<Host, byte> ttt = tupobj as Tuple<Host, byte>;
                    XuanZhuResponse resp = new XuanZhuResponse();
                    resp.code = ttt.Item1.SysHotel.Code;
                    resp.roomNumber = ttt.Item1.RoomNumber;
                    resp.address = "054000001";
                    resp.name = "碳达人";
                    resp.status = ttt.Item2;


                    //string mns = Newtonsoft.Json.JsonConvert.SerializeObject(resp);
                    //CSRedisCacheHelper.Publish("redis-carbon_trigger", mns);

                    MyHttp.SendHttpData(ttt.Item1.SysHotel.DeviceStatusPushURL, resp);
                    //XuanZhuOperation.ReportService(ttt.Item1.SysHotel.DeviceStatusPushURL, resp);
                }, tup);
            }
        }



        /// <summary>
        /// 处理故障（温控器掉线）
        /// </summary>
        /// <param name="host"></param>
        /// <param name="faults"></param>
        private void ProcessFaults(Host host, ConcurrentDictionary<string, FaultStaus> faults)
        {
            string HotelCode = host.SysHotel.Code;

            string PropertyUUID = host.SysHotel.FCS_PropertyID;

            string FCS_RCU_Device_Offline = host.SysHotel.FCS_RCU_Device_Offline;

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

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

            string FCS_MenCi_Open = host.SysHotel.FCS_MenCi_Open;
            string FCS_MenCi_Close = host.SysHotel.FCS_MenCi_Close;

            string FCS_RCU_Online = host.SysHotel.FCS_RCU_Online;
            string FCS_RCU_Offline = host.SysHotel.FCS_RCU_Offline;
            DateTime now = DateTime.Now;
            bool isInsert = false;
            //StringBuilder sbSQL;
            foreach (var fault in faults)
            {

                var hostModal = HostModalRepository.Get(host.ID, fault.Value.FaultNo);
                if (hostModal == null ||
                    (fault.Value.Type == 1 && !hostModal.Modal.OfflineDisplay) ||
                    (fault.Value.Type == 2 && !hostModal.Modal.LowPowerDisplay) ||
                    hostModal.Modal.Abnormal == false)
                {
                    continue;//回路不存在，或离线不显示，或低电不显示，则不保存 add by jophywu on 20191102
                }
                var record = HostFaultsRepository.Get(host.ID, fault.Value.FaultNo);
                //sbSQL = new StringBuilder();
                //sbSQL.Append("UPDATE tb_HostFaults SET ");
                if (record == null)
                {
                    isInsert = true;
                    record = new HostFaults();
                    record.HostID = host.ID;
                    record.Address = fault.Value.FaultNo;
                    record.AbnormalStatus = 0;//默认在线
                    record.StatusDate = Convert.ToDateTime("1800-1-1");
                    record.AbnormalElectricQty = 100;//默认电量100
                    record.ElectricQtyDate = Convert.ToDateTime("1800-1-1");
                    record.Abnormal3 = 0;//默认电流100
                    record.Abnormal3Date = Convert.ToDateTime("1800-1-1");
                    record.Abnormal4 = 0;//1901故障检测次数，默认0
                    record.Abnormal4Date = Convert.ToDateTime("1800-1-1");
                    record.Abnormal5 = 0;//设备单个回路状态：0正常，1损坏
                    record.Abnormal5Date = Convert.ToDateTime("1800-1-1");
                }
                switch (fault.Value.Type)
                {
                    case 1://状态：1离线,0在线
                        record.AbnormalStatus = fault.Value.Data;
                        record.StatusDate = now;
                        RR.FCS_PushData(FCS_RCU_Device_Offline, host.FCS_locationUUID, PropertyUUID, FCSLoginUrl, FCSLoginUserName, FCSLoginPassWord, host.SysHotel.Code, host.RoomNumber);
                        //sbSQL.Append("AbnormalStatus=" + record.AbnormalStatus + ",StatusDate=GETDATE()");
                        break;
                    case 2://电量
                        record.AbnormalElectricQty = fault.Value.Data;
                        record.ElectricQtyDate = now;
                        //sbSQL.Append("AbnormalElectricQty=" + record.AbnormalElectricQty + ",ElectricQtyDate=GETDATE()");
                        break;
                    case 3://电流（10MA）
                        record.Abnormal3 = fault.Value.Data;
                        record.Abnormal3Date = now;
                        //sbSQL.Append("Abnormal3=" + record.Abnormal3 + ",Abnormal3Date=GETDATE()");
                        break;
                    case 4://1901故障检测次数
                        record.Abnormal4 = fault.Value.Data;
                        record.Abnormal4Date = now;
                        //sbSQL.Append("Abnormal4=" + record.Abnormal4 + ",Abnormal4Date=GETDATE()");
                        break;
                    case 5://设备单个回路状态：0正常，1损坏
                        record.Abnormal5 = fault.Value.Data;
                        record.Abnormal5Date = now;
                        //sbSQL.Append("Abnormal5=" + record.Abnormal5 + ",Abnormal5Date=GETDATE()");
                        break;
                    default:
                        continue;//不保存
                }
                if (isInsert)
                {
                    isInsert = false;
                    HostFaultsRepository.Save(record);
                }
                else
                {
                    //sbSQL.Append(" WHERE ID=" + record.ID);
                    HostFaultsRepository.Update(record);//sbSQL.ToString());
                }
                //保存每一次异常记录
                HostFaultRecords hostFaultRecords = new HostFaultRecords();
                hostFaultRecords.HostID = host.ID;
                hostFaultRecords.RoomNumber = host.RoomNumber;
                hostFaultRecords.RoomTypeID = hostModal.Modal.RoomType.ID;
                hostFaultRecords.RoomTypeModalID = hostModal.Modal.ID;
                hostFaultRecords.ModalAddress = hostModal.Modal.ModalAddress;
                hostFaultRecords.Type = fault.Value.Type;
                hostFaultRecords.Value = fault.Value.Data;
                hostFaultRecords.Date = now;
                HostFaultRecordsRepository.Save(hostFaultRecords);


                XuanZhuResponse resp1 = new XuanZhuResponse()
                {
                    code = host.SysHotel.Code,
                    roomNumber = host.RoomNumber,
                    address = hostModal.Modal.ModalAddress,
                    name = hostModal.Modal.Name,
                    status = hostModal.Status,
                    faultType = fault.Value.Type,
                    faultData = fault.Value.Data
                };
                string KKK = CacheKey.WebChatDeviceFault + "_" + resp1.code + "_" + resp1.roomNumber;
                CSRedisCacheHelper.redis_webchat.HMSet(KKK, resp1.address, resp1);
                //出现异常信息时上报
                if (!string.IsNullOrEmpty(host.SysHotel.FaultPushURL))
                {
                    XuanZhuResponse resp = new XuanZhuResponse()
                    {
                        code = host.SysHotel.Code,
                        roomNumber = host.RoomNumber,
                        address = hostModal.Modal.ModalAddress,
                        name = hostModal.Modal.Name,
                        status = hostModal.Status,
                        faultType = fault.Value.Type,
                        faultData = fault.Value.Data
                    };

                    //XuanZhuResponse_Fault hfault = new XuanZhuResponse_Fault()
                    //    {
                    //        data = resp,
                    //        updatetime = DateTime.Now,
                    //        url = host.SysHotel.FaultPushURL
                    //    };

                    //string FaultKey = CacheKey.FaultKey_;
                    //string FFFFFKey = HotelCode + "_" + host.RoomNumber + "_" + hostModal.Modal.ModalAddress;
                    //CSRedisCacheHelper.HMSet(5, 60, FaultKey, FFFFFKey, resp);
                    //var u = Newtonsoft.Json.JsonConvert.SerializeObject(resp);
                    //logger.Error("logger report fault: "+u);
                    var fault_data = new Tuple<string, XuanZhuResponse>(host.SysHotel.FaultPushURL, resp);
                    Task.Factory.StartNew((State) =>
                    {
                        var DDD = State as Tuple<string, XuanZhuResponse>;
                        string Res_P = MyHttp.SendHttpData(DDD.Item1, DDD.Item1);
                        //XuanZhuOperation.ReportService(DDD.Item1, DDD.Item2);
                        //logger.Error("Fault Return:" + "");
                    }, fault_data);
                }
            }
            faults.Clear();
        }

        /// <summary>
        /// 暂时用不到
        /// </summary>
        /// <param name="host"></param>
        /// <param name="faults"></param>
        private void ProcessFaults_NEW(SomeDeviceExistsData host, ConcurrentDictionary<string, FaultStaus> faults)
        {
            DateTime now = DateTime.Now;
            bool isInsert = false;
            //StringBuilder sbSQL;
            foreach (var fault in faults)
            {
                var hostModal = HostModalRepository.Get(host.HostID, fault.Value.FaultNo);
                if (hostModal == null ||
                    (fault.Value.Type == 1 && !hostModal.Modal.OfflineDisplay) ||
                    (fault.Value.Type == 2 && !hostModal.Modal.LowPowerDisplay))
                {
                    continue;//回路不存在，或离线不显示，或低电不显示，则不保存 add by jophywu on 20191102
                }
                var record = HostFaultsRepository.Get(host.HostID, fault.Value.FaultNo);
                //sbSQL = new StringBuilder();
                //sbSQL.Append("UPDATE tb_HostFaults SET ");
                if (record == null)
                {
                    isInsert = true;
                    record = new HostFaults();
                    record.HostID = host.HostID;
                    record.Address = fault.Value.FaultNo;
                    record.AbnormalStatus = 0;//默认在线
                    record.StatusDate = Convert.ToDateTime("1800-1-1");
                    record.AbnormalElectricQty = 100;//默认电量100
                    record.ElectricQtyDate = Convert.ToDateTime("1800-1-1");
                    record.Abnormal3 = 0;//默认电流100
                    record.Abnormal3Date = Convert.ToDateTime("1800-1-1");
                    record.Abnormal4 = 0;//1901故障检测次数，默认0
                    record.Abnormal4Date = Convert.ToDateTime("1800-1-1");
                    record.Abnormal5 = 0;//设备单个回路状态：0正常，1损坏
                    record.Abnormal5Date = Convert.ToDateTime("1800-1-1");
                }
                switch (fault.Value.Type)
                {
                    case 1://状态：1离线,0在线
                        record.AbnormalStatus = fault.Value.Data;
                        record.StatusDate = now;
                        //sbSQL.Append("AbnormalStatus=" + record.AbnormalStatus + ",StatusDate=GETDATE()");
                        break;
                    case 2://电量
                        record.AbnormalElectricQty = fault.Value.Data;
                        record.ElectricQtyDate = now;
                        //sbSQL.Append("AbnormalElectricQty=" + record.AbnormalElectricQty + ",ElectricQtyDate=GETDATE()");
                        break;
                    case 3://电流（10MA）
                        record.Abnormal3 = fault.Value.Data;
                        record.Abnormal3Date = now;
                        //sbSQL.Append("Abnormal3=" + record.Abnormal3 + ",Abnormal3Date=GETDATE()");
                        break;
                    case 4://1901故障检测次数
                        record.Abnormal4 = fault.Value.Data;
                        record.Abnormal4Date = now;
                        //sbSQL.Append("Abnormal4=" + record.Abnormal4 + ",Abnormal4Date=GETDATE()");
                        break;
                    case 5://设备单个回路状态：0正常，1损坏
                        record.Abnormal5 = fault.Value.Data;
                        record.Abnormal5Date = now;
                        //sbSQL.Append("Abnormal5=" + record.Abnormal5 + ",Abnormal5Date=GETDATE()");
                        break;
                    default:
                        continue;//不保存
                }
                if (isInsert)
                {
                    isInsert = false;
                    HostFaultsRepository.Save(record);
                }
                else
                {
                    //sbSQL.Append(" WHERE ID=" + record.ID);
                    HostFaultsRepository.Update(record);//sbSQL.ToString());
                }
                //保存每一次异常记录
                HostFaultRecords hostFaultRecords = new HostFaultRecords();
                hostFaultRecords.HostID = host.HostID;
                hostFaultRecords.RoomNumber = host.RoomNumber;
                hostFaultRecords.RoomTypeID = hostModal.Modal.RoomType.ID;
                hostFaultRecords.RoomTypeModalID = hostModal.Modal.ID;
                hostFaultRecords.ModalAddress = hostModal.Modal.ModalAddress;
                hostFaultRecords.Type = fault.Value.Type;
                hostFaultRecords.Value = fault.Value.Data;
                hostFaultRecords.Date = now;
                HostFaultRecordsRepository.Save(hostFaultRecords);
                //出现异常信息时上报
                if (!string.IsNullOrEmpty(host.FaultPushURL))
                {
                    Task.Factory.StartNew(() =>
                    {
                        XuanZhuResponse resp = new XuanZhuResponse()
                        {
                            code = host.HotelCode,
                            roomNumber = host.RoomNumber,
                            address = hostModal.Modal.ModalAddress,
                            name = hostModal.Modal.Name,
                            status = hostModal.Status,
                            faultType = fault.Value.Type,
                            faultData = fault.Value.Data
                        };
                        //XuanZhuOperation.ReportService(host.FaultPushURL, resp);
                        MyHttp.SendHttpData(host.FaultPushURL, resp);
                    });
                }
            }
            //faults.Clear();
        }

        public override CommandType CommandType
        {
            get { return CommandType.RoomStatus; }
        }

        private byte[] CreateRoomStatusRequestPacket()
        {
            SystemHeader systemHeader = CreateSystemHeader();
            int size = StructConverter.SizeOf(systemHeader) + 2;
            systemHeader.FrameLength = (ushort)size;
            byte[] buffer = new byte[size];
            byte[] data1 = StructConverter.StructToBytes(systemHeader);
            Array.Copy(data1, 0, buffer, 0, data1.Length);
            return buffer;
        }
        /// <summary>
        /// 解释上报命令
        /// </summary>
        /// <param name="host"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        private Status DecodeRoomStatus(Host host, Stream stream)
        {
            Status roomStatus = new Status();
            try
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    roomStatus.SysLock = reader.ReadBoolean();		//RCU是否锁定：0/否，1/是
                    roomStatus.CardType = reader.ReadByte();		//房卡类型：0/无人，1/有人，2/客人，3/经理，4/服务员
                    roomStatus.Door = reader.ReadBoolean();			//门磁开关：1/开，2/关
                    roomStatus.ElecQty = reader.ReadUInt16();		//门锁电量，单位：MV
                    roomStatus.HostTemp = reader.ReadByte();		//主机温度
                    //空调数量，默认0，新的回路方式，此处无用，兼容老版本
                    int airConditionNumber = reader.ReadByte();
                    for (int i = 0; i < airConditionNumber; i++)
                    {
                        byte airNo = reader.ReadByte();
                        if (!roomStatus.AirConditions.ContainsKey(airNo))
                        {
                            roomStatus.AirConditions[airNo] = new AirConditionStatus();
                        }
                        roomStatus.AirConditions[airNo].AirNo = airNo;
                        roomStatus.AirConditions[airNo].CurrentTemp = reader.ReadSByte();
                        roomStatus.AirConditions[airNo].SettingTemp = reader.ReadSByte();
                        roomStatus.AirConditions[airNo].OnOff = reader.ReadBoolean();
                        roomStatus.AirConditions[airNo].Speed = reader.ReadByte();
                        roomStatus.AirConditions[airNo].Mode = reader.ReadByte();
                        roomStatus.AirConditions[airNo].Valve = reader.ReadByte();
                        roomStatus.AirConditions[airNo].CompensatoryTemp = ConvertCompensatoryTempToServer(reader.ReadByte());
                        roomStatus.AirConditions[airNo].KeepTemp = reader.ReadByte();
                        roomStatus.AirConditions[airNo].ColdHotMode = reader.ReadByte();
                        roomStatus.AirConditions[airNo].DeadTemp = reader.ReadByte();
                        roomStatus.AirConditions[airNo].HotDevition = reader.ReadByte();
                        roomStatus.AirConditions[airNo].ColdDevition = reader.ReadByte();
                    }
                    //设备状态数量，包含所有回路状态
                    int deviceNumber = reader.ReadByte();
                    for (int i = 0; i < deviceNumber; i++)
                    {
                        var QA = reader.ReadBytes(4);
                        var Status = reader.ReadUInt16();


                        string address = new DeviceAddress(QA).ToString();
                        if (!roomStatus.Devices.ContainsKey(address))
                        {
                            roomStatus.Devices[address] = new Device();
                        }
                        roomStatus.Devices[address].Address = address;//设备地址
                        roomStatus.Devices[address].StatusReceiver = Status;//设备状态改为2个字节,Modified By 20181213
                    }
                    //故障数量，默认0
                    int faultNumber = reader.ReadByte();
                    for (int i = 0; i < faultNumber; i++)
                    {
                        string faultNo = new DeviceAddress(reader.ReadBytes(4)).ToString();//设备类型1、设备地址1、回路地址2
                        byte type = reader.ReadByte();
                        if (!roomStatus.Faults.ContainsKey(faultNo + type.ToString()))
                        {
                            roomStatus.Faults[faultNo + type.ToString()] = new FaultStaus();
                        }
                        roomStatus.Faults[faultNo + type.ToString()].FaultNo = faultNo;
                        roomStatus.Faults[faultNo + type.ToString()].Type = type;//类型：1在线状态（0在线，1离线），2电量（0~100%），3电流，4 1901故障检测次数
                        roomStatus.Faults[faultNo + type.ToString()].Data = reader.ReadByte();//内容
                    }
                    return roomStatus;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static string[] NoFilterHotelCode = new string[]
        {
           "1001","1085" ,"1197","2079"
        };

        private Status DecodeRoomStatus_NEW(Stream stream, string HostNumberOnly, out bool TakeCardTriggerWelcome, string hotelcode, string roomnum)
        {
            TakeCardTriggerWelcome = true;
            Status roomStatus = new Status();
            try
            {
                // 重要：将流的位置重置到开始，以便读取
                //stream.Seek(0, SeekOrigin.Begin);
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    roomStatus.SysLock = reader.ReadBoolean();		//RCU是否锁定：0/否，1/是
                    roomStatus.CardType = reader.ReadByte();		//房卡类型：0/无人，1/有人，2/客人，3/经理，4/服务员
                    roomStatus.Door = reader.ReadBoolean();			//门磁开关：1/开，2/关
                    roomStatus.ElecQty = reader.ReadUInt16();		//门锁电量，单位：MV
                    roomStatus.HostTemp = reader.ReadByte();		//主机温度
                    //空调数量，默认0，新的回路方式，此处无用，兼容老版本
                    int airConditionNumber = reader.ReadByte();
                    for (int i = 0; i < airConditionNumber; i++)
                    {
                        byte airNo = reader.ReadByte();
                        if (!roomStatus.AirConditions.ContainsKey(airNo))
                        {
                            roomStatus.AirConditions[airNo] = new AirConditionStatus();
                        }
                        roomStatus.AirConditions[airNo].AirNo = airNo;
                        roomStatus.AirConditions[airNo].CurrentTemp = reader.ReadSByte();
                        roomStatus.AirConditions[airNo].SettingTemp = reader.ReadSByte();
                        roomStatus.AirConditions[airNo].OnOff = reader.ReadBoolean();
                        roomStatus.AirConditions[airNo].Speed = reader.ReadByte();
                        roomStatus.AirConditions[airNo].Mode = reader.ReadByte();
                        roomStatus.AirConditions[airNo].Valve = reader.ReadByte();
                        roomStatus.AirConditions[airNo].CompensatoryTemp = ConvertCompensatoryTempToServer(reader.ReadByte());
                        roomStatus.AirConditions[airNo].KeepTemp = reader.ReadByte();
                        roomStatus.AirConditions[airNo].ColdHotMode = reader.ReadByte();
                        roomStatus.AirConditions[airNo].DeadTemp = reader.ReadByte();
                        roomStatus.AirConditions[airNo].HotDevition = reader.ReadByte();
                        roomStatus.AirConditions[airNo].ColdDevition = reader.ReadByte();
                    }
                    //设备状态数量，包含所有回路状态
                    int deviceNumber = reader.ReadByte();


                    //青奥酒店的数据是对的，包含在19中
                    if (!NoFilterHotelCode.Contains(hotelcode))
                    //if (!hotelcode.Equals("1001"))
                    {
                        if (deviceNumber == 25)
                        {
                            //Device dd = null;
                            //roomStatus.Devices.TryRemove("004000001", out dd);
                            string key123 = PoolOverFlowKey + "_" + HostNumberOnly;

                            //MemoryCacheHelper.Set(key123, 0, DateTimeOffset.Now.AddSeconds(5));
                            MemoryCacheHelper.SlideSet(key123, 0, new TimeSpan(0, 0, 5));
                            return null;
                        }
                    }

                    long originalPosition = reader.BaseStream.Position;
                    // 读取前先记录当前位置
                    try
                    {
                        //0x19数据缓冲区异常问题处理
                        //0x19 取电数据不处理
                        //非0x19 取电数据处理，但是不触发 欢迎词
                        ushort UUUS = 0;
                        for (int i = 0; i < deviceNumber; i++)
                        {
                            var QA = reader.ReadBytes(4);
                            var Status = reader.ReadUInt16();

                            string address = new DeviceAddress(QA).ToString();
                            if (!roomStatus.Devices.ContainsKey(address))
                            {
                                roomStatus.Devices[address] = new Device();
                            }
                            roomStatus.Devices[address].Address = address;//设备地址
                            roomStatus.Devices[address].StatusReceiver = Status;//设备状态改为2个字节,Modified By 20181213
                            originalPosition = reader.BaseStream.Position;
                            UUUS = Status;
                        }

                        if (roomStatus.Devices.All(A => A.Key.StartsWith("004000")))
                        {
                            //这个是定期上报,触发数据读写，但是不触发欢迎词
                            if (deviceNumber == 5 || deviceNumber == 6)
                            {
                                TakeCardTriggerWelcome = false;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // 发生异常时回退到原始位置
                        reader.BaseStream.Position = originalPosition;
                        //logger.Error("device_count error");
                    }
                    try
                    {
                        //故障数量，默认0
                        int faultNumber = reader.ReadByte();
                        for (int i = 0; i < faultNumber; i++)
                        {
                            string faultNo = new DeviceAddress(reader.ReadBytes(4)).ToString();//设备类型1、设备地址1、回路地址2
                            byte type = reader.ReadByte();
                            if (!roomStatus.Faults.ContainsKey(faultNo + type.ToString()))
                            {
                                roomStatus.Faults[faultNo + type.ToString()] = new FaultStaus();
                            }
                            roomStatus.Faults[faultNo + type.ToString()].FaultNo = faultNo;
                            roomStatus.Faults[faultNo + type.ToString()].Type = type;//类型：1在线状态（0在线，1离线），2电量（0~100%），3电流，4 1901故障检测次数
                            roomStatus.Faults[faultNo + type.ToString()].Data = reader.ReadByte();//内容
                        }
                    }
                    catch (Exception)
                    {

                    }
                    return roomStatus;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 将补偿温度转换为服务器存储格式，具体格式参见协议
        /// </summary>
        /// <param name="temp"></param>
        /// <returns></returns>
        private float ConvertCompensatoryTempToServer(byte temp)
        {
            float val = Convert.ToSingle((temp & 0x7F) / 10.0);
            if ((temp & 0x80) != 0)
            {
                return -val;
            }
            return val;
        }
    }

    public class Status
    {
        /// <summary>
        /// RCU是否锁定
        /// </summary>
        public bool SysLock { get; set; }
        /// <summary>
        /// 房卡类型
        /// </summary>
        public byte CardType { get; set; }
        /// <summary>
        /// 房门开关
        /// </summary>
        public bool Door { get; set; }
        /// <summary>
        /// 电量
        /// </summary>
        public ushort ElecQty { get; set; }
        /// <summary>
        /// 主机温度
        /// </summary>
        public byte HostTemp { get; set; }
        /// <summary>
        /// 空调状态
        /// </summary>
        public ConcurrentDictionary<byte, AirConditionStatus> AirConditions = new ConcurrentDictionary<byte, AirConditionStatus>();
        /// <summary>
        /// 设备状态
        /// </summary>
        public ConcurrentDictionary<string, Device> Devices = new ConcurrentDictionary<string, Device>();
        /// <summary>
        /// 故障列表
        /// </summary>
        public ConcurrentDictionary<string, FaultStaus> Faults = new ConcurrentDictionary<string, FaultStaus>();
    }

    /// <summary>
    /// 空调状态
    /// </summary>
    public class AirConditionStatus
    {
        /// <summary>
        /// 空调号
        /// </summary>
        public byte AirNo { get; set; }
        /// <summary>
        /// 当前温度
        /// </summary>
        public int CurrentTemp { get; set; }
        /// <summary>
        /// 设定温度
        /// </summary>
        public int SettingTemp { get; set; }
        /// <summary>
        /// 风机开关
        /// </summary>
        public bool OnOff { get; set; }
        /// <summary>
        /// 风速：0/停止, 1/低速, 2/中速, 3/高速, 4/自动
        /// </summary>
        public int Speed { get; set; }
        /// <summary>
        /// 模式: 0/制冷，1/制热，2/送风，3/除湿
        /// </summary>
        public int Mode { get; set; }
        /// <summary>
        /// 阀状态： 1/阀开，2/阀关
        /// </summary>
        public int Valve { get; set; }
        /// <summary>
        /// 补偿温度，范围-6.0~6.0
        /// </summary>
        public float CompensatoryTemp { get; set; }
        /// <summary>
        /// 保温温度
        /// </summary>
        public int KeepTemp { get; set; }
        /// <summary>
        /// 冷热模式：0/手动，1/自动
        /// </summary>
        public int ColdHotMode { get; set; }
        /// <summary>
        /// 死区温度
        /// </summary>
        public int DeadTemp { get; set; }
        /// <summary>
        /// 热偏差
        /// </summary>
        public int HotDevition { get; set; }
        /// <summary>
        /// 冷偏差
        /// </summary>
        public int ColdDevition { get; set; }
    }

    public class FaultStaus
    {
        /// <summary>
        /// 故障号
        /// </summary>
        public string FaultNo { get; set; }
        /// <summary>
        /// 类型：1在线状态（0在线，1离线），2电量（0~100%），3电流，4 1901故障检测次数，5设备单个回路状态（0正常，1损坏）
        /// </summary>
        public byte Type { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public byte Data { get; set; }
    }
}
