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

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.annotation.Logging;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.utils.EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;
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 javax.servlet.http.HttpServletRequest;

/**
 * 个人账号管理
 *
 * @author ThinkGem
 * @version 2013-5-31
 */
@Controller
@RequestMapping(value = "/admin/account")
public class AccountController {

    @Autowired
    private UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Logging(menu = "用户详情", type = LogType.QUERY)
    @RequestMapping(value = "/info")
    public String info(HttpServletRequest request, Model model) {
        User currentUser = RequestUtils.getWebUser(request).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";
    }

    @Logging(menu = "修改密码", type = LogType.UPDATE)
    @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 (EncryptUtils.md5(oldPassword).equals(user.getPassword())) {
                user.setPassword(EncryptUtils.md5(newPassword));
                userService.save(user);
                model.addAttribute("message", "修改密码成功");
            } else {
                model.addAttribute("message", "修改密码失败，旧密码错误");
            }
        }
        model.addAttribute("user", user);
        return "modules/sys/userModifyPwd";
    }
}
