using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dao;
using Domain;
using Common;

namespace Service.Implement
{
    public class SysHotelManager : GenericManagerBase<SysHotel>, ISysHotelManager
    {
        public IGroupRepository GroupRepository { get; set; }
        public IRoomTypeManager RoomTypeManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public IHostManager HostManager { get; set; }
        public RCUHost.IHotelTimeReceiver HotelTimeReceiver { get; set; }

        public IList<SysHotel> LoadAllByPage(out long total, int page, int rows, string order, string sort, string query, int? groupId)
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).LoadAllByPage(out total, page, rows, order, sort, query, groupId).ToList();
        }

        public SysHotel GetByCode(string code)
		{
            return ((ISysHotelRepository)(this.CurrentRepository)).GetByCode(code);
		}

        public SysHotel GetByCode(string code, DateTime date)
        {
            var entity = ((ISysHotelRepository)(this.CurrentRepository)).GetByCode(code);

            if (entity == null)
            {
                return null;
            }
            else
            {
                if (entity.WXValidate != ComputePasswordHash(code, date))
                {
                    return null;
                }
                return entity;
            }
        }

        public SysHotel GetByAssociatedAccount(string associatedAccount)
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).GetByAssociatedAccount(associatedAccount);
        }

        public SysHotel GetByDomainUrl(string domainUrl)
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).GetByDomainUrl(domainUrl);
        }

        public override object Save(SysHotel entity)
        {
            entity.WXValidate = ComputePasswordHash(entity.Code, entity.CreatedDate);
            entity.Last_Modified_Time = DateTime.Now;//标识有更新
            object result = base.Save(entity);
            //新增酒店时，需要新增酒店根楼层
            GroupRepository.Save(new Group { Parent = null, Name = entity.Name, Sort = 1, HotelID = entity.ID });
            //新增默认房型（同时新增房型时：新增微信菜单等）
            RoomTypeManager.Save(new RoomType { HotelID = entity.ID, Code = entity.Code + "01", Name = "默认房型", HostName = "默认房型", Default = true });
            return result;
        }

        public override void Update(SysHotel entity)
        {
            entity.WXValidate = ComputePasswordHash(entity.Code, entity.CreatedDate);
            entity.Last_Modified_Time = DateTime.Now;//标识有更新
            base.Update(entity);
        }

        public override void SaveOrUpdate(SysHotel entity)
        {
            entity.WXValidate = ComputePasswordHash(entity.Code, entity.CreatedDate);
            entity.Last_Modified_Time = DateTime.Now;//标识有更新
            base.SaveOrUpdate(entity);
        }
        /// <summary>
        /// 更新白天起始时间并下发命令给主机
        /// </summary>
        /// <param name="entity"></param>
        public void UpdateDayTime(SysHotel entity)
        {
            entity.WXValidate = ComputePasswordHash(entity.Code, entity.CreatedDate);
            base.Update(entity);
            IList<Host> hosts = HostManager.LoadAll().Where(r => r.SysHotel.ID == entity.ID).ToList();
            foreach (Host host in hosts)
            {
                if (Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                {
                    HotelTimeReceiver.Send(host);//下发白天起始时间命令
                }
            }
        }

        public override void Delete(IList<object> idList)
        {
            foreach (int id in idList)
            {
                //删除楼层信息
                var groups = GroupRepository.LoadAll().Where(r => r.HotelID == id).OrderByDescending(r => r.ID);
                foreach (var l in groups)
                {
                    GroupRepository.Delete(l.ID);
                }
                //删除房型
                var roomTypes = RoomTypeManager.LoadAll().Where(r => r.HotelID == id);
                foreach (var r in roomTypes)
                {
                    RoomTypeManager.Delete(r.ID);
                }
                //删除酒店关联用户
                var users = SysUserManager.LoadAll().Where(r => r.HotelID == id);
                foreach (SysUsers user in users)
                {
                    SysUserManager.Delete(user.ID);
                }
            }
            ((ISysHotelRepository)(this.CurrentRepository)).Delete(idList);
        }

		/// <summary>
		/// 计算密码 Hash值
		/// </summary>
		/// <param name="password"></param>
		/// <param name="entity"></param>
		/// <returns></returns>
        private string ComputePasswordHash(string code, DateTime createDate)
        {
            return HashCode(createDate.ToString("yyyy") + code.ToUpper() + createDate.ToString("MMdd"));
        }

		/// <summary>
		/// 获取MD5值
		/// </summary>
		/// <param name="key">加密的字符串</param>
		/// <returns>返回MD5值</returns>
		private string HashCode(string key)
		{
			return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "MD5");
		}



        public List<CommonEntity.KongQi> GetNeedData()
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).GetNeedData();
        }


        public List<CommonEntity.SomeDeviceExistsData> IsExistsSomeDeviceRoomModal(int id, string roomnum, string start_address, string end_address)
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).IsExistsSomeDeviceRoomModal(id,roomnum,start_address,end_address);
        }


        public IList<SysHotel> LoadFCS_PushData()
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).LoadAll().Where(A=>!A.IsDeleted&&A.FCSPushEnable).ToList();
        }


        public SysHotel GetByETV_HotelId(string hotelid)
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).GetByETV_HotelId(hotelid);
        }


        public List<SysHotel> get_fcs_hotel()
        {
            return ((ISysHotelRepository)(this.CurrentRepository)).get_fcs_hotels();
        }
    }
}
