package com.itjob.servlet;

import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itjob.dao.model.Role;
import com.itjob.dao.model.TRight;
import com.itjob.dao.model.User;
import com.itjob.service.*;

public class UserServlet  extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RoleManager roleManager;
	private UserManager userManager;
	private RightManager rightManager;
	
	public void init(ServletConfig config) throws ServletException {  
		// 从web.xml中获得初始化参数
		super.init(config);
	}
	
	protected void service(HttpServletRequest request, HttpServletResponse response) {
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); 
		roleManager = (RoleManager) ctx.getBean("roleManager");
		userManager = (UserManager) ctx.getBean("userManager");
		rightManager = (RightManager) ctx.getBean("rightManager");
		
		// 首先设置文档类型
		response.setContentType("text/html; charset=utf-8");
		String methodName = request.getParameter("methodName");
		try {
			request.setCharacterEncoding("utf-8");
			if ("list".equals(methodName)) {
				// 获得用户列表
				list(request, response);
			} else if ("saveUser".equals(methodName)) {
				// 保存用户信息
				saveUser(request, response);
			} else if ("getUser".equals(methodName)) {
				// 获得某个用户的信息
				getUser(request, response);
			} else if ("updateUser".equals(methodName)) {
				// 更新某个用户的信息
				updateUser(request, response);
			} else if ("deleteUser".equals(methodName)) {
				// 删除一到多个用户信息
				deleteUser(request, response);
			} else if ("initUpdateUserRole".equals(methodName)) {
				// 获得更新用户的角色信息页所需要的信息
				initUpdateUserRole(request, response);
			} else if ("updateUserRole".equals(methodName)) {
				// 更新用户的角色信息
				updateUserRole(request, response);
			} else if ("userLogin".equals(methodName)) {
				// 用户登录
				userLogin(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void list(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		List userList = userManager.getUserList();
		request.setAttribute("userList", userList);
		RequestDispatcher dispatcher = request.getRequestDispatcher("/userManage/list.jsp");
		dispatcher.forward(request, response);  
	}
	
	protected void saveUser(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		// 保存用户信息
		User user = new User();
		user.setLoginName(request.getParameter("loginName"));
		user.setUserPasswd(request.getParameter("userPasswd"));
		user.setRealName(request.getParameter("realName"));
		user.setTel(request.getParameter("tel"));
		user.setEmail(request.getParameter("email"));
		userManager.saveUser(user);
		request.setAttribute("returnPage", "/servlet/UserServlet?methodName=list");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp");
		dispatcher.forward(request, response);
	}
	
	protected void getUser(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		User user = userManager.getUser(request.getParameter("loginName"));
		request.setAttribute("user", user);
		RequestDispatcher dispatcher = request.getRequestDispatcher("/userManage/update.jsp");
		dispatcher.forward(request, response);  
	}
	
	protected void updateUser(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		// 更新用户信息
		User user = new User();
		user.setLoginName(request.getParameter("loginName"));
		user.setUserPasswd(request.getParameter("userPasswd"));
		user.setRealName(request.getParameter("realName"));
		user.setTel(request.getParameter("tel"));
		user.setEmail(request.getParameter("email"));
		userManager.updateUser(user);
		// 跳转到成功页面
		request.setAttribute("returnPage", "/servlet/UserServlet?methodName=list");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp");
		dispatcher.forward(request, response);  
	}
	
	protected void deleteUser(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		String[] loginNameArray = request.getParameterValues("loginName");
		userManager.deleteUser(loginNameArray);
		// 跳转到成功页面
		request.setAttribute("returnPage", "/servlet/UserServlet?methodName=list");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp");
		dispatcher.forward(request, response);  
	}
	
	protected void initUpdateUserRole(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		List roleList = roleManager.getRoleList();		   // 全部角色列表
		List<Role> selectRoleList = new ArrayList<Role>(); // 该用户已选择的角色列表
		List<Role> notSelRoleList = new ArrayList<Role>(); // 该用户未选择的角色列表
		
		User user = userManager.getUser(request.getParameter("loginName"));
		Set selectRoleSet = user.getRoles();
		Iterator ite = selectRoleSet.iterator();
		while (ite.hasNext()) {
			selectRoleList.add((Role)ite.next());
		}
		
		boolean flag = false;
		if (!roleList.isEmpty()) {
			ite = roleList.iterator();
			while (ite.hasNext()) {
				flag = false;
				Map<String, String> map = (Map<String, String>) ite.next();
				Role role = new Role();
				role.setTrId(Long.parseLong(map.get("trId")));
				role.setRoleName(map.get("roleName"));
				
				for (int i = 0; i < selectRoleList.size(); i++) {
					Role role2 = selectRoleList.get(i);
					if (role2.getTrId() == role.getTrId()) {
						flag = true;
						break;
					}
				}
				
				if (!flag) {
					notSelRoleList.add(role);
				}
			}
		}
		
		request.setAttribute("loginName", request.getParameter("loginName"));
		request.setAttribute("selectList", selectRoleList);
		request.setAttribute("notSelectList", notSelRoleList);
		RequestDispatcher dispatcher = request.getRequestDispatcher("/userManage/updateUserRole.jsp");
		dispatcher.forward(request, response);  
	}
	
	protected void updateUserRole(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		String loginName = request.getParameter("loginName");
		String roleIds = request.getParameter("roleIds");
		userManager.updateUserRole(loginName, roleIds);
		request.setAttribute("returnPage", "/servlet/UserServlet?methodName=list");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp");
		dispatcher.forward(request, response);  
	}
	
	protected void userLogin(HttpServletRequest request, HttpServletResponse response) 
									throws Exception {
		String loginName = request.getParameter("loginName");
		String loginPasswd = request.getParameter("loginPasswd");
		if ("superadmin".equals(loginName) && "sys123".equals(loginPasswd)) {
			// 超级管理员
			List list = rightManager.getRightList();
			List<TRight> rightList = new ArrayList<TRight>();
			request.getSession().removeAttribute("rightList");
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> map = (Map<String, String>) list.get(i);
				TRight right = new TRight();
				right.setTrId(Long.parseLong(map.get("trId")));
				right.setRightName(map.get("rightName"));
				right.setRightUrl(map.get("rightUrl"));
				right.setDescription(map.get("description"));
				rightList.add(right);
			}
			request.getSession().setAttribute("rightList", rightList);
			request.getSession().setAttribute("loginName", loginName);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/userManage/main.jsp");
			dispatcher.forward(request, response);  
		} else {
			// 另外的用户
			int resultCode = userManager.userLogin(loginName, loginPasswd);
			if (resultCode == 0) {
				// 登录成功
				User user = userManager.getUser(loginName);
				request.getSession().setAttribute("loginName", loginName);
				request.setAttribute("user", user);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/userManage/main.jsp");
				dispatcher.forward(request, response);  
			} else if (resultCode == 1) {
				request.setAttribute("errorMsg", "用户不存在!");
				request.setAttribute("returnPage", "/userManage/login.jsp");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
				dispatcher.forward(request, response);  
			} else {
				request.setAttribute("errorMsg", "密码错误!");
				request.setAttribute("returnPage", "/userManage/login.jsp");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
				dispatcher.forward(request, response);  
			}
		}
	}
}
																																												