package com.ssm.controller.system;

import java.util.Date;

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

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.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ssm.model.system.SysUser;
import com.ssm.service.system.SysUserService;
import com.ssm.util.Util;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;

/**
 * 个人设置
 * @author Administrator
 *
 */
@Controller
@RequestMapping("person")
public class PersonalController {
	@Autowired
	private SysUserService sysUserService;
	/**
	 * 修改个人密码
	 * @param model
	 * @param session
	 * @return
	 */
	@RoleLimit(pid = "person", mid = "updatePassword")
	@RequestMapping(value="updatePassword",method=RequestMethod.GET)
	public String updatePassword(HttpServletRequest request, Model model,HttpSession session){
		SysUser user = Util.getUserSession(request);
		SysUser su = new SysUser();
		su.setEmailaddress(user.getEmailaddress());
		//2.绑定SysUser对象
		if(!model.containsAttribute("sysUser"))
			model.addAttribute("sysUser",su);
		return "sysperson/passwordUpdate";
	}
	/**
	 * 保存用户密码
	 * @param sysUser
	 * @param session
	 * @param result
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value="txManager")
	@RequestMapping(value="updatePassword",method=RequestMethod.POST)
	public String getAddLocation(HttpServletRequest request, @Validated @ModelAttribute("sysUser") SysUser sysUser,HttpSession session,
			BindingResult result,Model model){
		SysUser user = Util.getUserSession(request);
		if(!user.getPassword().equals(sysUser.getJ_password())){
			result.addError(new FieldError("sysUser", "j_password", "旧密码不正确,请重新输入！"));
			return updatePassword(request,model,session);
		}
		sysUser.setUserid(user.getUserid());
		sysUser.setLastupdatedatetime(new Date());
		sysUserService.updateByPrimaryKeySelective(sysUser);
		session.invalidate();
		return "redirect:/login";
	}

}
