package cn.com.qmth.stmms.admin.home;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.utils.Md5EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;
/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-5-31
 */
@Controller
@RequestMapping(value = "/admin/sys/user/")
public class SystemController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private SchoolService schoolService;
	
	@RequestMapping(value = "info")
	public String info(HttpServletRequest request, Model model) {
	    WebUser wu = RequestUtils.getWebUser(request);
	    User currentUser = wu.getUser();
		School school = schoolService.findById(currentUser.getSchoolId());
		
		model.addAttribute("user", currentUser);
		model.addAttribute("school", school);
		return "modules/sys/userInfo";
	}
	
	@RequestMapping(value = "info/save",method=RequestMethod.POST)
    public String save(User user, Model model) {
        user = userService.save(user);
        School school = schoolService.findById(user.getSchoolId());
        
        model.addAttribute("user", user);
        model.addAttribute("school", school);
        return "modules/sys/userInfo";
    }
	
	@RequestMapping(value = "modifyPwd",method=RequestMethod.GET)
    public String modifyPwd() {
        return "modules/sys/userModifyPwd";
    }

	@RequestMapping(value = "modifyPwd",method=RequestMethod.POST)
	public String modifyPwd(HttpServletRequest request,String oldPassword, String newPassword, Model model) {
		User user = RequestUtils.getWebUser(request).getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if (Md5EncryptUtils.md5(oldPassword).equals(user.getPassword())){
				user.setPassword(Md5EncryptUtils.md5(newPassword));
				userService.save(user);
				model.addAttribute("message", "修改密码成功");
			}else{
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}
}
