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

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.utils.SessionExamUtils;
import cn.com.qmth.stmms.admin.vo.ExamInfoVO;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.query.ExamSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.auth.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.Paginator;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin")
public class ExamController extends BaseExamController {

    protected static Logger log = LoggerFactory.getLogger(ExamController.class);

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamStudentService examStudentService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @RequestMapping(value = { "/exam-list" })
    public String examList(Model model, HttpServletRequest request, ExamSearchQuery query) {
        SessionExamUtils.clearExamId(request);
        User user = RequestUtils.getWebUser(request).getUser();
        query.setSchoolId(user.getSchoolId());
        query.orderByIdDesc();
        query = examService.findByQuery(query);
        if (query.getCurrentCount() > 0) {
            model.addAttribute("examList", query.getResult());
            model.addAttribute("paginator",
                    new Paginator(query.getPageNumber(), query.getPageSize(), (int) query.getTotalCount()));
        }
        model.addAttribute("query", query);
        return "modules/exam/examList";
    }

    @RequestMapping("/exam-create")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String add(Exam exam, Model model) {
        model.addAttribute("exam", exam);
        model.addAttribute("statusList", ExamStatus.values());
        return "modules/exam/examForm";
    }

    @RequestMapping("/exam-edit/{examId}")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String edit(@PathVariable Integer examId, Model model) {
        Exam exam = examService.findById(examId);
        model.addAttribute("exam", exam);
        model.addAttribute("statusList", ExamStatus.values());
        return "modules/exam/examEdit";
    }

    @RequestMapping(value = "/exam-save", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String save(HttpServletRequest request, Exam exam, RedirectAttributes redirectAttributes) {
        User user = RequestUtils.getWebUser(request).getUser();
        exam.setSchoolId(user.getSchoolId());
        exam.setCreatorId(user.getId());
        exam.setStatus(ExamStatus.START);
        exam = examService.save(exam);
        addMessage(redirectAttributes, "创建考试'" + exam.getName() + "'成功");
        return "redirect:/admin/exam-list";
    }

    @RequestMapping(value = "/exam-edit", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String examEdit(HttpServletRequest request, Exam exam, int StatusValue, RedirectAttributes redirectAttributes) {
        User user = RequestUtils.getWebUser(request).getUser();
        Exam oldExam = examService.findById(exam.getId());
        if (oldExam != null && oldExam.getCreatorId().intValue() == user.getId().intValue()) {
            oldExam.setName(exam.getName());
            oldExam.setExamTime(exam.getExamTime());
            oldExam.setDescription(exam.getDescription());
            oldExam.setStatus(ExamStatus.findByValue(StatusValue));
            oldExam.setForceSpecialTag(exam.isForceSpecialTag());
            oldExam.setPassScore(exam.getPassScore());
            oldExam.setExcellentScore(exam.getExcellentScore());
            examService.save(oldExam);
        }
        return "redirect:/admin/exam-list";
    }

    @RequestMapping("/exam-select/{examId}")
    public String select(Model model, HttpServletRequest request, @PathVariable Integer examId) {
        SessionExamUtils.setExamId(request, examId);
        WebUser wu = RequestUtils.getWebUser(request);
        if (wu.isSchoolViewer()) {
            return "redirect:/admin/exam/score";
        }
        return "redirect:/admin/exam/student";
    }

    @RequestMapping("/exam-view/{examId}")
    public String view(Model model, HttpServletRequest request, @PathVariable Integer examId) {
        SessionExamUtils.setExamId(request, examId);

        Exam exam = examService.findById(examId);
        long studentCount = examStudentService.countByExamId(exam.getId());
        long subjectCount = examSubjectService.count(examId);
        long campusCount = examStudentService.countCampusByExam(examId);
        long markerCount = markerService.countByExam(exam.getId());
        long scanCount = examStudentService.countByExamIdAndUpload(examId, true);
        long markedCount = examStudentService.countByExamIdAndSubjectiveScoreListIsNotNull(examId);

        List<ExamInfoVO> voList = new ArrayList<ExamInfoVO>();

        ExamInfoVO student = new ExamInfoVO();
        student.setName("考生");
        student.setAttr("共导入 " + studentCount + " 个考生");
        student.setUrl("/admin/exam/student");

        ExamInfoVO subject = new ExamInfoVO();
        subject.setName("科目");
        subject.setAttr("共导入 " + subjectCount + " 个科目");
        subject.setUrl("/admin/exam/paper");

        ExamInfoVO campus = new ExamInfoVO();
        campus.setName("学习中心");
        campus.setAttr("共导入 " + campusCount + " 个学习中心");
        campus.setUrl("/admin/exam/student");

        ExamInfoVO marker = new ExamInfoVO();
        marker.setName("评卷员");
        marker.setAttr("已创建 " + markerCount + " 个评卷员");
        marker.setUrl("/admin/exam/marker");

        ExamInfoVO scan = new ExamInfoVO();
        scan.setName("扫描进度");
        scan.setAttr("已扫描 " + scanCount + " 个考生");
        scan.setUrl("/admin/exam/scan");

        ExamInfoVO mark = new ExamInfoVO();
        mark.setName("评卷进度");
        mark.setAttr("已评完 " + markedCount + " 个考生");
        mark.setUrl("/admin/exam/mark");

        voList.add(student);
        voList.add(subject);
        voList.add(campus);
        voList.add(marker);
        voList.add(scan);
        voList.add(mark);
        model.addAttribute("exam", exam);
        model.addAttribute("list", voList);
        return "modules/exam/examInfo";
    }

    @RequestMapping("/exam/info")
    @ResponseBody
    public Exam getExamInfo(HttpServletRequest request) {
        Exam exam = examService.findById(getSessionExamId(request));
        return exam;
    }

    @RequestMapping("/exam/finish")
    @ResponseBody
    @RoleRequire(Role.SCHOOL_ADMIN)
    public void finished(HttpServletRequest request) {
        Exam exam = examService.findById(getSessionExamId(request));
        exam.setStatus(ExamStatus.FINISH);
        examService.save(exam);
    }

}
