package com.ylcm.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ylcm.sys.common.Constants;
import com.ylcm.sys.common.LoginUtil;
import com.ylcm.sys.common.RequestUtil;
import com.ylcm.sys.common.Util;
import com.ylcm.sys.domain.Permission;
import com.ylcm.sys.domain.User;
import com.ylcm.sys.service.LogService;
import com.ylcm.sys.service.UserService;

import net.sf.json.JSONObject;


/**
 * 用户登录
 */
@Controller
public class LoginController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;
	
	@Autowired
	private LogService logService;

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param model
	 * @return 用户登录页面
	 */
	@RequestMapping(value = "/login.do")
	public ModelAndView login(HttpServletRequest request, Model model) {
		/**
		 * 1、跳转到用户登录页面，记录下next参数
		 */
		model.addAttribute("next", request.getParameter("next"));
		return new ModelAndView("login/login");
	}
	/**
	 * 用户退出登录
	 * 
	 * @param request
	 * @param model
	 * @return 用户登录页面
	 */
	@RequestMapping(value = "/logout.do")
	public void logout(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{
		User user = (User) request.getSession().getAttribute("manager");
		if (user != null) {
			this.logService.saveLog(Constants.LOG_TYPE_LOGOUT, user.getLoginName(), user.getNickName(), RequestUtil.getIpAddr(request), "登出系统");
		}

		request.getSession().invalidate();
		response.sendRedirect(Constants.PATH_BASE.concat("login.do"));

		return;
	}



	/**
	 * 登录功能执行
	 * 
	 * @param request
	 * @param response
	 * @return 登录页面
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/doLogin.do")
	public void doLogin(HttpServletRequest request, HttpServletResponse response, Model model) {
		JSONObject result = new JSONObject();
		try {

			/**
			 * 1、接收登录名和密码
			 */
			String loginName = request.getParameter("loginName");
			String password = request.getParameter("password");

			/**
			 * 2、根据登录名获取用户对象
			 */
			User user = userService.getUserByLoginName(loginName);

			if (user == null) {

				/**
				 * 3、用户不存在
				 */
				model.addAttribute("loginName", loginName);
				result.put("code", 0);
				result.put("msg", "用户不存在，登录失败");
				ajaxJson(result.toString(),response);
			} else {
				if (Constants.STATUS_USER_NORMAL != user.getStatus()) {

					/**
					 * 4、用户状态异常
					 */
					result.put("code", 0);
					result.put("msg", "用户状态异常，登录失败");
					ajaxJson(result.toString(),response);
				} else {

					/**
					 * 5、用户存在
					 */
					if (Util.isBlank(user.getLoginPwd()) || !LoginUtil.generatePassword(password).equals(user.getLoginPwd())) {
						/**
						 * 6、密码错误
						 */
						model.addAttribute("loginName", loginName);
						result.put("code", 0);
						result.put("msg", "密码错误，登录失败");
						ajaxJson(result.toString(),response);
					} else {

						/**
						 * 7、密码正确，判断用户角色
						 */
						List<Permission> permList = null;
						if (user.getRole() != null) {

							/**
							 * 8、角色存在,判断用户权限
							 */
							permList = user.getRole().getPerms();

							/**
							 * 9、处理权限列表
							 */
							permList = userService.getPermissoins(permList);

							/**
							 * 10、保存到用户信息
							 */
							user.getRole().setPerms(permList);
							if (permList == null || permList.size() <= 0) {

								/**
								 * 11、没有权限
								 */
								result.put("code", 0);
								result.put("msg", "没有权限，登录失败");
								ajaxJson(result.toString(),response);
							}
						} else {

							/**
							 * 12、角色不存在
							 */
							result.put("code", 0);
							result.put("msg", "角色不存在，登录失败");
							ajaxJson(result.toString(),response);
						}
						request.getParameterNames();
						String next = request.getParameter("next");
						
						if (Util.isBlank(next)) {

							/**
							 * 14、判断next参数为空时，获取权限中的url
							 */
							for (Permission permission : permList) {
								if (Constants.MENU_TYPE.equals(permission.getType())
										&& permission.getUrl().contains(".do")) {
									next = permission.getUrl();
								} else {
									List<Permission> subPerms = permission.getSubPerms();
									for (Permission subPerm : subPerms) {
										if (Constants.SUB_MENU_TYPE.equals(subPerm.getType())
												&& subPerm.getUrl().contains(".do")) {
											next = subPerm.getUrl();
										}
										break;
									}
								}
								break;
							}
						}

						if (Util.isBlank(next)) {

							/**
							 * 15、登录成功，返回登录页面
							 */
							result.put("code", 0);
							result.put("msg", "没有权限，登录失败");
							ajaxJson(result.toString(),response);
						} else {
							/**
							 * 16、登录成功，返回登录页面
							 */
							result.put("code", 1);
							result.put("msg", "登录成功");
							result.put("redirect", next);
						
							/**
							 * 保存session
							 */
							request.getSession().setAttribute("manager", user);
							request.getSession().setAttribute("nextUrl", next);
							
							/**
							 *  菜单权限
							 */
							Map menuMap = new HashMap<String,Integer>();
							/**
							 *  子菜单权限
							 */
							Map subMenuMap = new HashMap<String,Integer>();
							if(CollectionUtils.isNotEmpty(user.getRole().getPerms())){						
								for(Permission p : user.getRole().getPerms()){
									menuMap.put(p.getCode(), 1);
									if(CollectionUtils.isNotEmpty(p.getSubPerms())) {
										for(Permission subP : p.getSubPerms()) {
											subMenuMap.put(subP.getCode(), 1);
										}
									}
								}
							}
							request.getSession().setAttribute("menuMap", menuMap);
							request.getSession().setAttribute("subMenuMap", subMenuMap);
							/**
							 *  功能权限
							 */
							Map funcMap = new HashMap<String,Integer>();
							if(user.getRole().getFuncs().size() > 0){
								for(Permission p : user.getRole().getFuncs()){
									funcMap.put(p.getCode(), 1);
								}
							}
							request.getSession().setAttribute("funcMap", funcMap);
							/**
							 *  记录登录日志 by zjm
							 */
							this.logService.saveLog(Constants.LOG_TYPE_LOGIN, loginName, user.getNickName(), RequestUtil.getIpAddr(request), "登录系统");
							
							ajaxJson(result.toString(),response);
						}
					}
				}
			}
		} catch (Exception e) {

			/**
			 * 17、登录失败，返回登录页面
			 */
			logger.error(e.getMessage());
			result.put("code", 0);
			result.put("msg", "登录异常");
			ajaxJson(result.toString(),response);
		}

	}
	
	
}