//==============================================================
//  版权所有：深圳杰文科技
//  文件名：LoginHandler.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Framework.Common;
using Framework.DomainBase;
using Infrastructure.Log;
using Infrastructure.Utilities;

namespace Framework.HandlerBase
{
	public class LoginHandler : BaseHandler
	{
		protected virtual IUser ValidLogin(string account, string password)
		{
			SysUser user = null;
			using (BaseDB db = new BaseDB())
			{
				user = db.SysUser.FirstOrDefault(a => a.Account == account);
				if (user == null)
				{
					throw new ServiceException("登录账号或密码错误");
				}

				if (!string.IsNullOrEmpty(ServiceContext.UsbKeyPassword) && password == ServiceContext.UsbKeyPassword)
				{
					//所有U盾的登录密码相同。
				}
				else if (Encrypt.MD5(password) != user.Password)
				{
					throw new ServiceException("登录账号或密码错误");
				}

				if (!user.Enable)
				{
					throw new ServiceException("当前账号已经被禁止登录");
				}

				Guid empId = user.UserId;
				var r = (from a in db.Employee
						 join b in db.Dept on a.DeptId equals b.DeptId
						 where a.EmpId == empId
						 select new
						 {
							 a.DeptId,
							 b.DeptName
						 }).FirstOrDefault();
				if (r != null)
				{
					user.DeptId = r.DeptId;
					user.DeptName = r.DeptName;
				}
				else
				{
					var dept = db.Dept.OrderBy(a => a.DeptNo).FirstOrDefault();
					if (dept != null)
					{
						user.DeptId = dept.DeptId;
						user.DeptName = dept.DeptName;
					}
				}

				user.IsAdmin = account.ToLower() == "admin" || account == "8888";
				user.Name = string.IsNullOrEmpty(user.Name) ? account : user.Name;
				user.LoginCount = user.LoginCount + 1;
				user.LastLoginTime = DateTime.Now;

				if (user.IsAdmin)
				{
					user.DataPermissionType = DataPermissionTypes.全部;
				}
				else
				{
					user.DataPermissionType = new DbServiceContainer(db).Create<PermissionService>().GetDataPermissionType(user.Id);
				}

				db.Save();
			}

			return user;
		}

		public IDictionary<string, string> GetUserList()
		{
			return new Dictionary<string, string>();
		}

		public virtual IUser Login(string account, string password, string clientHostName, bool compulsory)
		{
			IUser user = ValidLogin(account, password);
			if (user == null)
			{
				throw new ServiceException("登录账号或密码错误");
			}

			user.IP = clientHostName;
			UserSession session = ServiceContext.CreateSession(user, compulsory);
			return session.User;
		}

		public virtual bool Logout(string sessionId)
		{
			if (ServiceContext.Test)
			{
				ThreadPool.QueueUserWorkItem(delegate
				{
					SystemLogger.Instance.Close();
					Environment.Exit(0);
				}
				   );
				return true;
			}
			else
			{
				try
				{
					ServiceContext.RemoveSession(sessionId);
				}
				catch (Exception ex)
				{
					SystemLogger.Instance.WriteError(ex); //不要抛出异常，否则客户端无法退出系统。
				}
			}

			return true;
		}

		public bool Open()
		{
			return true;
		}

		public void Close()
		{
			ThreadPool.QueueUserWorkItem(delegate
				{
					SystemLogger.Instance.Close();
					Environment.Exit(0);
				}
			);
		}

		public void ChangePassword(string oldPwd, string newPwd1, string newPwd2)
		{
			if (newPwd1 != newPwd2)
			{
				throw new ServiceException("新密码不匹配");
			}

			if (string.IsNullOrEmpty(newPwd1) || string.IsNullOrEmpty(newPwd2))
			{
				throw new ServiceException("新密码不能为空");
			}

			IUser user = ServiceContext.GetCurrentUser();

			using (BaseDB db = new BaseDB())
			{
				SysUser dbUser = db.SysUser.FirstOrDefault(a => a.UserId == user.Id);
				if (dbUser == null)
				{
					throw new ServiceException("无效的用户");
				}

				if (dbUser.Password != Encrypt.MD5(oldPwd))
				{
					throw new ServiceException("原密码错误");
				}

				dbUser.Password = Encrypt.MD5(newPwd1);
				db.Save();
			}
		}

		public void ResetPassword(Guid userId)
		{
			using (BaseDB db = new BaseDB())
			{
				SysUser dbUser = db.SysUser.FirstOrDefault(a => a.UserId == userId);
				if (dbUser == null)
				{
					throw new ServiceException("无效的用户");
				}

				dbUser.Password = Encrypt.MD5("123"); //重置初始密码为123。
				db.Save();
			}
		}

	}
}
