package cn.com.qmth.stmms.biz.report.utils.module;

import org.apache.commons.lang.StringUtils;

import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.report.model.ReportSubjectTeacher;
import cn.com.qmth.stmms.biz.report.service.ReportSubjectTeacherService;
import cn.com.qmth.stmms.biz.report.utils.Module;
import cn.com.qmth.stmms.biz.report.utils.ReportContext;
import cn.com.qmth.stmms.biz.report.utils.unit.BaseCalculatorUnit;
import cn.com.qmth.stmms.biz.report.utils.unit.BaseCounter;
import cn.com.qmth.stmms.biz.utils.SpringContextHolder;

public class SubjectTeacherModule extends SubjectModule implements Module {

    public SubjectTeacherModule(ReportContext context) {
        super(context);
    }

    public String getKey(ExamStudent student) {
        return student.getSubjectCode() + "\t" + StringUtils.trimToEmpty(student.getTeacher());
    }

    public void save() {
        ReportSubjectTeacherService service = SpringContextHolder.getBean(ReportSubjectTeacherService.class);
        ExamStudentService studentService = SpringContextHolder.getBean(ExamStudentService.class);

        for (String key : this.units.keySet()) {
            BaseCalculatorUnit unit = units.get(key);
            BaseCounter counter = counters.get(key);
            String s[] = key.split("\t");
            if (s.length > 1) {
                String subjectCode = s[0];
                String teacherName = s[1];
                ReportSubjectTeacher subject = new ReportSubjectTeacher();
                subject.setExamId(this.context.getExamId());
                subject.setSubjectCode(subjectCode);
                subject.setSubjectName(context.getSubject(subjectCode).getName());
                subject.setTeacherName(teacherName);
                subject.setRealityCount(counter.realityCount);
                subject.setTotalCount((int) studentService.countByExamIdAndSubjectCodeAndTeacher(
                        this.context.getExamId(), subjectCode, teacherName));
                subject.setPassCount(unit.passCount);
                subject.setExcellentCount(unit.excellentCount);
                subject.setMaxScore(unit.maxScore);
                subject.setMinScore(unit.minScore);
                subject.setPassRate(unit.passRate);
                subject.setExcellentRate(unit.excellentRate);
                subject.setAvgScore(unit.avgScore);
                service.save(subject);
            }
        }
    }

}
