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

namespace Dao.Implement
{
    public class SysHotelRepository : RepositoryBase<SysHotel>, ISysHotelRepository
    {
        public IQueryable<SysHotel> LoadAllByPage(out long total, int page, int rows, string order, string sort, string query, int? groupId)
        {
            var list = this.LoadAll().Where(r => r.IsDeleted != true);
            if (groupId.HasValue && groupId > 1)
            {
                list = list.Where(r => r.SysHotelGroup == null || r.SysHotelGroup.ID == groupId || (r.SysHotelGroup.Parent != null && r.SysHotelGroup.Parent.ID == groupId));
            }
            if (!string.IsNullOrEmpty(query))
            {
                list = list.Where(r => r.Code.Contains(query) || r.Name.Contains(query));
            }
            total = list.LongCount();
            list = list.OrderBy(sort + " " + order);
            list = list.Skip((page - 1) * rows).Take(rows);
            return list;
        }

        public SysHotel GetByCode(string code)
        {
            return LoadAll().Where(r => r.Code == code && r.IsDeleted != true).OrderBy(r => r.Sort).FirstOrDefault();
        }

        public SysHotel GetByAssociatedAccount(string associatedAccount)
        {
            return LoadAll().Where(r => r.AssociatedAccount == associatedAccount && r.IsDeleted != true).OrderBy(r => r.Sort).FirstOrDefault();
        }

        public SysHotel GetByDomainUrl(string domainUrl)
        {
            return LoadAll().Where(r => r.DomainUrl.Contains("%" + domainUrl + "%") && r.IsDeleted != true).OrderBy(r => r.Sort).FirstOrDefault();
        }

        public IList<SysHotel> GetByGroup(SysHotelGroup group)
        {
            return base.LoadAll().Where(r => r.SysHotelGroup == group && r.IsDeleted != true).OrderBy(r => r.Code).ToList();
        }
        /// <summary>
        /// 重载删除，只做标记
        /// </summary>
        /// <param name="id"></param>
        public override void Delete(object id)
        {
            var entity = this.HibernateTemplate.Get<SysHotel>(id);
            if (entity == null)
            {
                return;
            }
            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<SysHotel>(id);
                if (entity == null)
                {
                    return;
                }
                entity.IsDeleted = true;
                entity.Last_Modified_Time = DateTime.Now;
                this.HibernateTemplate.Update(entity);
            }
        }


        /// <summary>
        /// 阿宝添加的
        /// </summary>
        /// <returns></returns>
        public List<CommonEntity.KongQi> GetNeedData()
        {
            using (IStatelessSession session = SessionFactory.OpenStatelessSession())
            using (IDbCommand cmd = session.Connection.CreateCommand())
            {

                cmd.CommandText = @"select B.HotelID,D.Code, C.RoomNumber,D.CreatedDate from tb_RoomTypeModal A 
                left join tb_RoomType B 
                on A.RoomTypeID=B.ID
                left join tb_Sys_Hotels D
                on D.ID=B.HotelID
                left join tb_Hosts C
                on C.HotelID=B.HotelID and C.RoomTypeID=B.ID 
                where C.IsDeleted=0 
                and B.IsDeleted=0 and D.IsDeleted=0 
                and A.ModalAddress>='009000001' and A.ModalAddress<='009001000';";
                cmd.CommandType = CommandType.Text;

                IDbDataAdapter da = new SqlDataAdapter(cmd as SqlCommand);

                DataSet ds = new DataSet();

                da.Fill(ds);

                DataTable dt = ds.Tables[0];
                List<KongQi> list = new List<KongQi>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        CommonEntity.KongQi k = new CommonEntity.KongQi();
                        string hotelid = item["HotelID"].ToString();
                        string hotelcode = item["Code"].ToString();
                        string roomnumber = item["RoomNumber"].ToString();
                        string createdate = item["CreatedDate"].ToString();
                        k.HotelID = hotelid.ToString();
                        k.HotelCode = hotelcode;
                        k.RoomNumber = roomnumber;
                        k.CreatDate = createdate;
                        list.Add(k);
                    }
                }
                return list;
            }


        }


        /// <summary>
        /// 判断 某个房间 是否存在某个设备
        /// </summary>
        /// <param name="hotelcode"></param>
        /// <param name="roomnum"></param>
        /// <param name="start_address"></param>
        /// <param name="end_address"></param>
        /// <returns></returns>
        public List<SomeDeviceExistsData> IsExistsSomeDeviceRoomModal(int id, string roomnum, string start_address, string end_address)
        {
            using (IStatelessSession session = SessionFactory.OpenStatelessSession())
            using (IDbCommand cmd = session.Connection.CreateCommand())
            {

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = @"select B.HotelID,D.Code, C.RoomNumber,D.CreatedDate,A.ModalAddress,A.ID from tb_RoomTypeModal A 
                inner join tb_RoomType B 
                on A.RoomTypeID=B.ID
                inner join tb_Sys_Hotels D
                on D.ID=B.HotelID
                inner join tb_Hosts C
                on C.HotelID=B.HotelID and C.RoomTypeID=B.ID
                where C.IsDeleted=0 
                and B.IsDeleted=0 and D.IsDeleted=0 
                and A.ModalAddress>=@start_address and A.ModalAddress<=@end_address 
                and D.ID=@id and C.RoomNumber=@roomnumber;";

                SqlParameter p1 = new SqlParameter("@id", id);
                SqlParameter p2 = new SqlParameter("@roomnumber", roomnum);
                SqlParameter p3 = new SqlParameter("@start_address", start_address);
                SqlParameter p4 = new SqlParameter("@end_address", end_address);
                cmd.Parameters.Add(p1);
                cmd.Parameters.Add(p2);
                cmd.Parameters.Add(p3);
                cmd.Parameters.Add(p4);
                IDbDataAdapter da = new SqlDataAdapter(cmd as SqlCommand);

                DataSet ds = new DataSet();

                da.Fill(ds);

                DataTable dt = ds.Tables[0];
                List<SomeDeviceExistsData> list = new List<SomeDeviceExistsData>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        CommonEntity.SomeDeviceExistsData k = new CommonEntity.SomeDeviceExistsData();
                        string hotelid = item["HotelID"].ToString();
                        string hotelcode = item["Code"].ToString();
                        string roomnumber = item["RoomNumber"].ToString();
                        string createdate = item["CreatedDate"].ToString();
                        string modalid = item["ID"].ToString();
                        k.HotelID = int.Parse(hotelid);
                        k.HotelCode = hotelcode;
                        k.RoomNumber = roomnumber;
                        k.CreatDate = createdate;
                        k.ModalID = modalid;
                        list.Add(k);
                    }
                }
                return list;
            }
        }


        public SysHotel GetByETV_HotelId(string hotelid)
        {
            return LoadAll().Where(r => r.ETV_HotelID.Equals(hotelid) && r.IsDeleted != true).OrderBy(r => r.Sort).FirstOrDefault();
        }


        public List<SysHotel> get_fcs_hotels()
        {
            return LoadAll().Where(r => r.IsDeleted != true && (r.FCSLoginUrl != "" && r.FCSLoginUrl != null)).ToList();
        }
    }
}
