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

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.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.biz.campus.model.Campus;
import cn.com.qmth.stmms.biz.campus.service.CampusService;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.model.ExamStudentPaper;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentPaperService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.mark.model.MarkLibrary;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.utils.ScoreCalculateUtil;
import cn.com.qmth.stmms.biz.utils.ScoreInfo;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.enums.ExamSubjectStatus;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.utils.RequestUtils;

public class BaseParameterController extends BaseController {

    public static final int EXAM_SELECT_COUNT = 5;

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

    @Autowired
    private ExamSubjectService examSubjectService;

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamStudentPaperService studentPaperService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private CampusService campusSerivce;

    protected int getSessionExamId(HttpServletRequest request) {
        int examId = 0;
        try {
            examId = Integer.valueOf(RequestUtils.getSession(request).getParameter("examId"));
        } catch (Exception e) {
            // log.error("考试-基础参数设置-examId类型转换出错", e);
        }
        if (examId == 0) {
            try {
                examId = Integer.valueOf(request.getParameter("examId"));
            } catch (Exception e) {
                // log.error("考试-基础参数设置-examId类型转换出错", e);
            }
        }
        return examId;
    }

    protected boolean isFinish(int examId) {
        Exam exam = examService.findById(examId);
        return exam != null ? exam.getStatus() == ExamStatus.ENDED : false;
    }

    protected boolean isMarking(int examId, String subjectCode) {
        ExamSubject subject = examSubjectService.find(examId, subjectCode);
        return subject != null && subject.getStatus() == ExamSubjectStatus.MARKING;
    }

    /**
     * 添加Flash消息
     * 
     * @param messages
     *            消息
     */
    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
    }

    protected List<ExamSubject> getExamSubject(int examId) {
        return examSubjectService.list(examId);
    }

    protected List<ExamSubject> getMarkExamSubject(int examId) {
        return examSubjectService.list(examId, 0, 0);
    }

    protected void saveMarkLibrary(ExamStudent student) {
        if (student.isAbsent() || student.isBreach()) {
            // 缺考(或违纪)则强制删除评卷任务
            libraryService.deleteByStudent(student.getId());
        } else {
            MarkLibrary library = libraryService.findByStudentId(student.getId());
            if (library == null) {
                Campus campus = campusSerivce.findBySchoolAndName(student.getSchoolId(), student.getCampusName());

                library = new MarkLibrary();
                library.setExamId(student.getExamId());
                library.setSubjectCode(student.getSubjectCode());
                library.setCampusId(campus.getId());
                library.setStudentId(student.getId());
                library.setExamNumber(student.getExamNumber());
                library.setPicStart(1);
                library.setPicCount(student.getSliceCount());
                library.setStatus(LibraryStatus.WAITING);
            } else {
                library.setPicCount(student.getSliceCount());
            }
            libraryService.save(library);
        }
        calculateObjectiveScore(student);
        subjectService.updateLibraryCount(student.getExamId(), student.getSubjectCode(),
                (int) libraryService.countByExamAndSubject(student.getExamId(), student.getSubjectCode()));
        subjectService.updateMarkedCount(student.getExamId(), student.getSubjectCode(), (int) libraryService
                .countByExamAndSubjectAndStatus(student.getExamId(), student.getSubjectCode(), LibraryStatus.MARKED));
    }

    protected void calculateObjectiveScore(ExamStudent student) {
        ScoreCalculateUtil util = ScoreCalculateUtil.instance(student);

        List<ExamQuestion> list = null;
        // 优先取考生专属客观题结构
        ExamStudentPaper paper = studentPaperService.find(student.getExamId(), student.getExamNumber(), true);
        if (paper != null) {
            list = paper.getQuestionList();
        }
        // 没有再取科目通用客观题结构
        if (list == null || list.isEmpty()) {
            list = questionService.findByExamAndSubjectAndObjective(student.getExamId(), student.getSubjectCode(),
                    true);
        }
        ScoreInfo info = util.calculate(list, null);

        student.setObjectiveScore(info.getObjectiveScore());
        student.setScoreList(info.getScoreList(), true);
    }

}
