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

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

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.RequestIPUtil;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Value("${marker.name.verify}")
    private boolean nameVerify;

    @RequestMapping(value = "/reset", method = RequestMethod.GET)
    public ModelAndView reset(HttpServletRequest request) {
        User user = RequestUtils.getWebUser(request).getUser();
        ModelAndView modelAndView = new ModelAndView("modules/sys/reset");
        modelAndView.addObject("user", user);
        modelAndView.addObject("nameVerify", nameVerify);
        return modelAndView;
    }

    @Logging(menu = "修改姓名密码", type = LogType.UPDATE)
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    public ModelAndView reset(HttpServletRequest request, User user) {
        User current = RequestUtils.getWebUser(request).getUser();
        if (current.getPassword().equalsIgnoreCase(EncryptUtils.md5(user.getPassword()))) {
            ModelAndView modelAndView = new ModelAndView("modules/sys/reset");
            modelAndView.addObject("message", "新密码不可与初始密码一致");
            modelAndView.addObject("user", user);
            modelAndView.addObject("nameVerify", nameVerify);
            return modelAndView;
        }
        current.setName(user.getName());
        current.setEmpno(user.getEmpno());
        current.setRandomPassword(null);
        current.setPassword(EncryptUtils.md5(user.getPassword()));
        current.setLastLoginIp(RequestIPUtil.getIpAddress(request));
        current.setLastLoginTime(new Date());
        userService.save(current);
        return new ModelAndView("redirect:/admin/exam/select");
    }

}
