using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using Common;
using Domain;
using NHibernate;
using NHibernate.Criterion;
using CommonEntity;

namespace Dao.Implement
{
    public class HostRepository : RepositoryBase<Host>, IHostRepository
    {
        public IList<Host> LoadAll(string order, string sort, IList<Group> groups, string roomNumber)
        {
            int[] groupIDs = groups.Select(r => r.ID).ToArray();
            var list = Session.QueryOver<Host>().Where(r => r.IsDeleted != true);
            if (!String.IsNullOrEmpty(roomNumber))
            {
                list = list.Where(r => r.RoomNumber == roomNumber);
            }
            if (groupIDs != null)
            {
                list = list.WhereRestrictionOn(r => r.Group.ID).IsIn(groupIDs);
            }
            list.OrderBy(sort, order);
            return list.List();
        }

        public IList<Host> LoadAll(IList<Group> groupList)
        {
            var list = Session.QueryOver<Host>().Where(r => !r.IsDeleted);
            if (groupList != null && groupList.Count > 0)
            {
                list.WhereRestrictionOn(r => r.Group.ID).IsIn(groupList.Select(r => r.ID).ToArray());
            }
            return list.List();
        }

        /// <summary>
        /// 这段代码有BUG
        /// </summary>
        /// <param name="hotelID"></param>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
        public IList<Host> LoadAll(int hotelID, string roomNumber = "")
        {
            if (string.IsNullOrEmpty(roomNumber))
            {
                return Session.QueryOver<Host>().Where(r => !r.IsDeleted && r.SysHotel.ID == hotelID).List();
            }
            else
            {
                return Session.QueryOver<Host>().Where(r => !r.IsDeleted && r.SysHotel.ID == hotelID && r.RoomNumber == roomNumber).List();
            }
        }

        public IList<Host> GetByHotelCode(string hotelcode)
        {
            return base.LoadAll().Where(r => !r.IsDeleted && r.SysHotel.Code.Equals(hotelcode)).ToList();
        }


        public IList<Host> LoadAll(IList<Group> groupList, RoomStatus roomStatus, RoomType roomType)
        {
            var list = Session.QueryOver<Host>().Where(r => !r.IsDeleted); ;
            if (roomStatus != null)
            {
                list.Where(r => r.RoomStatus == roomStatus);
            }
            if (roomType != null)
            {
                list.Where(r => r.RoomType == roomType);
            }
            if (groupList != null && groupList.Count > 0)
            {
                list.WhereRestrictionOn(r => r.Group.ID).IsIn(groupList.Select(r => r.ID).ToArray());
            }
            return list.List();
        }

        public IQueryable<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)
        {
            var list = this.LoadAll().Where(r => !r.IsDeleted && (r.SysHotel.ID == hotelID) && ((r.Group.ID == groupId) || (r.Group.Parent != null && r.Group.Parent.ID == groupId)));
            if (!string.IsNullOrEmpty(roomNumber))
            {
                list = list.Where(r => r.RoomNumber.Contains(roomNumber));
            }
            if (!string.IsNullOrEmpty(mac))
            {
                list = list.Where(r => r.MAC.Contains(mac));
            }
            if (!string.IsNullOrEmpty(roomType))
            {
                list = list.Where(r => r.RoomType.Name.Contains(roomType));
            }
            switch (isSyncRoomNumber)
            {
                case 0:
                    list = list.Where(r => r.IsSyncRoomNumber == false);
                    break;
                case 1:
                    list = list.Where(r => r.IsSyncRoomNumber == true);
                    break;
            }
            total = list.LongCount();
            list = list.OrderBy(sort + " " + order);
            list = list.Skip((page - 1) * rows).Take(rows);
            return list;
        }
        /// <summary>
        /// 重载删除，只做标记
        /// </summary>
        /// <param name="id"></param>
        public override void Delete(object id)
        {
            var entity = this.HibernateTemplate.Get<Host>(id);
            if (entity == null)
            {
                return;
            }
            entity.MAC = entity.MAC + "-del";
            entity.IsDeleted = true;
            entity.Last_Modified_Time = DateTime.Now;
            this.HibernateTemplate.Update(entity);
        }
        /// <summary>
        /// 重载删除，只做标记
        /// </summary>
        /// <param name="idList"></param>
        public override void Delete(IList<object> idList)
        {
            foreach (var id in idList)
            {
                var entity = this.HibernateTemplate.Get<Host>(id);
                if (entity == null)
                {
                    return;
                }
                entity.MAC = entity.MAC + "-del";
                entity.IsDeleted = true;
                entity.Last_Modified_Time = DateTime.Now;
                this.HibernateTemplate.Update(entity);
            }
        }

        public DataTable LoadHostWithPage(out long total, int page, int rows, string order, string sort, int groupId, int hotelID, string roomNumber, string mac, string roomType)
        {
            total = 0;

            //using (IStatelessSession session = SessionFactory.OpenStatelessSession())
            //using (IDbCommand cmd = session.Connection.CreateCommand())
            //{
            IDbCommand cmd = Session.Connection.CreateCommand();
            cmd.CommandText = "QueryHostWithPage";
            cmd.CommandType = CommandType.StoredProcedure;

            IDbDataParameter parameter = cmd.CreateParameter();
            parameter.ParameterName = "@total";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@page";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = page;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@rows";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = rows;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@order";
            parameter.DbType = DbType.String;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = order;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@sort";
            parameter.DbType = DbType.String;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = sort;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@groupId";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = groupId;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@hotelID";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = hotelID;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@roomNumber";
            parameter.DbType = DbType.String;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = roomNumber;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@mac";
            parameter.DbType = DbType.String;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = mac;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@roomType";
            parameter.DbType = DbType.String;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = roomType;
            cmd.Parameters.Add(parameter);

            IDbDataAdapter da = new SqlDataAdapter(cmd as SqlCommand);
            DataSet ds = new DataSet();
            da.Fill(ds);
            parameter = cmd.Parameters["@total"] as IDbDataParameter;
            total = (parameter != null && parameter.Value != null && parameter.Value != DBNull.Value) ? Convert.ToInt64(parameter.Value) : 0;
            return ds.Tables[0];
            //}
        }

        public IList<Room> LoadRooms(out long total, int page, int rows, int? groupId, int lang, int hotelID)
        {
            IDbCommand cmd = Session.Connection.CreateCommand();

            cmd.CommandText = "QueryRoomInfo";
            cmd.CommandType = CommandType.StoredProcedure;

            var parameter = cmd.CreateParameter();
            parameter.ParameterName = "@total";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@page";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = page;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@rows";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = rows;
            cmd.Parameters.Add(parameter);

            if (groupId.HasValue)
            {
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "@groupId";
                parameter.DbType = DbType.Int32;
                parameter.Direction = ParameterDirection.Input;
                parameter.Value = groupId;
                cmd.Parameters.Add(parameter);
            }

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@lang";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = lang;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@hotelID";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = hotelID;
            cmd.Parameters.Add(parameter);

            IDbDataAdapter adapter = new SqlDataAdapter(cmd as SqlCommand);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            //parameter = cmd.Parameters["@total"] as IDbDataParameter;
            //total = (parameter != null && parameter.Value != null && parameter.Value != DBNull.Value) ? Convert.ToInt64(parameter.Value) : 0;

            IList<Room> rooms = new List<Room>();
            foreach (DataRow dataRow in ds.Tables[0].Rows)
            {
                Room room = new Room();
                room.HostID = Convert.ToInt32(dataRow["ID"]);
                room.HostNumber = Convert.ToString(dataRow["HostNumber"]);
                //房间状态从数据库里面拉取
                var aaa = Common.CSRedisCacheHelper.Contains(Convert.ToString(dataRow["HostNumber"]),
                    Convert.ToString(dataRow["MAC"]));
                //System.IO.File.WriteAllText("1.txt","ffffff:"+aaa);
                room.HostStatus = aaa;// Convert.ToInt32(dataRow["HostStatus"]);
                room.IP = Convert.ToString(dataRow["IP"]);
                room.RoomNumber = Convert.ToString(dataRow["RoomNumber"]);
                room.RoomStatus = Convert.ToString(dataRow["RoomStatus"]);
                room.RoomStatusID = Convert.ToInt32(dataRow["RoomStatusID"]);
                room.DoorLock = Convert.ToBoolean(dataRow["DoorLock"]);
                room.Identity = Convert.ToString(dataRow["Identity"]);
                //room.IsConnectingRoom = Convert.ToBoolean(dataRow["IsConnectingRoom"]);
                room.GroupID = Convert.ToInt32(dataRow["GroupID"]);
                room.GroupSort = Convert.ToInt32(dataRow["GroupSort"]);
                room.MAC = Convert.ToString(dataRow["MAC"]);
                room.PowerSupply = Convert.ToBoolean(dataRow["PowerSupply"]);
                room.LockStatus = Convert.ToInt16(dataRow["LockStatus"]);
                room.LockVoltage = Convert.ToSingle(dataRow["LockVoltage"]);
                room.PeripheralOfflineCount = Convert.ToInt16(dataRow["PeripheralOfflineCount"]);
                room.PeripheralLowPowerCount = Convert.ToInt16(dataRow["PeripheralLowPowerCount"]);

                rooms.Add(room);
            }
            total = rooms.Count;
            return rooms;
        }

        public IList<Host> LoadAllByGroups(IList<int> groupIDs)
        {
            return Session.QueryOver<Host>().WhereRestrictionOn(r => r.Group.ID).IsIn(groupIDs.ToArray()).List();
        }

        public Host GetByHostNumber(string hostNumber, string code = "")
        {
            if (string.IsNullOrEmpty(code))
            {
                return base.LoadAll().Where(r => r.HostNumber == hostNumber && !r.IsDeleted).FirstOrDefault();
            }
            else
            {
                return base.LoadAll().Where(r => r.SysHotel.Code == code && r.HostNumber == hostNumber && !r.IsDeleted).FirstOrDefault();
            }
        }

        public Host GetByMAC(string mac, int hotelID)
        {
            return base.LoadAll().Where(r => r.MAC == mac && r.SysHotel.ID == hotelID && !r.IsDeleted).FirstOrDefault();
        }

        //public Host GetByRoomNumber(string roomNumber, string code)
        //{
        //    return base.LoadAll().Where(r => r.RoomNumber == roomNumber && r.SysHotel.Code == code).FirstOrDefault();
        //}

        public Host GetByXiaoDuCUID(string cuid)
        {
            return base.LoadAll().Where(r => r.XiaoDuCUID.Contains(cuid) && !r.IsDeleted).FirstOrDefault();
        }

        public Host GetByTianMaoCUID(string cuid)
        {
            return base.LoadAll().Where(r => r.TianMaoCUID.Contains(cuid) && !r.IsDeleted).FirstOrDefault();
        }

        public Host GetByHuaWeiCUID(string cuid)
        {
            return base.LoadAll().Where(r => r.HuaWeiCUID.Contains(cuid) && !r.IsDeleted).FirstOrDefault();
        }

        public Host GetByTCLCUID(string cuid)
        {
            return base.LoadAll().Where(r => r.TCLCUID.Contains(cuid) && !r.IsDeleted).FirstOrDefault();
        }
        /// <summary>
        /// 通过mac地址获取主机列表（只限C系列主机）
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        public IList<Host> LoadByMac(string mac)
        {
            //return base.LoadAll().Where(r => r.MAC == mac && r.Version.StartsWith("C") && !r.IsDeleted).ToList();
            var Q = base.LoadAll().Where(r => r.MAC.Equals(mac) && !r.IsDeleted).ToList();
            var QS = Q.Where(A => A.Version.StartsWith("C")).ToList();
            return QS;
        }

        //public Host GetByIP(string ip)
        //{
        //    return base.LoadAll().Where(r => r.IP == ip).FirstOrDefault();
        //}

        public IList<Host> GetByGroup(Group group)
        {
            return base.LoadAll().Where(r => r.Group == group && !r.IsDeleted).OrderBy(r => r.RoomNumber).ToList();
        }

        public int GetHostsCount()
        {
            return base.LoadAll().Where(r => !r.IsDeleted).Count();
        }

        public DataTable LoadRoomNumbers(Group group, int hotelID)
        {
            IDbCommand cmd = Session.Connection.CreateCommand();

            cmd.CommandText = "LoadRoomNumbersByGroup";
            cmd.CommandType = CommandType.StoredProcedure;

            IDbDataParameter parameter = cmd.CreateParameter();
            parameter.ParameterName = "@groupId";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = group != null ? group.ID : 0;
            cmd.Parameters.Add(parameter);

            parameter = cmd.CreateParameter();
            parameter.ParameterName = "@hotelID";
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.Input;
            parameter.Value = hotelID;
            cmd.Parameters.Add(parameter);

            IDbDataAdapter da = new SqlDataAdapter(cmd as SqlCommand);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds.Tables[0];
        }
        /// <summary>
        /// 设置主机基本信息（房态更新命令调用）
        /// </summary>
        /// <param name="host"></param>
        public void SetHostInfo(Host host)
        {
            string sql = sql = "UPDATE tb_Hosts SET FrameNo=?,PowerSupply=?,LockVoltage=?,HostTemp=?,FrameNoTime=GETDATE() WHERE ID=?";
            IQuery query = query = Session.CreateSQLQuery(sql);
            query.SetInt32(0, host.FrameNo);
            query.SetBoolean(1, host.PowerSupply);
            query.SetSingle(2, host.LockVoltage);
            query.SetInt32(3, host.HostTemp);
            query.SetInt32(4, host.ID);
            query.ExecuteUpdate();
        }
        /// <summary>
        /// 设置房卡：插卡同时插入新记录，拔卡同时更新拔卡时间
        /// </summary>
        /// <param name="host"></param>
        /// <param name="roomCard"></param>
        public void SetRoomCard(Host host, RoomCard roomCard)
        {
            //using (IStatelessSession session = SessionFactory.OpenStatelessSession())
            //{
            host.RoomCard = roomCard;
            string sql;
            IQuery query;
            if (roomCard != null)
            {
                sql = "UPDATE tb_Hosts SET RoomCardID=? WHERE ID=?";//插卡同时设置卡ID
                query = Session.CreateSQLQuery(sql);
                //query = session.CreateSQLQuery(sql);
                query.SetInt32(0, roomCard.ID);
                query.SetInt32(1, host.ID);
                query.ExecuteUpdate();

                sql = "INSERT tb_HostRoomCard (HostID,RoomNumber,RoomCardID,CardNumber,CardTypeID,UserNumber,UserName,InCardTime)VALUES(?,?,?,?,?,?,?,?)";
                query = Session.CreateSQLQuery(sql);
                query.SetInt32(0, host.ID);
                query.SetString(1, host.RoomNumber);
                query.SetInt32(2, roomCard.ID);
                query.SetString(3, roomCard.CardNumber);
                query.SetInt32(4, roomCard.RoomCardType.ID);
                query.SetString(5, roomCard.UserNumber);
                query.SetString(6, roomCard.UserName);
                query.SetDateTime(7, DateTime.Now);
                query.ExecuteUpdate();
            }
            else
            {
                sql = "UPDATE tb_Hosts SET RoomCardID=NULL WHERE ID=?";//拔卡，同时更新拔卡时间
                query = Session.CreateSQLQuery(sql);
                query.SetInt32(0, host.ID);
                query.ExecuteUpdate();

                sql = "UPDATE tb_HostRoomCard SET OutCardTime=GETDATE() WHERE HostID=? AND OutCardTime IS NULL";
                query = Session.CreateSQLQuery(sql);
                query.SetInt32(0, host.ID);
                query.ExecuteUpdate();
            }
            //}
        }
        /// <summary>
        /// 设置主机温度
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="hostTemp">主机温度</param>
        public void SetHostTemp(Host host, int hostTemp)
        {
            string sql = "UPDATE tb_Hosts SET HostTemp=? WHERE ID=?";
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetInt32(0, hostTemp);
            query.SetInt32(1, host.ID);
            query.ExecuteUpdate();
        }
        /// <summary>
        /// 设置主机bool字段内容
        /// </summary>
        /// <param name="hostID"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        public void SetHostByField(int hostID, string field, bool value)
        {
            string sql = "UPDATE tb_Hosts SET " + field + "=? WHERE ID=?";
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetBoolean(0, value);
            query.SetInt32(1, hostID);
            query.ExecuteUpdate();
        }
        /// <summary>
        /// 设置微信锁
        /// </summary>
        /// <param name="host"></param>
        /// <param name="lockStatus"></param>
        public void SetLockStatus(Host host, int lockStatus)
        {
            string sql = "UPDATE tb_Hosts SET LockStatus=? WHERE ID=?";
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetInt32(0, lockStatus);
            query.SetInt32(1, host.ID);
            query.ExecuteUpdate();
            host.LockStatus = lockStatus;
        }

        /// <summary>
        /// 设置门锁状态
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="doorLockStatus">True/开，False/关</param>
        public void SetDoorLockStatus(Host host, bool doorLockStatus)
        {
            string sql = "";
            IQuery query = null;
            if (host.DoorLockStatus != doorLockStatus || host.DoorLockStatusUpdateTime == null)
            {
                sql = "UPDATE tb_Hosts SET DoorLockStatus=?, DoorLockStatusUpdateTime=? WHERE ID=?";
                query = Session.CreateSQLQuery(sql);
                query.SetInt32(0, doorLockStatus ? 1 : 0);
                query.SetDateTime(1, DateTime.Now);
                query.SetInt32(2, host.ID);
                query.ExecuteUpdate();

                host.DoorLockStatus = doorLockStatus;
                host.DoorLockStatusUpdateTime = DateTime.Now;
            }
        }

        /// <summary>
        /// 设置保险箱状态
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="safeBoxStatus">保险箱：0关，1开，2未接保险箱</param>
        public void SetSafeBoxStatus(Host host, int safeBoxStatus)
        {
            if (host != null)
            {
                host.SafeStatus = safeBoxStatus;
                string sql = "UPDATE tb_Hosts SET SafeStatus=? WHERE ID=?";
                IQuery query = Session.CreateSQLQuery(sql);
                query.SetInt32(0, safeBoxStatus);
                query.SetInt32(1, host.ID);
                query.ExecuteUpdate();
            }
        }
        /// <summary>
        /// 根据房型获取所有主机列表
        /// </summary>
        /// <param name="hotelID"></param>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        public IList<Object> LoadAllHostByRoomType(int hotelID, int roomTypeID)
        {
            string sql = "select a.ID,a.HostNumber,a.RoomNumber,a.MAC,a.RoomTypeID,a.ExpireTime,a.SetExpireTime from tb_Hosts a"
                + " where isnull(a.MAC,'')<>'' and a.HotelID=? and a.RoomTypeID=? and a.IsDeleted<>1";
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetInt32(0, hotelID);
            query.SetInt32(1, roomTypeID);
            return query.List<Object>();
        }
        /// <summary>
        /// 根据房型获取主机列表（C主机升级使用）
        /// </summary>
        /// <param name="hotelID"></param>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        public IList<Object> LoadHostByRoomType(int hotelID, int roomTypeID)
        {
            string sql = "select a.ID,a.HostNumber,a.RoomNumber,a.MAC,a.RoomTypeID,a.Model,a.LauncherVersion,a.Version,a.ConfigVersion,a.UpgradeStatus,a.UpgradeTime,a.LanIP,a.LanPort,b.TypeNumber from tb_Hosts a left join tb_HostsRCU b on a.ID=b.HostID"
                + " where isnull(a.MAC,'')<>'' and a.HotelID=? and a.RoomTypeID=? and a.Version like 'C%' and a.IsDeleted<>1";//left join tb_HostUpdateStatus b on b.HostID=a.ID
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetInt32(0, hotelID);
            query.SetInt32(1, roomTypeID);
            return query.List<Object>();
        }

        /// <summary>
        /// 根据房型，房间号获取房间信息(C系列)
        /// </summary>
        /// <param name="hotelID"></param>
        /// <param name="roomTypeID"></param>
        /// <param name="roomnumber"></param>
        /// <returns></returns>
        public IList<Object> LoadHostByRoomTypeChengZiHao(int hotelID, int roomTypeID, string roomNumber)
        {
            string sql = "select a.ID,a.HostNumber,a.RoomNumber,a.MAC,a.RoomTypeID,a.Model,a.LauncherVersion,a.Version,a.ConfigVersion,a.UpgradeStatus,a.UpgradeTime,a.LanIP,a.LanPort,b.TypeNumber from tb_Hosts a left join tb_HostsRCU b on a.ID=b.HostID"
                + " where isnull(a.MAC,'')<>'' and a.HotelID=? and a.RoomTypeID=? and a.RoomNumber=? and a.Version like 'C%' and a.IsDeleted<>1";//left join tb_HostUpdateStatus b on b.HostID=a.ID
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetInt32(0, hotelID);
            query.SetInt32(1, roomTypeID);
            query.SetString(2, roomNumber);
            return query.List<Object>();
        }

        /// <summary>
        /// 设置升级状态
        /// </summary>
        /// <param name="host"></param>
        /// <param name="upgradeStatus"></param>
        public void SetUpgradeStatus(Host host, int upgradeStatus, bool isReseet = false)
        {
            string sql = "UPDATE tb_Hosts SET UpgradeStatus=" + upgradeStatus + ",UpgradeTime=" + (isReseet ? "NULL" : "GETDATE()") + " WHERE ID=" + host.ID;
            IQuery query = Session.CreateSQLQuery(sql);
            query.ExecuteUpdate();
        }
        /// <summary>
        /// 设置机型和Launcher
        /// </summary>
        /// <param name="host"></param>
        /// <param name="model"></param>
        /// <param name="launcher"></param>
        public void SetModelAndLauncher(Host host,string ConfigVersion,string Version, string lanIP, int lanPort, string model, string launcher, DateTime expireTime, DateTime setExpireTime)
        {
            string HostNumberOnly = host.HostNumber;
            Host host_take = null;
            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + HostNumberOnly;
            object obj = MemoryCacheHelper.Get(Key);
            if (obj != null)
            {
                host_take = obj as Host;

                #region 更新缓存
                host_take.ExpireTime = host.ExpireTime;
                host_take.SetExpireTime = host.SetExpireTime;

                host_take.LanIP = host.LanIP;
                host_take.LanPort = host.LanPort;

                host_take.ServerIP = host.ServerIP;
                host_take.ServerPort = host.ServerPort;
                host_take.SubnetMask = host.SubnetMask;
                host_take.Gateway = host.Gateway;
                host_take.DNS = host.DNS;
                host_take.Version =Version;
                host_take.RunTime = host.RunTime;
                host_take.LauncherVersion = host.LauncherVersion;
                host_take.MAC = host.MAC;
                host_take.SysHotel.Code = host.SysHotel.Code;
                host_take.RoomType.ID = host.RoomType.ID;
                host_take.ConfigVersion = host.ConfigVersion;
                host_take.RoomStatus.ID = host.RoomStatus.ID;
                host_take.Season = host.Season;

                host_take.RoomNumber = host.RoomNumber;
                //host_take.Model = host.Model;
                host_take.Model = model;
                host_take.LauncherVersion = launcher;
                host_take.ConfigVersion = ConfigVersion;
                host_take.UpgradeTime = host.UpgradeTime;
                #endregion
            }

            string sql = "UPDATE tb_Hosts SET LanIP=?,LanPort=?,Model=?,LauncherVersion=?,ExpireTime=?,SetExpireTime=?,ConfigVersion=?,Version=? WHERE ID=?";
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetString(0, lanIP);
            query.SetInt32(1, lanPort);
            query.SetString(2, model);
            query.SetString(3, launcher);
            query.SetDateTime(4, expireTime);
            query.SetDateTime(5, setExpireTime);
            query.SetString(6, ConfigVersion);
            query.SetString(7, Version);
            query.SetInt32(8, host.ID);
            query.ExecuteUpdate();
        }
        /// <summary>
        /// 设置是否发布
        /// </summary>
        /// <param name="host"></param>
        /// <param name="isPublish"></param>
        public void SetPublish(Host host, bool isPublish)
        {
            string sql = "UPDATE tb_Hosts SET IsPublish=? WHERE ID=?";
            IQuery query = Session.CreateSQLQuery(sql);
            query.SetBoolean(0, isPublish);
            query.SetInt32(1, host.ID);
            query.ExecuteUpdate();
        }

        /// <summary>
        /// 设置当前温度
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="currentTemp">当前温度</param>
        //public void SetCurrentTemp(Host host, int currentTemp)
        //{
        //    host.CurrentTemp = currentTemp;

        //    string sql = "UPDATE tb_Hosts SET CurrentTemp=? WHERE ID=?";
        //    IQuery query = Session.CreateSQLQuery(sql);
        //    query.SetInt32(0, currentTemp);
        //    query.SetInt32(1, host.ID);
        //    query.ExecuteUpdate();
        //}

        /// <summary>
        /// 设置设定温度
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="settingTemp">设定温度</param>
        //public void SetSettingTemp(Host host, int settingTemp)
        //{
        //    string sql = "UPDATE tb_Hosts SET SettingTemp=? WHERE ID=?";
        //    IQuery query = Session.CreateSQLQuery(sql);
        //    query.SetInt32(0, settingTemp);
        //    query.SetInt32(1, host.ID);
        //    query.ExecuteUpdate();
        //}

        /// <summary>
        /// 设置风速
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="speed">风速</param>
        //public void SetSpeed(Host host, int speed)
        //{
        //    string sql = "UPDATE tb_Hosts SET Speed=? WHERE ID=?";
        //    IQuery query = Session.CreateSQLQuery(sql);
        //    query.SetInt32(0, speed);
        //    query.SetInt32(1, host.ID);
        //    query.ExecuteUpdate();
        //}

        /// <summary>
        /// 返回与指定 host 连通的 Host，结果中不包含指定的host。
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        //public IList<Host> GetConnectRoomHosts(Host host)
        //{
        //    var hostList = new List<Host>();

        //    if (String.IsNullOrEmpty(host.ConnectingRooms))
        //    {
        //        return hostList;
        //    }

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

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

        //    return hostList;
        //}


        public Host GetByHiWeiCUID(string cuid)
        {
            return base.LoadAll().Where(r => r.HiWeiCUID.Equals(cuid) && !r.IsDeleted).FirstOrDefault();
        }

        /// <summary>
        /// 找到那些使用新版本协议的主机
        /// </summary>
        /// <returns></returns>
        public IList<HostMappingData> LoadAllID_HostNumberMapping()
        {
            return base.LoadAll().Where(A => A.SysHotel.IsNewVersionProtocol == true && A.IsDeleted == false).Select(A => new HostMappingData() { Id = A.ID, HostNumber = A.HostNumber }).ToList();
        }


        public IList<HostRoomNumberMapping> LoadAll_RoomNumberMapping()
        {
            return base.LoadAll().Where(A => A.IsDeleted == false).Select(A => new HostRoomNumberMapping() { RoomNumber = A.RoomNumber, HostNumber = A.HostNumber }).ToList();
        }
    }
}
