package com.ssm.controller.system;

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

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

import org.apache.commons.lang.StringUtils;
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 org.springframework.web.bind.annotation.RequestParam;
import com.ssm.model.system.SysDepartment;
import com.ssm.model.system.SysRole;
import com.ssm.model.system.SysUser;
import com.ssm.model.validator.UserCreateValidator;
import com.ssm.service.system.SysDepartmentService;
import com.ssm.service.system.SysRoleService;
import com.ssm.service.system.SysUserService;
import com.ssm.util.Util;
import com.ssm.util.page.PagedResult;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;

/**
 * 用户管理 Controller
 * @author xk
 */
@RequestMapping("sysUser")
@Controller
public class SysUserController {
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysDepartmentService sysDepartmentService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	/**
	 * SysUserExample 为模糊匹配条件
	 * 内容根据 condition 来 设置, 分页必须 设置 order by 
	 * 查询 用户 列表 
	 * 分页查询
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "userList")
	@RequestMapping(value="userList")
	public String userList(HttpSession session, Model model,  SysUser condition, 
			Integer pageNo, Integer pageSize){
//		PagedResult<SysUser> pageResult = sysUserService.findAllByContidion(
//				condition != null ? condition.getUsername() : null,
//				condition != null ? condition.getEmployeeno() : null, pageNo, 2);
//		model.addAttribute("list", pageResult);
//		model.addAttribute("condition", condition);
		List<SysRole> roleList = sysRoleService.selectRoleAndMenuList();
		model.addAttribute("roleList", roleList);
		return "sysuser/userList";
	}
	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="initDataList")
	public String initDataList(Model model,  SysUser condition, Integer pageNo, Integer pageSize){
		PagedResult<SysUser> pageResult = sysUserService.findAllByContidion(
		condition != null ? condition.getUsername() : null,
		condition != null ? condition.getEmployeeno() : null, pageNo, 10);
		model.addAttribute("list", pageResult);
		model.addAttribute("condition", condition);
		return "sysuser/dataList";
	}
	
	/**
	 * 添加用户和编辑用户 表单验证
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@InitBinder("user")
	public void InitBinder(DataBinder binder){
		binder.setValidator(new UserCreateValidator());
	}
	
	/**
	 * 进入用户添加 页面
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "userAdd")
	@RequestMapping(value="userAdd", method=RequestMethod.GET)
	public String userAdd(Model model){
		if(!model.containsAttribute("user"))
			model.addAttribute("user", new SysUser());
		//查询所有的部门
		List<SysDepartment> depList = sysDepartmentService.findAll();
		model.addAttribute("depList", depList);
		if(!depList.isEmpty())
			model.addAttribute("firstDep", depList.get(0).getDepid());
		return "sysuser/userAdd";
	}
	
	/**
	 * 添加用户
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "userAdd")
	@Transactional(value="txManager")
	@RequestMapping(value="userAdd", method=RequestMethod.POST)
	public String userAdd(HttpServletRequest request, HttpSession session, Model model, 
			@Validated @ModelAttribute("user") SysUser user, 
			BindingResult result){
		if(result.hasErrors())
			return userAdd(model);
		String employeeno = user.getEmployeeno();
		SysUser isExistsUser = sysUserService.findByEmployeeno(employeeno);
		if(isExistsUser != null) {
			result.addError(new FieldError("user", "employeeno", "员工 "+employeeno+" 已存在"));
			return userAdd(model);
		}
		user.setIsdeleted(false);// 新增的用户,默认 没有被删除
		SysUser operator = Util.getUserSession(request);
		user.setCreateduserid(operator != null ? operator.getUserid() : null);
		user.setCreateddatetime(new Date());
		sysUserService.insertSelective(user);
		return "redirect:/sysUser/userList";
	}
	
	/**
	 * 进入编辑用户 页面
	 * @param model
	 * @param userId
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "userEdit")
	@RequestMapping(value="userEdit", method=RequestMethod.GET)
	public String userEdit(Model model, @RequestParam("userId") Integer userId){
		SysUser user = sysUserService.findById(userId);
		if(!model.containsAttribute("user"))
			model.addAttribute("user", user != null ? user : new SysUser());
		//查询所有的部门
		List<SysDepartment> depList = sysDepartmentService.findAll();
		model.addAttribute("depList", depList);
		//默认选择的部门
		if(user != null)
			model.addAttribute("firstDep", user.getSysDepartment().getDepid());
		return "sysuser/userEdit";
	}
	
	/**
	 * 用户编辑 保存
	 * @param session
	 * @param model
	 * @param user
	 * @param result
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "userEdit")
	@Transactional(value="txManager")
	@RequestMapping(value="userEdit", method=RequestMethod.POST)
	public String userEdit(HttpServletRequest request, HttpSession session, Model model, 
			@Validated @ModelAttribute("user") SysUser user, 
			BindingResult result){
		if(result.hasErrors())
			return userEdit(model, user.getUserid());
		SysUser operator = Util.getUserSession(request);
		user.setLastupdateuserid(operator.getUserid());
		user.setLastupdatedatetime(new Date());
		sysUserService.updateByPrimaryKeySelective(user);
		return "redirect:/sysUser/userList";
	}
	
	/**
	 * 查询 用户 拥有的角色 并 回显到页面
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "findUserRole")
	@RequestMapping(value="findUserRole", method=RequestMethod.POST)
	public Map<String, Object> findUserRoleByUserId(@RequestParam("userId") Integer userId){
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		List<SysRole> roleList = sysRoleService.findUserRoleByUserId(userId);
		record.put("roleList", roleList);
		return record;
	}
	
	
	/**
	 * 更新 用户的状态, 是否有效还是无效
	 * 修改数据库 需要 添加 事物 控制
	 * userStatus 用于 通知 页面 改变 "状态" 样式 
	 * @param userId
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "updateUserEnable")
	@Transactional(value="txManager")
	@RequestMapping(value="updateUserEnable", method=RequestMethod.POST)
	public Map<String, Object> updateUserEnable(@RequestParam("userId") Integer userId){
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		//查询用户
		SysUser user = sysUserService.findById(userId);
		if(user != null) {
			if(user.getIsenabled()) { 
				user.setIsenabled(false);
				record.put("userStatus", false);
			} else {
				user.setIsenabled(true);
				record.put("userStatus", true);
			}
			int count = sysUserService.updateByPrimaryKey(user);
			if(count <= 0)
				record.put("success", false);
		} else {
			//不存在
			record.put("success", false);
		}
		return record;
	}
	
	/**
	 * 用户 更新角色
	 * 先删除，后添加
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "updateUserRole")
	@Transactional(value="txManager")
	@RequestMapping(value="updateUserRole", method=RequestMethod.POST)
	public Map<String, Object> updateUserRole(@RequestParam("userId") Integer userId, @RequestParam("roleIds") String roleIds){
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		sysUserService.deleteUserRole(userId);
		if(StringUtils.isNotBlank(roleIds)){
			String[] roles = roleIds.split(",");
			for(String roleId : roles){
				sysUserService.insertUserRole(userId, Integer.valueOf(roleId));
			}
		}
		return record;
	}
	
	
	/**
	 * 重置用户密码， 密码在const 里配置 ,默认为dgt.0000
	 * 修改数据库 需要 添加 事物 控制
	 * @param userId
	 * @return
	 */
	@RoleLimit(pid = "sysUser", mid = "resetUserPw")
	@Transactional(value="txManager")
	@RequestMapping(value="resetUserPw", method=RequestMethod.POST)
	public Map<String, Object> resetUserPw(@RequestParam("userId") Integer userId){
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		//查询用户
		SysUser user = sysUserService.findById(userId);
		if(user != null) {
			user.setPassword(Const.DEFAULT_USER_PASSWORD);
			int count = sysUserService.updateByPrimaryKey(user);
			if(count <= 0)
				record.put("success", false);
		} else {
			//不存在
			record.put("success", false);
		}
		return record;
	}
	
	@RoleLimit(pid = "sysUser", mid = "deleteUser")
	@Transactional(value="txManager")
	@RequestMapping(value="deleteUser", method=RequestMethod.POST)
	public Map<String, Object> deleteUser(@RequestParam("userId") Integer userId){
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		sysUserService.deleteUser(userId);
		return record;
	}
	
}
