using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Dao;
using Domain;
using RCUHost;
using System.Xml;
using Common;
using System.IO;
using Dao.Implement;
using RestSharp;
using CommonEntity;
using System.Configuration;

namespace Service.Implement
{
    public class HostManager : GenericManagerBase<Host>, IHostManager
    {
        #region Properties

        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HostManager));

        public IUpdateHostReceiver UpdateHostReceiver { get; set; }
        public IUpdateHostFTPReceiver UpdateHostFTPReceiver { get; set; }
        public IUpdateRCUFileReceiver UpdateRCUFileReceiver { get; set; }
        public IAuthorizationReceiver AuthorizationReceiver { get; set; }
        //public IUpdateConfigReceiver UpdateConfigReceiver { get; set; }
        //public IConnectingRoomReceiver ConnectingRoomReceiver { get; set; }
        //public IHeartReceiver HeartReceiver { get; set; }
        //public IRoomTypeRepository RoomTypeRepository { get; set; }
        public IAlarmSettingRepository AlarmSettingRepository { get; set; }
        public IGroupRepository GroupRepository { get; set; }
        public IRoomTypeModalRepository RoomTypeModalRepository { get; set; }
        public IRoomTypeAirRepository RoomTypeAirRepository { get; set; }
        public IHostAirRepository HostAirRepository { get; set; }
        public IHostModalRepository HostModalRepository { get; set; }
        public INetworkSettingReceiver NetworkSettingReceiver { get; set; }
        public IRoomStatusRepository RoomStatusRepository { get; set; }
        public IRoomStatusChangedReceiver RoomStatusChangedReceiver { get; set; }
        public IRoomServiceRepository RoomServiceRepository { get; set; }
        public ISysHotelRepository SysHotelRepository { get; set; }
        public IDeviceSecretReceiver DeviceSecretReceiver { get; set; }
        public IHostSecretReceiver HostSecretReceiver { get; set; }
        public IHostWordsReportRepository HostWordsReportRepository { get; set; }
        public IHostFaultsRepository HostFaultsRepository { get; set; }
        public IHostFaultRecordsRepository HostFaultRecordsRepository { get; set; }
        public IHostSceneRepository HostSceneRepository { get; set; }
        public IHostRoomCardRepository HostRoomCardRepository { get; set; }
        public IHostRegisterReceiver HostRegisterReceiver { get; set; }
        public IHostRegisterSetReceiver HostRegisterSetReceiver { get; set; }
        public ISysOauth2Repository SysOauth2Repository { get; set; }
        public IHotelSeasonRepository HotelSeasonRepository { get; set; }
        public IHotelAirControlRepository HotelAirControlRepository { get; set; }
        public IHostModalManager HostModalManager { get; set; }
        public IHostRepository HostRepository { get; set; }


        /// <summary>
        /// 阿宝添加的功能
        /// </summary>
        public IKongTiaoTimerManager KongTiaoManager { get; set; }
        public IRoomNoBodyMananger RoomNoBodyMananger { get; set; }
        public IRoomNoBodyLogMananger RoomNoBodyLogMananger { get; set; }

        public IECO_DetailRepository ECO_DetailRepository { get; set; }
        public IECO_SettingRepository ECO_SettingRepository { get; set; }


        public IT_FTPReceiver TFTP_LogReceiver { get; set; }
        public IT_FTPSettingReceiver TFTP_LogSettingReceiver { get; set; }

        /// <summary>
        /// 透传功能
        /// </summary>
        public IHostTouChuan HostUDPTouChuan { get; set; }
        #endregion

        //private bool GetHostStatus(string hostNumber)
        //{
        //    return Common.MemoryCacheHelper.Contains(hostNumber);
        //}

        #region Public Methods

        public override Host Get(object id)
        {
            var host = base.Get(id);
            if (host != null)
            {
                host.Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
            }
            return host;
        }

        public override IList<Host> LoadAll()
        {
            IList<Host> list = base.LoadAll();
            foreach (var host in list)
            {
                host.Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
            }
            return list;
        }


        public IList<Host> LoadAll(string order, string sort, Group group, string roomNumber)
        {
            IList<Group> groups = GroupRepository.GetGroupList(group);
            IList<Host> hosts = ((IHostRepository)CurrentRepository).LoadAll(order, sort, groups, roomNumber);
            foreach (var host in hosts)
            {
                host.Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
                var table = RoomServiceRepository.LoadAll().Where(r => r.HostID == host.ID && r.AlarmType == 'B').ToList();
                //foreach (var roomService in table)
                //{
                //    if (roomService.AlarmCode == "B01")
                //    {
                //        host.SOS = roomService.Status;
                //    }
                //    else if (roomService.AlarmCode == "B02")
                //    {
                //        host.RequestDNDST = roomService.Status;
                //    }
                //    else if (roomService.AlarmCode == "B03")
                //    {
                //        host.RequestClear = roomService.Status;
                //    }
                //    else if (roomService.AlarmCode == "B04")
                //    {
                //        host.RequestService = roomService.Status;
                //    }
                //    else if (roomService.AlarmCode == "B05")
                //    {
                //        host.RequestCheckOut = roomService.Status;
                //    }
                //}
            }

            return hosts;
        }

        public IList<Host> LoadAll(Group group)
        {
            IList<Group> groups = GroupRepository.GetGroupList(group);
            IList<Host> hosts = ((IHostRepository)CurrentRepository).LoadAll(groups);
            foreach (var host in hosts)
            {
                host.Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
            }
            return hosts;
        }

        public IList<Host> LoadAll(string hotelCode)
        {
            var hotel = SysHotelRepository.GetByCode(hotelCode);
            return ((IHostRepository)CurrentRepository).LoadAll(hotel.ID, "");
        }

        public IList<Host> LoadAll(int hotelID, string roomNumber = "")
        {
            IList<Host> hosts = ((IHostRepository)CurrentRepository).LoadAll(hotelID, roomNumber);
            foreach (var host in hosts)
            {
                host.Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
            }
            return hosts;
        }

        public IList<Host> LoadAll(IList<Group> groupList, RoomStatus roomStatus, RoomType roomType)
        {
            var hostList = ((IHostRepository)CurrentRepository).LoadAll(groupList, roomStatus, roomType);
            foreach (var host in hostList)
            {
                host.Status = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
            }
            return hostList;
        }

        public IList<Host> LoadAllByPage(out long total, int page, int rows, string order, string sort, int groupId, int hotelID, string roomNumber, string mac, string roomType, int isSyncRoomNumber)
        {
            return ((IHostRepository)CurrentRepository).LoadAllByPage(out total, page, rows, order, sort, groupId, hotelID, roomNumber, mac, roomType, isSyncRoomNumber).ToList();
            //var list = CurrentRepository.LoadAll();
            //if (groupId.HasValue && groupId != 1)
            //{
            //    list = list.Where(r => r.Group != null && r.Group.ID == groupId);
            //}
            //total = list.LongCount();
            //list = list.OrderBy(sort + " " + order);
            //list = list.Skip((page - 1) * rows).Take(rows);
            //return list.ToList();
        }

        public DataTable LoadHostWithPage(out long total, int page, int rows, string order, string sort, int groupId, int hotelID, string roomNumber, string mac, string roomType)
        {
            return ((IHostRepository)CurrentRepository).LoadHostWithPage(out total, page, rows, order, sort, groupId, hotelID, roomNumber, mac, roomType);
        }

        public IList<Room> LoadRooms(out long total, int page, int rows, int? groupId, int lang, int hotelID)
        {
            return ((IHostRepository)CurrentRepository).LoadRooms(out total, page, rows, groupId, lang, hotelID);
        }

        public IList<string> LoadRoomNumbers()
        {
            return ((IHostRepository)CurrentRepository).LoadAll().Select(r => r.RoomNumber).ToList<string>();
        }

        public DataTable LoadRoomNumbers(Group group, int hotelID)
        {
            return ((IHostRepository)CurrentRepository).LoadRoomNumbers(group, hotelID);
        }

        public override object Save(Host entity)
        {
            try
            {
                //SysHotel sysHotel = SysHotelRepository.Get(entity.SysHotel.ID);
                //if (sysHotel == null) { throw new ApplicationException("无效的酒店！"); }
                //RoomType roomType = RoomTypeRepository.Get(entity.RoomType.ID);
                //if (roomType == null) { throw new ApplicationException("无效的房型！"); }
                if (entity.ID == 0)//新增
                {
                    entity.RegisterDate = DateTime.Now;
                    entity.RoomStatus = new RoomStatus { ID = 16 };
                    entity.SafeStatus = 2;
                    entity.Version = "C";//界面上新增的主机都属于C系列主机
                    entity.ExpireTime = Convert.ToDateTime("2100-12-31");//默认有效期永久
                    entity.Last_Modified_Time = DateTime.Now;//标识有更新
                    base.Save(entity);
                    Task.Factory.StartNew((state) =>
                        {
                            var entity1 = state as Host;
                            UpdateHostModals(entity1);
                        }, entity);
                    //更新回路
                    return entity;
                }
                else
                {
                    var host = CurrentRepository.Get(entity.ID);

                    Host host_take = null;
                    string Key = CacheKey.HostInfo_Key_HostNumber + "_" + host.HostNumber;
                    object obj = MemoryCacheHelper.Get(Key);
                    if (obj != null)
                    {
                        host_take = obj as Host;
                    }

                    int oldRoomTypeID = host.RoomType.ID;
                    bool isChanged = false;
                    if (host.RoomNumber != entity.RoomNumber)
                    {
                        host.RoomNumber = entity.RoomNumber;
                        isChanged = true;
                    }
                    if (host.MAC != entity.MAC)
                    {
                        host.MAC = entity.MAC;
                        isChanged = true;
                    }
                    if (host.SysHotel.ID != entity.SysHotel.ID)
                    {
                        host.SysHotel = entity.SysHotel;
                        isChanged = true;
                    }
                    if (host.RoomType.ID != entity.RoomType.ID)
                    {
                        host.RoomType = entity.RoomType;
                        isChanged = true;
                    }
                    if (host.Remark != entity.Remark.Trim())
                    {
                        host.Remark = entity.Remark.Trim();
                        isChanged = true;
                    }
                    if (host.ServerIP != entity.ServerIP.Trim())
                    {
                        host.ServerIP = entity.ServerIP.Trim();
                        isChanged = true;
                    }
                    if (host.ServerPort != entity.ServerPort)
                    {
                        host.ServerPort = entity.ServerPort;
                        isChanged = true;
                    }

                    if (host.FCS_locationUUID != entity.FCS_locationUUID)
                    {
                        host.FCS_locationUUID = entity.FCS_locationUUID;
                        isChanged = true;
                    }
                    if (isChanged) { host.Last_Modified_Time = DateTime.Now; }
                    host.HostNumber = entity.HostNumber;
                    host.Group = entity.Group;
                    if (string.IsNullOrEmpty(host.Version)) { host.Version = "C"; }
                    host.IsSyncRoomNumber = entity.IsSyncRoomNumber;
                    host.IsAutoUpdate = entity.IsAutoUpdate;
                    host.IPType = entity.IPType;
                    if (host.IPType == 2)
                    {
                        host.LanIP = entity.LanIP.Trim();
                        host.LanPort = entity.LanPort;
                        host.SubnetMask = entity.SubnetMask.Trim();
                        host.Gateway = entity.Gateway.Trim();
                        host.DNS = entity.DNS.Trim();
                    }
                    base.Update(host);
                    if (host_take != null)
                    {
                        host_take.ServerPort = host.ServerPort;
                        host_take.ServerIP = host.ServerIP;
                        host_take.FCS_locationUUID = host.FCS_locationUUID;

                        host.RoomType = host.RoomType;
                        host_take.MAC = host.MAC;
                        host_take.Version = host.Version;
                        host_take.LanIP = host.LanIP;
                        host_take.LanPort = host.LanPort;
                        host_take.SubnetMask = host.SubnetMask;
                        host_take.Gateway = host.Gateway;
                        host_take.DNS = host.DNS;
                    }
                    if (HostModalRepository.LoadByHostID(entity.ID).ToList().Count == 0 || host.RoomType == null || host.RoomType.ID != oldRoomTypeID)
                    {
                        Task.Factory.StartNew((state) =>
                        {
                            var entity1 = state as Host;
                            UpdateHostModals(entity1);
                        }, entity);//更新回路
                    }
                    return host;
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.ToString());
            }
        }

        public void SaveSmartVoiceBinding(Host entity)
        {
            var host = CurrentRepository.Get(entity.ID);
            host.XiaoDuCUID = entity.XiaoDuCUID;
            host.TCLCUID = entity.TCLCUID;
            host.TCLSkillID = entity.TCLSkillID;
            host.HuaWeiCUID = entity.HuaWeiCUID;
            host.TianMaoCUID = entity.TianMaoCUID;
            host.HiWeiCUID = entity.HiWeiCUID;
            host.RokidWebhookUrl = entity.RokidWebhookUrl;
            host.IsWelcomeDisableTime = entity.IsWelcomeDisableTime;
            host.DisableStartTime = entity.DisableStartTime;
            host.DisableEndTime = entity.DisableEndTime;
            host.EBell_RSTP = entity.EBell_RSTP;
            if (entity.EBell_TV_duration==0)
            {
                entity.EBell_TV_duration = 20000; 
            }
            host.EBell_TV_duration = entity.EBell_TV_duration;

            //string Key = CacheKey.HostInfo_Key_HostNumber + "_" + host.HostNumber;
            //object obj = MemoryCacheHelper.Get(Key);
            //if (obj != null)
            //{
            //    host = obj as Host;
            //    host.XiaoDuCUID;
            //}

            ((IHostRepository)CurrentRepository).Update(host);
        }

        public Host GetByMAC(string mac, int hotelID)
        {
            return (CurrentRepository as Dao.IHostRepository).GetByMAC(mac, hotelID);
        }

        public IList<Host> LoadByMac(string mac)
        {
            return (CurrentRepository as Dao.IHostRepository).LoadByMac(mac);
        }

        public Host GetByXiaoDuCUID(string cuid)
        {
            return (CurrentRepository as Dao.IHostRepository).GetByXiaoDuCUID(cuid);
        }

        public Host GetByTianMaoCUID(string cuid)
        {
            return (CurrentRepository as Dao.IHostRepository).GetByTianMaoCUID(cuid);
        }

        public Host GetByHuaWeiCUID(string cuid)
        {
            return (CurrentRepository as Dao.IHostRepository).GetByHuaWeiCUID(cuid);
        }

        public Host GetByTCLCUID(string cuid)
        {
            return (CurrentRepository as Dao.IHostRepository).GetByTCLCUID(cuid);
        }

        public Host GetByRoomNumber(string roomNumber, int hotelID)
        {
            if (String.IsNullOrEmpty(roomNumber))
            {
                return null;
            }
            return CurrentRepository.LoadAll().FirstOrDefault(r => r.RoomNumber == roomNumber && r.SysHotel.ID == hotelID && !r.IsDeleted);
        }

        public Host GetByRoomNumber(string roomNumber, string hotelCode)
        {
            if (String.IsNullOrEmpty(roomNumber))
            {
                return null;
            }
            return CurrentRepository.LoadAll().FirstOrDefault(r => r.RoomNumber == roomNumber && r.SysHotel.Code == hotelCode && !r.IsDeleted);
        }

        public Host GetByRoomNumberSupply(string roomNumber)
        {
            if (String.IsNullOrEmpty(roomNumber))
            {
                return null;
            }
            return CurrentRepository.LoadAll().FirstOrDefault(r => r.RoomNumber == roomNumber && !r.IsDeleted);
        }

        //public IList<Host> GetConnectRoomHosts(Host host)
        //{
        //    return ((IHostRepository)CurrentRepository).GetConnectRoomHosts(host);
        //}

        public string GetRoomNumber(int hostID)
        {
            return CurrentRepository.LoadAll().Where(r => r.ID == hostID && !r.IsDeleted).Select(r => r.RoomNumber).FirstOrDefault();
        }

        public IList<Host> GetByGroup(Group group)
        {
            return LoadAll().Where(r => r.Group == group).ToList();
        }
        /// <summary>
        /// 删除主机的同时，删除其关联的数据
        /// </summary>
        /// <param name="idList"></param>
        public override void Delete(IList<object> idList)
        {
            foreach (int id in idList)
            {
                HostModalRepository.DeteleByHostID(id);//删除 HostModal
                HostWordsReportRepository.DeteleByHostID(id);
                HostFaultsRepository.DeteleByHostID(id);
                //HostFaultRecordsRepository.DeteleByHostID(id);
                HostSceneRepository.DeteleByHostID(id);
                HostRoomCardRepository.DeteleByHostID(id);
            }
            ((IHostRepository)(this.CurrentRepository)).Delete(idList);
        }

        public void UpdateHost(HostUpdate hostUpdate, FileType fileType, string fileHref, string fileMd5, IList<Host> hosts, bool isTFTP)
        {
            switch (hostUpdate.FileType)
            {
                case FileType.RCUValidate:
                    UpdateRCUFileReceiver.Update(hostUpdate, hosts);
                    break;
                default:
                    if (isTFTP)
                    {
                        UpdateHostReceiver.Update(hostUpdate, fileType, fileHref, fileMd5, hosts);
                    }
                    else
                    {
                        UpdateHostFTPReceiver.Update(hostUpdate, fileType, fileHref, fileMd5, hosts);
                    }
                    break;
            }
        }
        /// <summary>
        /// 针对C主机升级
        /// </summary>
        /// <param name="hostUpdate"></param>
        /// <param name="fileType"></param>
        /// <param name="fileHref"></param>
        /// <param name="fileMd5"></param>
        /// <param name="hosts"></param>
        public void UpdateHostC(HostUpdate hostUpdate, FileType fileType, string fileHref, string fileMd5, IList<Host> hosts)
        {
            UpdateHostReceiver.Update(hostUpdate, fileType, fileHref, fileMd5, hosts);
        }
        /// <summary>
        /// 修改房态
        /// </summary>
        /// <param name="host"></param>
        /// <param name="roomStatusID">2：出租，4：待租，8：退房，16：空房</param>
        public void ChangeRoomStatus(Host host, int roomStatusID, string wxValidate)
        {

            RoomStatus NNN = NewMethod(host, roomStatusID);

            ChangeRoomStatus(host, NNN, wxValidate);
        }

        private RoomStatus NewMethod(Host host, int roomStatusID)
        {
            //目前房态信息有一下4种
            //0x01:入住 - 用户插卡取电后，RCU主机上报入住服务
            //0x02:退房 - 服务器通过协议下发房态
            //0x03:待租 - 服务器通过协议下发房态
            //0x04:空房 - 服务器通过协议下发房态

            RoomStatus NNN = RoomStatusRepository.Get(roomStatusID);
            string host_number = host.HostNumber;
            //string CKey = CacheKey.RoomStatus_Prefix + "_" + host_number;
            //var q = CSRedisCacheHelper.Get_Partition<SomeDeviceExistsData>(CKey);

            Host host_takeout = null;
            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + host_number;
            object obj = MemoryCacheHelper.Get(Key);
            if (obj != null)
            {

                //q.RoomStatus = NNN;
                //CSRedisCacheHelper.Set_Partition<SomeDeviceExistsData>(CKey,q);

                host_takeout = (Host)obj;
                host_takeout.RoomStatus = NNN;
            }
            return NNN;
        }

        /// <summary>
        /// 阿宝要修改的，
        /// PMS 有房态变化，这里就要产生一个任务
        /// </summary>
        /// <param name="host"></param>
        /// <param name="roomStatus"></param>
        /// <param name="wxValidate"></param>
        public void ChangeRoomStatus(Host host, RoomStatus roomStatus, string wxValidate)
        {
            try
            {
                logger.Error("触发状态ID：" + roomStatus.ID);
                RoomStatusChangedReceiver.SendRoomStatus(host, roomStatus);
                host.RoomStatus = roomStatus;

                Host host_takeout = null;
                string Key = CacheKey.HostInfo_Key_HostNumber + "_" + host.HostNumber;
                object obj = MemoryCacheHelper.Get(Key);
                if (obj != null)
                {
                    host_takeout = (Host)obj;
                    host_takeout.RoomStatus = roomStatus;
                }

                if (!string.IsNullOrEmpty(wxValidate))
                {
                    host.WXValidate = wxValidate;
                }
                CurrentRepository.Update(host);


                #region 语言重置

                if (roomStatus.ID == 2 || roomStatus.ID == 8)//开房和退房时重置
                {
                    if (!string.IsNullOrEmpty(host.XiaoDuCUID))
                    {
                        string accessToken = "";
                        string KKK = CacheKey.DuOSToken;
                        var ooo = MemoryCacheHelper.Get(KKK);
                        if (ooo != null)
                        {
                            accessToken = ooo.ToString();
                        }
                        else
                        {
                            accessToken = SysOauth2Repository.GetXiaoDuToken();
                            MemoryCacheHelper.Set(KKK, accessToken, DateTimeOffset.Now.AddMinutes(20));
                        }
                        if (!string.IsNullOrEmpty(accessToken) && host.SysHotel.IsPowerOffResetXiaoDu)
                        {

                            foreach (string cuid in host.XiaoDuCUID.Split(','))//多个小度英文逗号隔开
                            {
                                XiaoDuOperation.PostWebRequestToXiaoDu(accessToken, cuid, new XiaoDuParamJson() { method = "reset" }, host.SysHotel.Code, host.RoomNumber);//重置小度
                            }
                            //Task.Factory.StartNew(() =>
                            //{
                            //});
                        }
                    }
                    if (!string.IsNullOrEmpty(host.TianMaoCUID))
                    {

                        foreach (string cuid in host.TianMaoCUID.Split(','))//多个英文逗号隔开
                        {
                            TianMaoOperation.PostWebRequestToTianMao("CheckoutWithAK",
                                Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = cuid.Split('&')[0], RoomNo = cuid.Split('&')[1] }), host.SysHotel.Code, host.RoomNumber);//重置天猫精灵
                        }
                        //Task.Factory.StartNew(() =>
                        //{
                        //});
                    }
                }

                #endregion

                if (roomStatus.ID == 8)
                {
                    #region 退房后空调控制
                    HotelSeason hotelSeason = null;
                    string KKKOne = "HotelSeason_" + host.SysHotel.ID;
                    var ooss = MemoryCacheHelper.Get(KKKOne);
                    if (ooss != null)
                    {
                        hotelSeason = ooss as HotelSeason;
                    }
                    else
                    {
                        hotelSeason = HotelSeasonRepository.LoadByHotelID(host.SysHotel.ID);//获取该酒店下季节设置记录
                        MemoryCacheHelper.Set(KKKOne, hotelSeason, DateTimeOffset.Now.AddMinutes(20));
                    }
                    if (hotelSeason != null)
                    {
                        //条件：1出租后，2取电后，3断电后
                        List<HotelAirControl> list = HotelAirControlRepository.LoadAll(host.SysHotel.ID, 4, true);
                        string KKK = "HostModalRepository_" + host.ID;
                        List<HostModal> hostModals = null;
                        var ooo = MemoryCacheHelper.Get(KKK);
                        if (ooo != null)
                        {
                            hostModals = ooo as List<HostModal>;
                        }
                        else
                        {
                            hostModals = HostModalRepository.LoadByHostID(host.ID).Where(r => r.Modal.Type == DeviceType.AirConditioner && r.Modal.ActiveIndicator).ToList();//获取启用的空调回路
                            MemoryCacheHelper.Set(KKK, hostModals, DateTimeOffset.Now.AddMinutes(20));
                        }
                        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设置空调
                                    {
                                        #region 备用方案
                                        //var TTT = new Tuple<Host, HotelAirControl, List<HostModal>>(host, item, hostModals);
                                        //Task.Factory.StartNew((state) =>
                                        //    {
                                        //        System.Threading.Thread.Sleep(item.DelayTime * 1000);//延迟执行

                                        //        Tuple<Host, HotelAirControl, List<HostModal>> NNN = state as Tuple<Host, HotelAirControl, List<HostModal>>;

                                        //        var QQ0 = NNN.Item1;
                                        //        var QQ1 = NNN.Item2;
                                        //        var QQ2 = NNN.Item3;
                                        //        foreach (HostModal hostModal in QQ2)
                                        //        {
                                        //            HostModalManager.SetDevice(QQ0, hostModal, QQ1.Status, 0, QQ1.SettingTemp, QQ1.FanSpeed, QQ1.Mode, 0);//0表示不变
                                        //        }
                                        //    }, TTT);
                                        #endregion


                                        try
                                        {
                                            //这段代码在生产环境中不管用，很奇怪
                                            string KeyMission = System.Guid.NewGuid().ToString("N");
                                            MissonData m = new MissonData()
                                            {
                                                hostnumber = host.HostNumber,
                                                mac = host.MAC,
                                            };

                                            m.HostModalList = new List<Tuple<string, DeviceType>>();
                                            foreach (HostModal hostModal in hostModals)
                                            {
                                                var t = new Tuple<string, DeviceType>(hostModal.Modal.ModalAddress, hostModal.Modal.Type);
                                                m.HostModalList.Add(t);
                                            }
                                            m.Status = item.Status;
                                            m.SettingTemp = item.SettingTemp;
                                            m.FanSpeed = item.FanSpeed;
                                            m.Mode = item.Mode;
                                            string MKey = "TuiFang_" + KeyMission;
                                            CSRedisCacheHelper.Set_Partition<MissonData>(MKey, m, 1);

                                            DelayExe_Task(host, item.DelayTime, MKey);
                                            break;
                                        }
                                        catch (Exception)
                                        {

                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }

                if (roomStatus.ID == 2)
                {
                    #region 出租后空调处理
                    //阿宝
                    //空调 在10分钟无人入住的情况之下，就关闭
                    //启动 一个任务

                    #region 阿宝添加的
                    int currenthotelid = host.SysHotel.ID;
                    RoomNobodyHowTo nnn = RoomNoBodyMananger.LoadAll().FirstOrDefault(A => A.CurrentHotelID == currenthotelid);
                    if (nnn != null)
                    {
                        if (!nnn.How.Equals("without"))
                        {
                            string Code = host.SysHotel.Code;
                            string RoomNo = host.RoomNumber;
                            DateTime CreateDate = host.SysHotel.CreatedDate;
                            string CD = CreateDate.ToString("yyyy-MM-dd");
                            int hotel_id = host.SysHotel.ID;
                            int host_id = host.ID;
                            string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            int delaytime = nnn.DelayTime;
                            int sustain = 20;
                            string MissionKey = System.Guid.NewGuid().ToString("N");
                            DateTime starttime = DateTime.Now.AddMinutes(delaytime);
                            DateTime endtime = starttime.AddMinutes(sustain);

                            //创建一条任务 插 入数据库
                            KongTiaoTimer k = new KongTiaoTimer();
                            k.HotelID = hotel_id;
                            k.HostID = host_id;
                            k.HotelCode = Code;
                            k.RoomNo = RoomNo;
                            k.MissonKey = MissionKey;
                            k.IsCancel = 0;
                            k.CreateTime = ti;
                            k.StartTime = starttime.ToString("yyyy-MM-dd HH:mm:ss");
                            k.EndTime = endtime.ToString("yyyy-MM-dd HH:mm:ss");
                            k.CreateDate = CD;

                            //string HotelCode, string RoomNo, int host_id,int hotel_id

                            MissionRequestData mm = new MissionRequestData();

                            mm.DelayTimer = delaytime;
                            mm.KT = k;
                            //mm.HotelCode = Code;
                            //mm.RoomNo = RoomNo;
                            //mm.HotelID = hotel_id;
                            //mm.HostID = host_id;
                            //mm.CreateDate = CD;

                            string jsstr = Newtonsoft.Json.JsonConvert.SerializeObject(mm);
                            //k.JsonData = jsstr;
                            k.MissonKey = MissionKey;
                            KongTiaoManager.Save(k);

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

                            logger.Error("任务管理系统发送了数据：" + Missionsys_Address + "API/Index");
                            //GetRequest ggg = new GetRequest() { creatDate = DateTime.Now.ToString("yyyy-mm-dd"), roomNumber = RoomNo, code = Code };


                            request1.AddParameter("jsonData", jsstr);

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

                    #endregion

                    HotelSeason hotelSeason = HotelSeasonRepository.LoadByHotelID(host.SysHotel.ID);//获取该酒店下季节设置记录
                    if (hotelSeason != null)
                    {
                        List<HotelAirControl> list = HotelAirControlRepository.LoadAll(host.SysHotel.ID, 1, 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);//延迟执行
                                        //foreach (HostModal hostModal in hostModals)
                                        //{
                                        //    //host 只需要hostnumber和mac
                                        //    //hostmodal只需要 address //和type
                                        //    //device.Address = hostModal.Modal.ModalAddress;
                                        //    //device.Type = hostModal.Modal.Type;
                                        //    HostModalManager.SetDevice(host, hostModal, item.Status, 0, item.SettingTemp, item.FanSpeed, item.Mode, 0);//0表示不变
                                        //}

                                        var TTT = new Tuple<Host, HotelAirControl, List<HostModal>>(host, item, hostModals);
                                        Task.Factory.StartNew((state) =>
                                            {
                                                System.Threading.Thread.Sleep(item.DelayTime * 1000);//延迟执行

                                                Tuple<Host, HotelAirControl, List<HostModal>> NNN = state as Tuple<Host, HotelAirControl, List<HostModal>>;

                                                var QQ0 = NNN.Item1;
                                                var QQ1 = NNN.Item2;
                                                var QQ2 = NNN.Item3;
                                                foreach (HostModal hostModal in QQ2)
                                                {
                                                    //host 只需要hostnumber和mac
                                                    //hostmodal只需要 address //和type
                                                    //device.Address = hostModal.Modal.ModalAddress;
                                                    //device.Type = hostModal.Modal.Type;
                                                    HostModalManager.SetDevice(QQ0, hostModal, QQ1.Status, 0, QQ1.SettingTemp, QQ1.FanSpeed, QQ1.Mode, 0);//0表示不变
                                                }
                                            }, TTT);
                                        //try
                                        //{
                                            //这段代码在生产环境中不管用，很奇怪
                                            //string KeyMission = System.Guid.NewGuid().ToString("N");

                                            //MissonData m = new MissonData()
                                            //{
                                            //    hostnumber = host.HostNumber,
                                            //    mac = host.MAC,
                                            //};

                                            //m.HostModalList = new List<Tuple<string, DeviceType>>();
                                            //foreach (HostModal hostModal in hostModals)
                                            //{
                                            //    var t = new Tuple<string, DeviceType>(hostModal.Modal.ModalAddress, hostModal.Modal.Type);
                                            //    m.HostModalList.Add(t);
                                            //}
                                            //m.Status = item.Status;
                                            //m.SettingTemp = item.SettingTemp;
                                            //m.FanSpeed = item.FanSpeed;
                                            //m.Mode = item.Mode;
                                            //string MKey = "Mission_" + KeyMission;
                                            //CSRedisCacheHelper.Set_Partition<MissonData>(MKey, m, 1);

                                            //DelayExe_Task(host, item.DelayTime, KeyMission);
                                        //    break;
                                        //}
                                        //catch (Exception)
                                        //{

                                        //}
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
            }
        }
        public class MissonData
        {
            public string hostnumber { get; set; }
            public string mac { get; set; }
            public List<Tuple<string, DeviceType>> HostModalList { get; set; }
            public int Status { get; set; }
            public int SettingTemp { get; set; }
            public int FanSpeed { get; set; }
            public int Mode { get; set; }
        }

        /// <summary>
        ///  任务管理系统是 分钟，这里是秒
        /// </summary>
        /// <param name="host"></param>
        /// <param name="delaytime">秒</param>
        /// <param name="MissionKey"></param>
        private static void DelayExe_Task(Host host, int delaytime, string MissionKey)
        {
            string Code = host.SysHotel.Code;
            string RoomNo = host.RoomNumber;
            DateTime CreateDate = host.SysHotel.CreatedDate;
            string CD = CreateDate.ToString("yyyy-MM-dd");
            int hotel_id = host.SysHotel.ID;
            int host_id = host.ID;
            string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            int sustain = 20;
            DateTime starttime = DateTime.Now.AddSeconds(delaytime);
            DateTime endtime = starttime.AddMinutes(sustain);

            //创建一条任务 插 入数据库
            KongTiaoTimer k = new KongTiaoTimer();
            k.HotelID = hotel_id;
            k.HotelCode = Code;
            k.RoomNo = RoomNo;
            k.MissonKey = MissionKey;
            k.IsCancel = 0;
            k.CreateTime = ti;
            k.StartTime = starttime.ToString("yyyy-MM-dd HH:mm:ss");
            k.EndTime = endtime.ToString("yyyy-MM-dd HH:mm:ss");
            k.CreateDate = CD;

            MissionRequestData mm = new MissionRequestData();

            mm.DelayTimer = delaytime;
            mm.KT = k;
            string jsstr = Newtonsoft.Json.JsonConvert.SerializeObject(mm);

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

            request1.AddParameter("jsonData", jsstr);

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


        /// <summary>
        /// 批量更改主机网络设置
        /// </summary>
        /// <param name="hostList">RCU主机列表</param>
        /// <param name="ip">IP地址</param>
        /// <param name="subnetmask">子网掩码</param>
        /// <param name="gateway">默认网关</param>
        /// <param name="port">通讯端口</param>
        public void ChangeNetworkSetting(IList<Host> hostList, string ip, string subnetmask, string gateway, ushort port)
        {
            foreach (var host in hostList)
            {
                string newIP = GetNewIP(host.IP, ip);

                if (!NetworkSettingReceiver.SetNetwork(host, newIP, subnetmask, gateway, port))
                {
                    throw new ApplicationException("设置客房【" + host.RoomNumber + "】主机网络参数失败。");
                }

                host.IP = newIP;
                host.SubnetMask = subnetmask;
                host.Gateway = gateway;
                host.Port = port;
                CurrentRepository.Update(host);
            }
        }

        #endregion

        #region Private Methods

        private bool UpdateHostAirs(Host host)
        {
            HostAirRepository.DeteleByHostID(host.ID);

            var list = RoomTypeAirRepository.LoadAll().Where(r => r.RoomType == host.RoomType);

            foreach (var modal in list)
            {
                var hostAir = new HostAir();

                hostAir.HostID = host.ID;
                hostAir.Modal = modal;
                hostAir.ControlType = host.RoomType.ControlType;

                HostAirRepository.SaveOrUpdate(hostAir);
            }

            return true;
        }

        private bool UpdateHostModals(Host host)
        {
            if (host == null)
            {
                return false;
            }
            HostModalRepository.DeteleByHostID(host.ID);
            var list = RoomTypeModalRepository.LoadAll().Where(r => r.RoomType == host.RoomType);
            DateTime now = DateTime.Now;
            foreach (var modal in list)
            {
                HostModalRepository.Save(new HostModal { HostID = host.ID, Modal = modal, Status = 2, Time = 0, UpdateTime = now });
            }

            return true;
        }

        /// <summary>
        /// 创建服务异常
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        private bool CreateServiceAndAbnormity(Host host)
        {
            if (host == null)
            {
                return false;
            }

            try
            {
                var services = RoomServiceRepository.LoadAll(host.ID);
                foreach (var service in services)
                {
                    RoomServiceRepository.Delete(service.ID);
                }

                var servicesSetting = AlarmSettingRepository.LoadAll().Where(r => r.HotelID == host.SysHotel.ID && (r.Type == 'B' || r.Type == 'C'));

                foreach (var serviceSetting in servicesSetting)
                {
                    var service = new RoomService();
                    service.HostID = host.ID;
                    service.AlarmType = serviceSetting.Type;
                    service.AlarmCode = serviceSetting.Code;
                    service.Status = false;
                    RoomServiceRepository.Save(service);
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 读取连通房到 connectingRooms 中
        /// </summary>
        /// <param name="host"></param>
        /// <param name="connectingRooms"></param>
        //private void ReadConnectRoomsToList(Host host, IList<Host> connectingRooms)
        //{
        //    if (String.IsNullOrEmpty(host.ConnectingRooms))
        //    {
        //        return;
        //    }

        //    var hosts = host.ConnectingRooms.Split(',').Select(r => Get(int.Parse(r)));

        //    foreach (var h in hosts)
        //    {
        //        if (h != null && !connectingRooms.Contains(h))
        //        {
        //            connectingRooms.Add(h);
        //        }
        //    }
        //}

        /// <summary>
        /// 复制ip2地址前两段到ip1
        /// </summary>
        /// <param name="ip1">IP1</param>
        /// <param name="ip2">IP2</param>
        /// <returns></returns>
        private string GetNewIP(string ip1, string ip2)
        {
            string[] ip1Arr = ip1.Split('.');
            string[] ip2Arr = ip2.Split('.');
            ip1Arr[0] = ip2Arr[0];
            ip1Arr[1] = ip2Arr[1];

            return String.Join(".", ip1Arr);
        }
        /// <summary>
        /// 处理“退房保险箱关”异常
        /// </summary>
        /// <param name="host"></param>
        private void ProcessAbnormities(Host host)
        {
            //如果是退房，并且保险箱是关的状态，报警，否则存在此报警，关掉
            var abnormity = RoomServiceRepository.Get(host.ID, "C04");
            if (host.RoomStatus.ID == 0x08)
            {
                if (host.SafeStatus == 0 && abnormity != null && !abnormity.Status)
                {
                    abnormity.Status = true;
                    abnormity.StartTime = DateTime.Now;
                    RoomServiceRepository.Update(abnormity);
                }
            }
            else //if (host.SafeStatus != 0)
            {
                if (abnormity != null && abnormity.Status)
                {
                    abnormity.Status = false;//关掉报警
                    abnormity.StartTime = DateTime.Now;
                    RoomServiceRepository.Update(abnormity);
                }
            }
        }

        #endregion


        public void AccreditForHost(IList<Host> hostList, DateTime expires)
        {
            AuthorizationReceiver.AccreditForHost(hostList, expires);
        }

        public void SetDeviceSecret(Host host)
        {
            DeviceSecretReceiver.Send(host);
        }

        public void SendForGetHostSecret(Host host)
        {
            HostSecretReceiver.Send(host);
        }

        public void SyncHostInfo(Host host)
        {
            HostRegisterReceiver.Send(host);
        }

        public void PublishHostInfo(Host host)
        {
            HostRegisterSetReceiver.Send(host);
        }

        public void PublishHostInfo(Host host, byte[] sendData)
        {
            HostRegisterSetReceiver.Send(host, sendData);
        }

        /// <summary>
        /// 根据房型获取主机列表（C主机升级使用）
        /// </summary>
        /// <param name="hotelID"></param>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        public IList<Object> LoadHostByRoomType(int hotelID, int roomTypeID)
        {
            return (CurrentRepository as Dao.IHostRepository).LoadHostByRoomType(hotelID, roomTypeID);
        }


        public IList<Object> LoadHostByRoomTypeChengZiHao(int hotelID, int roomTypeID, string roomNumber)
        {
            return (CurrentRepository as Dao.IHostRepository).LoadHostByRoomTypeChengZiHao(hotelID, roomTypeID, roomNumber);
        }
        /// <summary>
        /// 根据房型获取所有主机列表
        /// </summary>
        /// <param name="hotelID"></param>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        public IList<Object> LoadAllHostByRoomType(int hotelID, int roomTypeID)
        {
            return (CurrentRepository as Dao.IHostRepository).LoadAllHostByRoomType(hotelID, roomTypeID);
        }


        /// <summary>
        /// 阿宝
        /// </summary>
        public List<KongTiaoTimer> GetInitializeKTMission()
        {
            return KongTiaoManager.Select();
        }


        public static readonly string Missionsys_Address = ConfigurationManager.AppSettings["missionsys_address"];
        public static readonly string Currentsys_address = ConfigurationManager.AppSettings["currentsys_address"];

        public void TimerECO(string hotelcode, int sheng_jiang_value)
        {
            try
            {
                int finallytemp = 0;
                //模式：1制冷，2制热，3送风
                var hostlist = HostRepository.GetByHotelCode(hotelcode);

                foreach (var item in hostlist)
                {
                    List<HostModal> hostModals = HostModalRepository.LoadByHostID(item.ID).Where(r => r.Modal.Type == DeviceType.AirConditioner && r.Modal.ActiveIndicator).ToList();
                    foreach (HostModal hostModal in hostModals)
                    {
                        string KKey = CacheKey.HostModalStatus_Prefix + "_" + item.ID + "_" + hostModal.Modal.ModalAddress;
                        var mm = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                        if (mm != null)
                        {
                            int s = mm.Status;
                            int sss = mm.AirConditionData.SettingTemp;
                            int model = mm.AirConditionData.Mode;
                            if (s == 1)
                            {

                                if (model == 1)
                                {
                                    finallytemp = sss + sheng_jiang_value;
                                }
                                if (model == 2)
                                {

                                    finallytemp = sss - sheng_jiang_value;
                                }
                                //获取 触发的 酒店
                                //循环这些 酒店，获取每个房间，获取每个房间的 空调，如何开的话 ，就触发
                                Host host111 = new Host();
                                host111.HostNumber = item.HostNumber;
                                host111.MAC = item.MAC;
                                //host 只需要hostnumber和mac
                                //hostmodal只需要 address 和type
                                //device.Address = hostModal.Modal.ModalAddress;
                                //device.Type = hostModal.Modal.Type;
                                HostModal hm = new HostModal();
                                hm.Modal = new RoomTypeModal();
                                hm.Modal.Type = DeviceType.AirConditioner;
                                hm.Modal.ModalAddress = hostModal.Modal.ModalAddress;
                                logger.Error("ECO系统要开始执行了:" + host111.RoomNumber + " air_condition stattus: " + finallytemp);
                                //HostModalManager.SetDevice(host111, hm, 1, 0, GenericData.SetTemperatureValue, GenericData.FanSpeed, GenericData.Mode, 0);//0表示不变
                                HostModalManager.SetDevice(host111, hm, 0, 0, finallytemp, 0, 0, 0);//0表示不变
                            }
                        }

                    }
                }



            }
            catch (Exception ex)
            {
                logger.Error("ECO 系统出异常了" + ex.Message);
            }
        }

        /// <summary>
        /// 任务控制
        /// </summary>
        /// <param name="hotel_id"></param>
        /// <param name="HotelCode"></param>
        /// <param name="host_id"></param>
        /// <param name="RoomNo"></param>
        /// <param name="k"></param>
        public void AirConditionTimer_Controller(int hotel_id, string HotelCode, string HotelCreateDate, int host_id, string RoomNo, KongTiaoTimer k)
        {
            try
            {
                string LieECOTaskKey = CacheKey.LieECOTask;
                string MKey = k.MissonKey;
                bool OldOrNew0 = MKey.StartsWith("TuiFang");
                bool OldOrNew1 = MKey.StartsWith("Mission");
                bool OldOrNew2 = MKey.StartsWith(LieECOTaskKey);
                if (OldOrNew0)
                {
                    NewMission(MKey);
                    return;
                }
                else if (OldOrNew1)
                {
                    NewMission(MKey);
                    return;
                }
                else if (OldOrNew2)
                {
                    var GenericData = CSRedisCacheHelper.Get_Partition<LieECOTaskExtra>(MKey, 1);
                    if (GenericData != null)
                    {
                        try
                        {
                            Host host111 = new Host();
                            host111.HostNumber = GenericData.HostNUMBER;
                            host111.MAC = GenericData.MAC;
                            //host 只需要hostnumber和mac
                            //hostmodal只需要 address 和type
                            //device.Address = hostModal.Modal.ModalAddress;
                            //device.Type = hostModal.Modal.Type;
                            HostModal hm = new HostModal();
                            hm.Modal = new RoomTypeModal();
                            hm.Modal.Type = DeviceType.AirConditioner;
                            hm.Modal.ModalAddress = GenericData.ModalAddress;
                            logger.Error("ECO系统要开始执行了:" + host111.RoomNumber + " air_condition stattus: " + GenericData.SetTemperatureValue);
                            //HostModalManager.SetDevice(host111, hm, 1, 0, GenericData.SetTemperatureValue, GenericData.FanSpeed, GenericData.Mode, 0);//0表示不变
                            HostModalManager.SetDevice(host111, hm, 0, 0, GenericData.SetTemperatureValue, 0, 0, 0);//0表示不变
                        }
                        catch (Exception ex)
                        {
                            logger.Error("ECO 系统出异常了" + ex.Message);
                        }
                    }
                }
                else
                {

                    string ct = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    RoomNobodyHowToLog n = new RoomNobodyHowToLog() { MissionKey = MKey, CreateTime = ct };
                    Host host = GetByRoomNumber(RoomNo, hotel_id);
                    if (host == null)
                    {
                        return;
                    }
                    //查询 现在有没有补取电
                    //string KKey = CacheKey.HostModalStatus_Prefix + "_" +host_id + "_" + device.Value.Address;
                    //var client = new RestClient("https://pms.boonlive-rcu.com/");
                    //var client = new RestClient(Currentsys_address);
                    //var request = new RestRequest("api/GetRoomServiceList", Method.GET);
                    //GetRequest ggg = new GetRequest() { creatDate = HotelCreateDate, roomNumber = RoomNo, code = HotelCode };
                    //string jsstr = Newtonsoft.Json.JsonConvert.SerializeObject(ggg);
                    //request.AddParameter("jsonData", jsstr);
                    //var response = client.Execute(request);
                    //string str = response.Content;
                    logger.Error("222:");
                    //logger.Error("333333:" + str);

                    string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000001";
                    var mm = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                    //333333:{"IsSuccess":true,"Result":[{"ModalAddress":"004000002","Name":"勿扰","Status":2,"Brightness":0},{"ModalAddress":"004000003","Name":"清理","Status":2,"Brightness":0}]}
                    //{"IsSuccess":true,"Result":[{"ModalAddress":"004000001",
                    //    "Name":"取电","Status":2,"Brightness":0},
                    //{"ModalAddress":"004000003","Name":"清理","Status":2,"Brightness":0}]}
                    if (mm != null)
                    {
                        var Nstr = Newtonsoft.Json.JsonConvert.SerializeObject(mm);
                        logger.Error("222:" + Nstr);
                        logger.Error("takecard:" + mm.Status);
                        //超过了30分钟，还没有取电
                        //如果没有取电就关了空调
                        //1 为取电，2为没有取电
                        if (mm.Status != 1)
                        {
                            List<HostModal> hostModals = new List<HostModal>();
                            //获取启用的空调回路
                            string Hkey = "HostManagerHostModal_" + host_id;
                            var ddd = MemoryCacheHelper.Get(Hkey);
                            if (ddd != null)
                            {
                                hostModals = ddd as List<HostModal>;
                            }
                            else
                            {
                                hostModals = HostModalRepository.LoadByHostID(host_id).Where(r => r.Modal.Type == DeviceType.AirConditioner && r.Modal.ActiveIndicator).ToList();
                                MemoryCacheHelper.Set(Hkey, hostModals, DateTimeOffset.Now.AddMinutes(30));
                            }

                            RoomNobodyHowTo nnn = null;
                            string RKey = "RNO_" + hotel_id;
                            var ooo = MemoryCacheHelper.Get(RKey);
                            if (ooo != null)
                            {
                                nnn = ooo as RoomNobodyHowTo;
                            }
                            else
                            {
                                nnn = RoomNoBodyMananger.LoadAll().FirstOrDefault(A => A.CurrentHotelID == hotel_id);
                                MemoryCacheHelper.Set(RKey, nnn, DateTimeOffset.Now.AddMinutes(30));
                            }
                            if (nnn != null)
                            {
                                foreach (HostModal hostModal in hostModals)
                                {
                                    logger.Error("nnn.how " + nnn.How);
                                    //close  or monitor
                                    if (nnn.How.Equals("close"))
                                    {
                                        //0表示不变
                                        HostModalManager.SetDevice(host, hostModal, 2, 0);
                                        RoomNoBodyLogMananger.Save(n);

                                    }
                                    else if (nnn.How.Equals("monitor"))
                                    {

                                        //状态：1开，2关，6停
                                        //0表示不变
                                        //如果只调温的话，所有的数据都要设置为0
                                        HostModalManager.SetDevice(host, hostModal, 0, 0, nnn.Temperature);

                                        RoomNoBodyLogMananger.Save(n);
                                        logger.Error("monitor is !!!!" + nnn.Temperature);
                                    }
                                    else
                                    {
                                    }
                                }
                            }

                            logger.Error("Air Condition Controller");
                            //空调关闭后，就将任务设置成已经完成了
                            k.IsCancel = 1;

                            KongTiaoManager.Update(k);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
            }
        }

        private void NewMission(string MKey)
        {
            var MMK = CSRedisCacheHelper.Get_Partition<MissonData>(MKey, 1);
            if (MMK != null)
            {
                Host host111 = new Host();
                host111.HostNumber = MMK.hostnumber;
                host111.MAC = MMK.mac;
                var L = MMK.HostModalList;
                foreach (var hostModal in L)
                {
                    //host 只需要hostnumber和mac
                    //hostmodal只需要 address 和type
                    //device.Address = hostModal.Modal.ModalAddress;
                    //device.Type = hostModal.Modal.Type;
                    HostModal hm = new HostModal();
                    hm.Modal = new RoomTypeModal();
                    hm.Modal.Type = hostModal.Item2;
                    hm.Modal.ModalAddress = hostModal.Item1;
                    logger.Error("delay Mission start:" + host111.RoomNumber + " air_condition stattus: " + MMK.Status);
                    HostModalManager.SetDevice(host111, hm, MMK.Status, 0, MMK.SettingTemp, MMK.FanSpeed, MMK.Mode, 0);//0表示不变
                }
            }
            return;
        }

        public void LoggerTest()
        {
            string MKey = "aaaaaaaaa";
            string ct = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            RoomNobodyHowToLog n = new RoomNobodyHowToLog() { MissionKey = MKey, CreateTime = ct };

            RoomNoBodyLogMananger.Save(n);
        }

        /// <summary>
        /// ECO模式执行
        /// </summary>
        public void ECO_Execute(string hotelid_api)
        {
            try
            {
                logger.Error("ECO_Execute here");
                //取出ECO配置的酒店 的房间号
                List<ECO_Setting> ECOList = ECO_SettingRepository.LoadAll().ToList();

                if (ECOList.Count > 0)
                {
                    foreach (var ECO in ECOList)
                    {

                        int hotelid = ECO.HotelID;
                        bool isenable = ECO.IsEnable;

                        string st_time = ECO.StartTime;

                        string[] h_m = st_time.Split(':');
                        int a1 = 0;
                        int.TryParse(h_m[0], out a1);

                        int b1 = 0;
                        int.TryParse(h_m[1], out b1);

                        string et_time = ECO.EndTime;
                        string[] h_m_1 = et_time.Split(':');
                        int a2 = 0;
                        int.TryParse(h_m_1[0], out a2);

                        int b2 = 0;
                        int.TryParse(h_m_1[1], out b2);

                        var ccc = DateTime.Now;
                        var start_time = new DateTime(ccc.Year, ccc.Month, ccc.Day, a1, b1, 0);
                        var end_time = new DateTime(ccc.Year, ccc.Month, ccc.Day, a2, b2, 0);


                        //节能模式开启了
                        if (isenable)
                        {
                            //当前时间在两个时间 区间内
                            if (ccc > start_time && ccc < end_time)
                            {
                                //获取当前酒店的主机
                                //IList<Host> hosts = LoadAll(hotelid).Where(r => r.Status == true).ToList();
                                IList<Host> hosts = LoadAll(hotelid).ToList();

                                foreach (Host host in hosts)
                                {
                                    int host_id = host.ID;
                                    //查看是否执行过了
                                    ECO_Detail detail = ECO_DetailRepository.GetDetail(hotelid, host_id);
                                    if (detail == null)
                                    {
                                        AirConditionECO_Execute(ECO, host);
                                        ECO_Detail e = new ECO_Detail();
                                        e.HotelID = hotelid;
                                        e.HostID = host_id;
                                        e.IsTrigger = true;
                                        e.RoomNo = host.RoomNumber;
                                        string ct = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                        e.TriggerTime = ct;
                                        e.ECO_ID = ECO.ID;
                                        ECO_DetailRepository.Add(e);
                                    }
                                    if (detail != null && !detail.IsTrigger)
                                    {
                                        //获取启用的空调回路
                                        AirConditionECO_Execute(ECO, host);


                                        detail.IsTrigger = true;
                                        string ct = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                        detail.TriggerTime = ct;
                                        ECO_DetailRepository.Update(detail);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("ECO execute error: " + ex.Message);
            }

        }


        /// <summary>
        /// 重置
        /// </summary>
        public void Zero_Refresh()
        {
            ECO_DetailRepository.ZeroRefresh();
        }


        private void AirConditionECO_Execute(ECO_Setting ECO, Host host)
        {
            int host_id = host.ID;
            //根据主机编号，获取所有的空调
            //获取所有空调的数据
            List<HostModal> hostModals = HostModalRepository.LoadByHostID(host_id).Where(r => r.Modal.Type == DeviceType.AirConditioner && r.Modal.ActiveIndicator).ToList();
            foreach (HostModal hostModal in hostModals)
            {
                string KKey = CacheKey.HostModalStatus_Prefix + "_" + host_id + "_" + hostModal.Modal.ModalAddress;
                var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                if (obj != null)
                {
                    HostModal_Cache hhh = obj as HostModal_Cache;

                    if (hhh.AirConditionData.AirStatus == 1 && hhh.Status == 1)
                    {
                        int settemp = 0;
                        //0x01:制冷
                        //0x02:制热
                        //0x03:送风

                        int moshi = hhh.AirConditionData.Mode;
                        if (moshi == 1)
                        {
                            //如果是制冷 ，那就将温度调高一些
                            settemp = hhh.AirConditionData.CurrentTemp + ECO.ActValue;
                        }
                        else if (moshi == 2)
                        {
                            settemp = hhh.AirConditionData.CurrentTemp - ECO.ActValue;
                        }
                        else
                        {

                        }

                        hostModal.Brightness = hhh.Brightness;
                        hostModal.Status = hhh.Status;
                        hostModal.SettingTemp = hhh.AirConditionData.SettingTemp;
                        hostModal.CurrentTemp = hhh.AirConditionData.CurrentTemp;
                        hostModal.Mode = hhh.AirConditionData.Mode;
                        hostModal.FanSpeed = hhh.AirConditionData.FanSpeed;
                        hostModal.Valve = hhh.AirConditionData.Valve;
                        //状态：1开，2关，6停
                        //0表示不变
                        //如果只调温的话，所有的数据都要设置为0
                        HostModalManager.SetDevice(host, hostModal, 0, 0, settemp);
                    }
                }
            }
        }



        public List<ECO_Setting> Get_ECOList()
        {
            return ECO_SettingRepository.LoadAll().Where(A => A.IsEnable == true).ToList();
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="data"></param>
        /// <param name="host_number"></param>
        /// <param name="mac"></param>
        public void Send_Query_Data(byte[] data, string host_number, string mac)
        {
            TFTP_LogReceiver.Send_QueryData(data, host_number, mac);
        }

        /// <summary>
        /// 发送设置
        /// </summary>
        /// <param name="data"></param>
        /// <param name="host_number"></param>
        /// <param name="mac"></param>
        public void Send_Setting_Data(byte[] data, string host_number, string mac)
        {
            TFTP_LogSettingReceiver.Send_Setting_Data(data, host_number, mac);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="roomid"></param>
        /// <param name="hotelID"></param>
        /// <returns></returns>
        public Host GetByRoomNumber(int roomid, int hotelID)
        {
            return CurrentRepository.LoadAll().FirstOrDefault(r => r.ID == roomid && r.SysHotel.ID == hotelID && !r.IsDeleted);
        }


        public Host GetByHiWeiCUID(string cuid)
        {
            return (CurrentRepository as Dao.IHostRepository).GetByHiWeiCUID(cuid);
        }


        public void PublishUDPData(string hostnumber, string mac, byte[] data, byte cmdtype, bool isoriginal)
        {
            HostUDPTouChuan.Send(hostnumber, mac, data, cmdtype, isoriginal);
        }

        public IList<HostMappingData> LoadAllID_HostNumberMapping()
        {
            return (CurrentRepository as Dao.IHostRepository).LoadAllID_HostNumberMapping();
        }


        public IList<HostRoomNumberMapping> LoadAll_RoomNumberMapping()
        {
            return (CurrentRepository as Dao.IHostRepository).LoadAll_RoomNumberMapping();
        }
    }



    //
    //{"IsSuccess":true,"Result":[{"ModalAddress":"004000001",
    //    "Name":"取电","Status":2,"Brightness":0},
    //{"ModalAddress":"004000003","Name":"清理","Status":2,"Brightness":0}]}
    public class ResultData
    {
        public bool IsSuccess { get; set; }
        public List<MySheBei> Result { get; set; }
    }
    public class MySheBei
    {
        public string ModalAddress { get; set; }
        public string Name { get; set; }
        public int Status { get; set; }
        public int Brightness { get; set; }
    }

    //"{\"creatDate\":\"2023-11-16\",\"roomNumber\":\"2206\",\"code\":\"1762\"}"
    public class GetRequest
    {
        public string creatDate { get; set; }
        public string roomNumber { get; set; }
        public string code { get; set; }
    }

}
