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 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.role.Role;
import org.ccpit.base.role.RoleDao;
import org.ccpit.base.usergroup.UserGroup;
import org.ccpit.base.usergroup.UserGroupDao;
import org.ccpit.base.usergroup.UserGroupService;
import org.ccpit.base.utils.CryptUtil;
import org.ccpit.base.utils.PasswordHash;
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;

/**
 * Created by sqp on 2015/9/5.
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private UserGroupService orgService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserGroupDao orgDao;

	@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;
	}

	@RequestMapping("/addUser")
	public void addUser(HttpServletRequest request,HttpServletResponse response,User user) {
		String result = "";
		User user_in_session = (User) request.getSession().getAttribute("user_in_session");
		try {
			//新增用户初始化密码
			user.setPassword(PasswordHash.createHash("111111"));
		} catch (Exception e) {
			throw new RuntimeException("新增用户初始化密码加密失败....", e);
		}
		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);
		}
		boolean flag = userService.addUser(user);
		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();
		}
	}

	@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;
	}
	
	@RequestMapping("/deleteUser")
	@ResponseBody
	public Object deleteUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String jsonIds = request.getParameter("ids");
		JSONArray jsonArray = JSONArray.fromObject(jsonIds);
		Object[] ids = jsonArray.toArray();
		boolean flag = false;
		for(Object str : ids){
			flag = userService.deleteUser((Integer) str);
		}
		if(flag){
			map.put("flag", flag);
			map.put("info", "数据删除成功！");
		}else {
			map.put("info", "数据删除失败！");
		}
		return map;
	}

	@RequestMapping("/queryAllUser")
	public Object queryAllUser() {
		ModelAndView mv = new ModelAndView("admin/user/manage");
		return mv;
	}

	@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 desc");
		}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 desc");
		}
		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 "";
	}
	
	/**
	 * 用户密码重置
	 */
	@RequestMapping("/resetPass")
	@ResponseBody
	public Object resetPass(HttpServletRequest request, HttpServletResponse response){
		Map result = new HashMap();
		String id = request.getParameter("userId");
		User user = userService.getUser(Long.valueOf(id));
		try {
			user.setPassword(PasswordHash.createHash("111111"));
		} catch (Exception e) {
			throw new RuntimeException("重置用户密码加密失败....", e);
		}
		boolean b = userService.updateUser(user);
		if(b){
			result.put("flag", true);
		}else {
			result.put("flag", false);
		}
		return result;
	}
	
	/**
	 * 用户密码修改
	 */
	@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) {
			throw new RuntimeException("修改用户密码加密失败....", 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;
	}
}
