using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Reflection;
using System.Text;
using Domain;
using Dao;

namespace Service.Implement
{
	public class SysUserManager : GenericManagerBase<SysUsers>, ISysUserManager
	{         
		private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SysUserManager));

        public IList<SysUsers> LoadAllByPage(out long total, int page, int rows, string order, string sort, int type, int? groupId, int? hotelID)
        {
            //var list = CurrentRepository.LoadAll();
            ////list = list.Where("Account != @0", "admin");
            //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();
            return ((ISysUserRepository)(this.CurrentRepository)).LoadAllByPage(out total, page, rows, order, sort, type, groupId, hotelID).ToList();
        }

		public SysUsers Get(string account)
		{
			return ((Dao.ISysUserRepository)(this.CurrentRepository)).Get(account);
		}

		public SysUsers Get(string account, string password)
		{
			var entity = ((Dao.ISysUserRepository)(this.CurrentRepository)).Get(account);
			if (entity != null)
			{
				if (entity.Password != ComputePasswordHash(password, entity))
				{
					return null;
				}
			}
			return entity;
		}

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

        public override object Save(SysUsers entity)
        {
            entity.Password = ComputePasswordHash("123456", entity);
            entity.Password2 = "123456";
            entity.Last_Modified_Time = DateTime.Now;//标识有更新
            return base.Save(entity);

            //if (entity.Hotels != null && entity.Hotels.Count > 0)
            //{
            //    var userHotel = SysUserHotelRepository.Get(entity.ID, entity.Hotels[0].ID);
            //    if (userHotel == null)
            //    {
            //        userHotel = new SysUserHotel();
            //    }
            //    userHotel.UserID = entity.ID;
            //    userHotel.HotelID = entity.Hotels[0].ID;
            //    userHotel.GroupID = entity.Group.ID;
            //    SysUserHotelRepository.SaveOrUpdate(userHotel);
            //}

            //return result;
        }

        public void Update(SysUsers entity, string password)
		{
			entity.Password = ComputePasswordHash(password, entity);
            entity.Password2 = password;
            entity.Last_Modified_Time = DateTime.Now;//标识有更新
            base.Update(entity);
		}

		public bool HasAuthority(string account, int authorityId)
		{
			SysUsers user = Get(account);
			if (user == null) 
			{
				return false;
			}
			if (user.Account == "admin")
			{
				return true;
			}
			if (user.Role == null || user.Role.Authorities == null)
			{
				return false;
			}
			if (user.Role.Authorities.Count(r => r.ID == authorityId) == 0)
			{
				return false;
			}
			return true;
		}

		#region Private Methods

		/// <summary>
		/// 计算密码 Hash值
		/// </summary>
		/// <param name="password"></param>
		/// <param name="entity"></param>
		/// <returns></returns>
		private string ComputePasswordHash(string password, SysUsers entity)
		{
			return HashCode(entity.Account.ToUpper() + password + entity.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss"));
		}

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

		#endregion
	}
}

