package com.ssm.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dgtis.sso.model.UserModel;
import com.dgtis.sso.utils.SSOHelper;
import com.ssm.model.system.SysRole;
import com.ssm.model.system.SysUser;
import com.ssm.model.system.SysUserLoginLog;
import com.ssm.model.validator.UserLoginValidator;
import com.ssm.service.system.SysRoleService;
import com.ssm.service.system.SysUserLoginLogService;
import com.ssm.service.system.SysUserService;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;
import com.ssm.web.WithoutUserLogin;

@Controller
public class LoginController {
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserLoginLogService userLoginLogService;
	@Autowired
	private SysRoleService sysRoleService;
	
	@WithoutUserLogin
	@RequestMapping(value="/")
	public String initHome(Model md,HttpServletRequest request) {
		/**
		 * 第一次从one portal跳转进来，
		 */
		UserModel model = SSOHelper.getUser(request);
		if(model != null){
			String loginId = model.getLoginName();
			SysUser sysuser = sysUserService.findByEmployeeno(loginId);
			if(sysuser != null){
				//保存到session
				HttpSession session = request.getSession();
				session.setAttribute(Const.USER_SESSION_KEY, sysuser);
				
				//绑定 用户的角色
				List<SysRole> roleList = sysRoleService.findUserRoleByUserId(sysuser.getUserid());
				session.setAttribute(sysuser.getUserid().toString(), roleList);
				
				sysuser.setLastlogindate(new Date());
				sysuser.setLastloginip(request.getRemoteAddr());
				int loginCount = sysuser.getLogincounts() != null ? (sysuser.getLogincounts() +1) : 1;
				sysuser.setLogincounts(loginCount);
				sysUserService.updateByPrimaryKeySelective(sysuser);
				
				//记录登录日志
				SysUserLoginLog loginLog = new SysUserLoginLog();
				loginLog.setUserid(sysuser.getUserid());
				loginLog.setIpaddress(request.getRemoteAddr());
				loginLog.setCreateddate(new Date());
				StringBuilder comments = new StringBuilder();
				String userAgent = request.getHeader("User-Agent").toLowerCase();
				String os = "未知";
				if (userAgent.indexOf("win") > -1) 
				{
					if (userAgent.indexOf("nt 10") > -1 ) 
					{ 
						os = "Windows 10"; 
					} 
					if (userAgent.indexOf("nt 6.1") > -1 ) 
					{ 
						os = "Windows 7"; 
					} 
					if (userAgent.indexOf("nt 6.3") > -1 ) 
					{ 
						os = "Windows 8"; 
					} 
					if (userAgent.indexOf("nt 5.2") > -1) 
					{ 
						os = "Windows Server 2003"; 
					} 
					if (userAgent.indexOf("nt 5.1") > -1) 
					{ 
						os = "Windows XP"; 
					} 
				}	
				comments.append("浏览器 :");
				comments.append(userAgent);
				comments.append(" 操作系统 :");
				comments.append(os);
				loginLog.setComments(comments.toString());
				userLoginLogService.saveUserLoginLog(loginLog);
			} else {
				sysUserService.insertUserSave(model);
			}
		}
		
		return "redirect:/home/homeIndex";
	}
	
	/**
	 * 用户表单提交 绑定验证
	 * @param binder
	 */
	@WithoutUserLogin
	@InitBinder
	public void InitBinder(DataBinder binder){
		binder.setValidator(new UserLoginValidator());
	}
	
	public String toLogin(Model model) {
		if(!model.containsAttribute("user"))
			model.addAttribute("user", new SysUser());
		return "login";
	}
	
	
	/**
	 * 用户登录操作
	 * 后台form表单验证
	 * @param username
	 * @param password
	 * @return 登录失败返回首页，登录成功转发到 框架首页欢迎页
	 */
	@Transactional(value="txManager")
	@WithoutUserLogin
	@RequestMapping(value="login")
	public String login(HttpServletRequest request,HttpServletResponse response, HttpSession session, Model model, 
			@Validated @ModelAttribute("user") SysUser user, BindingResult result) {
		/* 前台输入用户和密码为空  */
		if(result.hasErrors())
			return toLogin(model);
		SysUser sysUser = sysUserService.findByEmployeenoAndPasswod(user.getEmployeeno().trim(),
				user.getPassword().trim());
		if(sysUser == null || sysUser.getIsdeleted() == true || sysUser.getIsenabled() == true ) {
			if(sysUser == null)
				result.addError(new FieldError("user", "employeeno", "用户名或密码错误"));
			else if( sysUser.getIsdeleted() == true )
				result.addError(new FieldError("user", "employeeno", "用户不存在"));
			else if(sysUser.getIsenabled() == true) 
				result.addError(new FieldError("user", "employeeno", "此用户被禁用，不能登录。"));
			else
        		result.addError(new FieldError("user","employeeno","此用户当前未被授权，不能登录。"));
			return toLogin(model);
		}
		//用户验证通过
		session.setAttribute(Const.USER_SESSION_KEY, sysUser);
		UserModel userModel = new UserModel(sysUser.getEmployeeno(),sysUser.getPassword(),sysUser.getMobilenumber(),sysUser.getEmailaddress(),false,"","",sysUser.getUsername(), "", "");
		SSOHelper.createCookie(response, userModel);
		
		//绑定 用户的角色
		/*List<SysRole> roleList = sysRoleService.findUserRoleByUserId(sysUser.getUserid());
		session.setAttribute(sysUser.getUserid().toString(), roleList);
		
		sysUser.setLastlogindate(new Date());
		sysUser.setLastloginip(request.getRemoteAddr());
		int loginCount = sysUser.getLogincounts() != null ? (sysUser.getLogincounts() +1) : 1;
		sysUser.setLogincounts(loginCount);
		sysUserService.updateByPrimaryKeySelective(sysUser);*/
		
		//记录登录日志
		SysUserLoginLog loginLog = new SysUserLoginLog();
		loginLog.setUserid(sysUser.getUserid());
		loginLog.setIpaddress(request.getRemoteAddr());
		loginLog.setCreateddate(new Date());
		StringBuilder comments = new StringBuilder();
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		String os = "未知";
		if (userAgent.indexOf("win") > -1) 
		{
			if (userAgent.indexOf("nt 10") > -1 ) 
			{
				os = "Windows 10"; 
			} 
			if (userAgent.indexOf("nt 6.1") > -1 ) 
			{ 
				os = "Windows 7"; 
			} 
			if (userAgent.indexOf("nt 6.3") > -1 ) 
			{ 
				os = "Windows 8"; 
			} 
			if (userAgent.indexOf("nt 5.2") > -1) 
			{ 
				os = "Windows Server 2003"; 
			} 
			if (userAgent.indexOf("nt 5.1") > -1) 
			{ 
				os = "Windows XP"; 
			}
		}
		comments.append("浏览器 :");
		comments.append(userAgent);
		comments.append(" 操作系统 :");
		comments.append(os);
		loginLog.setComments(comments.toString());
		userLoginLogService.saveUserLoginLog(loginLog);
		
		return "redirect:/home/homeIndex";
	}
	
	/**
	 * 注销，登出系统时将session绑定的数据 清除
	 * @param session
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="loginOut", method=RequestMethod.GET)
	public String loginOut(HttpSession session, Model model){
		session.invalidate();
		return "redirect:/home/homeIndex";
	}
}
