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.ReportSubjectClass;
import cn.com.qmth.stmms.biz.report.service.ReportSubjectClassService;
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 SubjectClassModule extends SubjectModule implements Module {

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

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

    public void save() {
        ReportSubjectClassService service = SpringContextHolder.getBean(ReportSubjectClassService.class);
        ExamStudentService studentService = SpringContextHolder.getBean(ExamStudentService.class);
        for (String key : this.units.keySet()) {
            String s[] = key.split("\t");
            if (s.length > 1) {
                String subjectCode = s[0];
                String className = s[1];
                BaseCalculatorUnit unit = units.get(key);
                BaseCounter counter = counters.get(key);
                ReportSubjectClass r = new ReportSubjectClass();
                r.setExamId(this.context.getExamId());
                r.setSubjectCode(subjectCode);
                r.setSubjectName(context.getSubject(subjectCode).getName());
                r.setClassName(className);
                r.setAvgScore(unit.avgScore);
                r.setMaxScore(unit.maxScore);
                r.setMinScore(unit.minScore);
                r.setPassCount(unit.passCount);
                r.setPassRate(unit.passRate);
                r.setExcellentCount(unit.excellentCount);
                r.setExcellentRate(unit.excellentRate);
                r.setCoefficient(unit.coefficient);
                r.setDifficulty(unit.difficulty);
                r.setStdev(unit.stdev);
                r.setTotalCount((int) studentService.countByExamIdAndSubjectCodeAndClass(this.context.getExamId(),
                        subjectCode, className));
                r.setRealityCount(counter.realityCount);
                service.save(r);
            }
        }
    }

}
