package org.ccpit.base.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

import net.sf.json.JSONArray;

import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.orgManage.OrgInfo;
import org.ccpit.base.orgManage.OrgService;
import org.ccpit.base.role.RoleDao;
import org.ccpit.base.usergroup.UserGroupDao;
import org.ccpit.base.utils.PasswordHash;
import org.ccpit.base.utils.StringUtil;
import org.ccpit.base.utils.mailUtil.Mail;
import org.ccpit.base.utils.mailUtil.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * ClassName: UserController <br/>
 * Function: TODO 用户信息控制类. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2015年5月14日 下午8:53:32 <br/>
 *
 * @author dingwei
 * @version 
 * @since JDK 1.6
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

	private static final Logger loger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
//	@Autowired
//	private UserGroupService orgService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserGroupDao orgDao;
	/**
	 * 
	 * isExistUser:(判断用户是否存在). <br/>
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/isExistUser")
	@ResponseBody
	public Object isExistUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String loginName = request.getParameter("loginName");
		User user = userService.getUserByLoginName(loginName);
		if (null == user) {
			map.put("flag", false);
		} else {
			map.put("flag", true);
		}
		return map;
	}
	/**
	 * 
	 * addUser:(部门新增用户). <br/>
	 * @author dingwei
	 * @param request
	 * @param response
	 * @param user
	 * @since JDK 1.6
	 */
	@RequestMapping("/addUser")
	public void addUser(HttpServletRequest request,HttpServletResponse response,User user) {
		String result = "";
		User user_in_session = (User) request.getSession().getAttribute("user_in_session");
		String orgId = request.getParameter("orgId");
		String userId = request.getParameter("userId");
		String operation = request.getParameter("operation");
		boolean flag = false;
		if("add".equals(operation)){
			OrgInfo orgInfo = orgService.getOrgById(Integer.valueOf(orgId));
			user.setCreatorId(user_in_session.getId());
			user.setCreator(user_in_session.getUsername());
			user.setCreateTime(new Date());
			if(null == user.getUserType()){
				user.setUserType("back");
			}
			if(null == user.getCountStatus()){
				user.setCountStatus(1);
			}
			if(null != orgInfo){
				Set<User> userSet = orgInfo.getUsers();
				userSet.add(user);
				orgInfo.setUsers(userSet);
				flag = orgService.updateOrg(orgInfo);
			}
		}else {
			OrgInfo orgInfo = orgService.getOrgById(Integer.valueOf(orgId));
			if(null != orgInfo){
				Set<User> userSet = orgInfo.getUsers();
				List<User> userList = new ArrayList<User>(userSet);
				for(int i=0;i<userList.size();i++){
					long userid = userList.get(i).getId();
					if(String.valueOf(userid).equals(userId)){
						userSet.remove(userList.get(i));
						orgInfo.setUsers(userSet);
						boolean flag1 = orgService.updateOrg(orgInfo);
						if(flag1){
							OrgInfo orgInfo1 = orgService.getOrgById(Integer.valueOf(orgId));
							User user1 = userService.getUser(Integer.valueOf(userId));
							if(null != user.getAge()){
								user1.setAge(user.getAge());
							}if(null != user.getCompany()){
								user1.setCompany(user.getCompany());
							}if(null != user.getEmail()){
								user1.setEmail(user.getEmail());
							}if(null != user.getLoginName()){
								user1.setLoginName(user.getLoginName());
							}if(null != user.getSex()){
								user1.setSex(user.getSex());
							}if(null != user.getTelphone()){
								user1.setTelphone(user.getTelphone());
							}if(null != user.getUsername()){
								user1.setUsername(user.getUsername());
							}if(null != user.getUserType()){
								user1.setUserType(user.getUserType());
							}
							userSet = orgInfo1.getUsers();
							userSet.add(user1);
							orgInfo1.setUsers(userSet);
							flag = orgService.updateOrg(orgInfo1);
						}
					}
				}
			}
		}
		if(flag){
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存成功！\" }";
		}else {
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存失败！\" }";
		}
		try { 
			response.setContentType("text/html");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * editUser:(编辑用户信息). <br/>
	 * @author dingwei
	 * @param id
	 * @param user
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/edit/{id}")
	@ResponseBody
	public Object editUser(@PathVariable long id, User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user1 = userService.getUser(id);
		boolean flag = false;
		if(null != user.getAge()){
			user1.setAge(user.getAge());
		}
		if(null != user.getCountStatus()){
			user1.setCountStatus(user.getCountStatus());
		}
		if(null != user.getCompany()){
			user1.setCompany(user.getCompany());
		}
		if(null != user.getEmail()){
			user1.setEmail(user.getEmail());
		}
		if(null != user.getLoginName()){
			user1.setLoginName(user.getLoginName());
		}
		if(null != user.getSex()){
			user1.setSex(user.getSex());
		}
		if(null != user.getTelphone()){
			user1.setTelphone(user.getTelphone());
		}
		if(null != user.getUsername()){
			user1.setUsername(user.getUsername());
		}
		if(null != user.getUserType()){
			user1.setUserType(user.getUserType());
		}
		flag = userService.updateUser(user1);
		if (flag) {
			map.put("success", flag);
			map.put("info", "修改用户数据成功！");
		} else {
			map.put("info", "修改用户数据失败...");
		}
		return map;
	}

	@RequestMapping("/getUserById/{id}")
	@ResponseBody
	public User getUserById(@PathVariable long id) {
		User user = userService.getUser(id);
		return user;
	}
	/**
	 * 
	 * deleteUser:(删除用户信息). <br/>
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/deleteUser")
	@ResponseBody
	public Object deleteUser(HttpServletRequest request) {
		Map map = new HashMap();
		String orgId = request.getParameter("orgId");
		String userId = request.getParameter("userId");
		Set<User> setUser = new HashSet<User>();
		PageRequest pageRequest = this.getPage(request);
		Page<User> users = new Page<User>(pageRequest);
		boolean flag = false;
		if(null != orgId){
			OrgInfo org = orgService.getOrgById(Long.valueOf(orgId));
			setUser = org.getUsers();
			if(null != userId){
				User user = userService.getUser(Long.valueOf(userId));
				if(setUser.contains(user)){
					setUser.remove(user);
				}
				org.setUsers(setUser);
				boolean flag1 = orgService.updateOrg(org);
				if(flag1){
					user.setWhetherDelete(true);
					flag = userService.updateUser(user);
				}
			}
		}
		if(flag){
			map.put("flag", flag);
			map.put("info", "数据删除成功！");
		}else {
			map.put("flag", flag);
			map.put("info", "数据删除失败！");
		}
		return map;
	}

	@RequestMapping("/queryAllUser")
	public Object queryAllUser() {
		ModelAndView mv = new ModelAndView("admin/user/manage");
		return mv;
	}
	/**
	 * 
	 * getAllUsers:(查询所有用户信息列表). <br/>
	 * @author dingwei
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/getAllUsers")
	@ResponseBody
	public Object getAllUsers(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		PageRequest pageRequest = this.getPage(request);
		String userName = request.getParameter("userName");
		String userType = request.getParameter("userType");
		StringBuffer hql = new StringBuffer("from User where 1=1");
		if(null == userName && null == userType){
			hql.append(" order by createTime asc");
		}else {
			if(null != userName && !"".equals(userName)){
				hql.append(" and userName like '%" + userName + "%'");
			}
			if(null != userType && !"".equals(userType)){
				hql.append(" and userType ='"+ userType +"'");
			}
			hql.append(" order by createTime asc");
		}
		Page<User> users = userService.queryPage(pageRequest,hql.toString());
		return userService.convert(users);
	}

	/*@RequestMapping("/get/{id}")
	@ResponseBody
	public Object get(@PathVariable long id) {
		if (id != 0) {

			UserGroup usergroup = new UserGroup();
			Set<Role> roles = new HashSet<Role>();
			Set<User> users = new HashSet<User>();
			roles.add(roleDao.queryById(2L));
			users.add(userDao.queryById(1L));
			usergroup.setRoles(roles);
			usergroup.setUsers(users);
			usergroup.setName("test usergroup 1");
			orgService.save(usergroup);

			UserGroup org = orgDao.queryById(2L);
			System.out.println(org);
			User user = userService.getUser(id);
			return user;
		}
		return "";
	}*/
	
	/**
	 * 
	 * changePass:(用户密码修改). <br/>
	 * @author dingwei
	 * @param request
	 * @param rePass
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("/changePass/{rePass}")
	@ResponseBody
	public Object changePass(HttpServletRequest request,@PathVariable String rePass){
		Map result = new HashMap();
		User user = (User) request.getSession().getAttribute("user_in_session");
		try {
			user.setPassword(PasswordHash.createHash(rePass));
		} catch (Exception e) {
			loger.error("修改用户密码加密失败....", e);
		}
		boolean b = userService.updateUser(user);
		if(b){
			result.put("flag", true);
			result.put("info", "密码修改成功！");
		}else {
			result.put("flag", false);
		}
		return result;
	}
	
	@RequestMapping("/getUsersList")
	@ResponseBody
	public Object getUsersList(HttpServletRequest request){
		List<User> listBo = userService.getAllUsers();
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getId());
				result.put("text", listBo.get(i).getUsername());
				list.add(result);
			}
		}
		return list;
	}
	/**
	 * 
	 * sendEmailToUser:(修改用户登录密码之后通过邮件发送给用户). <br/>
	 * @author dingwei
	 * @param request
	 * @param response
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping("sendEmailToUser")
	@ResponseBody
	public Object sendEmailToUser(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user_in_session");
		
		String emailCount = null == user.getUserEmail()?"":user.getUserEmail().getEmailCount(); //邮箱账号
		String emailPassword = null == user.getUserEmail()?"":user.getUserEmail().getEmailPassword(); //邮箱密码
		String emailServerHost = null == user.getUserEmail()?"":user.getUserEmail().getServerHost(); //邮箱服务器地址
		String protocol = null == user.getUserEmail()?"":user.getUserEmail().getServerProtocol(); //邮箱服务器协议
		String port = null == user.getUserEmail()?"":user.getUserEmail().getServerPort(); //邮箱服务器端口号
		String jsonIds = request.getParameter("ids");
		JSONArray jsonArray = JSONArray.fromObject(jsonIds);
		Object[] ids = jsonArray.toArray();
		boolean flag = false;
		if(null != emailCount && !"".equals(emailCount)){
			Mail mail = new Mail();
			mail.setSender(emailCount);
			mail.setHost(emailServerHost);
			mail.setEmailPassword(emailPassword);
			mail.setEmailCount(emailCount);
			mail.setProtocol(protocol);
			mail.setMailTitle(StringUtil.SYSTEM_NAME+"账号和密码");
			
			String userPassword = "";
			for(Object str : ids){
				User user1 = userService.getUser((Integer)str);
				userPassword = StringUtil.getRandomString(15);
				mail.setReceiver(user1.getEmail());
				try {
					user1.setPassword(PasswordHash.createHash(userPassword));
				} catch (Exception e) {
					e.printStackTrace();
				}
				StringBuffer sb = new StringBuffer();
				sb.append("尊敬的"+user1.getUsername()+":");
				sb.append("<br>");
				sb.append("&emsp;&emsp;您好！您的"+StringUtil.SYSTEM_NAME+"登录账号：<font style='color:red'>"+user1.getLoginName()+"</font> 登录密码：<font style='color:green'>"+ userPassword+"</font> 您可以再登录系统之后在系统右上角修改登录密码！");
				sb.append("<br><br>");
				sb.append("&emsp;&emsp;"+StringUtil.SYSTEM_NAME+"访问地址："+StringUtil.SYSTEM_VISIT_URL+"/admin/login");
				sb.append("<br><br>");
				sb.append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;");
				sb.append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;");
				sb.append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;系统管理员");
				mail.setMailMessage(sb.toString());
				boolean flag1 = userService.updateUser(user1);
				if(flag1){
					flag = MailUtil.sendMail(mail);
				}
			}
			if(flag){
				map.put("flag", flag);
				map.put("info", "邮件发送成功！");
			}else {
				map.put("flag", flag);
				map.put("info", "邮件发送失败！");
			}
		}else {
			map.put("flag", flag);
			map.put("info", "邮件发送失败,发送邮件邮箱不存在，请在右上角配置发送邮件邮箱账号信息！");
		}
		
		return map;
	}
	  
}
