using System;
using System.Security.Cryptography;
using System.Text;

using HISClinic.DataModel;
using HISClinic.DataServices;

namespace HISClinic.BLL
{
	/// <summary>
	/// Class1 的摘要说明。
	/// </summary>
	public class User
	{
		public User()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}
		
		/// <summary>
		///  通过登录名和密码登录系统，获取用户的信息
		/// </summary>
		/// <param name="loginName">登录名</param>
		/// <param name="password">密码</param>
		/// <param name="loginResult">登录的结果</param>
		/// <returns>登录用户的信息</returns>
		public UsersEx Login(string loginName,string password,out LoginResult loginResult)
		{
			UsersEx usersEx=(new UserMapper()).FindUser(loginName);

			if(usersEx.t_User.Rows.Count>0)
			{
				UsersEx.t_UserRow userRow=(Users.t_UserRow)usersEx.t_User.Rows[0];
				Password pwd=new Password(userRow.UserID.ToString(),password);
				loginResult=pwd.Equals(new UserMapper().GetPassword(userRow.UserID))?LoginResult.Success:LoginResult.InvalidPassword;				
				return usersEx;
			}
			else
			{
				loginResult=LoginResult.InvalidLoginName;
				return null;
			}
		}
		/// <summary>
		/// 密码类，实现密码加密和判断
		/// </summary>
		public class Password
		{
		
			private byte[] _pwassword;
			public Password(string salt,string password){
				_pwassword=Encrypt(salt,password);
			
			}
			/// <summary>
			/// 加密密码
			/// </summary>
			/// <param name="oldpassword"></param>
			private byte[] Encrypt(string salt,string password){
				string key=salt+password;
				HashAlgorithm sha1=new SHA1CryptoServiceProvider();
				return sha1.ComputeHash(Encoding.Default.GetBytes(key));
			}

			public override bool Equals(object obj)
			{
				byte[] pwd=(byte[])obj;
				return Equals(pwd);
			}

			public bool Equals(byte[] pwd)
			{
				
				return Compare2Byts(_pwassword,pwd);
			}
			private bool Compare2Byts(byte[] bts1,byte[] bts2){
				if(bts1.Length!=bts2.Length)
					return false;
				for(int i=0;i<bts1.Length;i++){
					if(bts1[i]!=bts2[i])
						return false;
				}
				return true;
			}

		}
		/// <summary>
		/// 登录结果
		/// </summary>
		public enum LoginResult
		{
			InvalidLoginName=1,
			InvalidPassword,
			Success
		}

		/// <summary>
		/// Doctor 的摘要说明。
		/// </summary>
		public class Doctor
		{
			public Doctor()
			{
				//
				// TODO: 在此处添加构造函数逻辑
				//
			}

			/// <summary>
			/// 获取门诊医生
			/// </summary>
			/// <returns></returns>
			public DoctorsEx GetDoctor()
			{
				DoctorsEx doctorsEx=(new UserMapper.Doctor()).GetDoctor();
				return doctorsEx.t_Doctor.Rows.Count>0?doctorsEx:null;
			}

			/// <summary>
			/// 获取门诊医生
			/// </summary>
			/// <returns></returns>
			public DoctorsEx GetDoctor(int doctorID)
			{
				DoctorsEx doctorsEx=(new UserMapper.Doctor()).GetDoctor(doctorID );
				return doctorsEx.t_Doctor.Rows.Count>0?doctorsEx:null;
			}
		}
	}
}
