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

import javax.servlet.http.HttpServletRequest;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.common.auth.annotation.RoleRequire;
import cn.com.qmth.stmms.common.enums.Role;

@Controller
@RequestMapping("/admin/exam/subject")
public class SubjectController extends BaseExamController {

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamStudentService studentService;

    @RequestMapping("/edit")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String edit(HttpServletRequest request, @RequestParam String code, Model model) {
        ExamSubject subject = subjectService.find(getSessionExamId(request), code);
        model.addAttribute("subject", subject);
        return "modules/exam/subjectEdit";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    @Transactional
    public String save(HttpServletRequest request, ExamSubject subject, Model model) {
        ExamSubject previous = subjectService.find(getSessionExamId(request), subject.getCode());
        if (previous != null && StringUtils.isNotBlank(subject.getName())) {
            previous.setName(subject.getName());
            previous.setLevel(subject.getLevel());
            previous.setCategory(subject.getCategory());
            previous.setRemark(subject.getRemark());
            subjectService.save(previous);
            studentService.updateSubjectInfo(previous);
        }
        model.addAttribute("subject", previous);
        model.addAttribute("message", "修改成功");
        return "modules/exam/subjectEdit";
    }
}
