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

import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.report.model.ReportSubject;
import cn.com.qmth.stmms.biz.report.model.ReportSubjectQuestion;
import cn.com.qmth.stmms.biz.report.service.ReportSubjectQuestionService;
import cn.com.qmth.stmms.biz.report.service.ReportSubjectService;
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.OptionCounter;
import cn.com.qmth.stmms.biz.utils.SpringContextHolder;

/**
 * 按科目统计全样本小题选项指标
 * 
 * @author luoshi
 *
 */
public class SubjectQuestionOptionModule implements Module {

    private Map<String, OptionCounter> counters;

    private ReportContext context;

    private Map<String, Set<String>> optionMap;

    public static final String ANSWER_SPLIT = ",";

    public static final String ANSWER = "#";

    public SubjectQuestionOptionModule(ReportContext context) {
        this.counters = new HashMap<String, OptionCounter>();
        this.context = context;
        this.optionMap = new HashMap<String, Set<String>>();
    }

    public void process(ExamStudent student) {
        if (student.isUpload() && !student.isAbsent() && !student.isBreach() && student.getSubject() != null) {
            // 遍历客观题
            process(student, student.getAnswerList(), student.getObjectiveQuestionList());
        }
    }

    private void process(ExamStudent student, List<String> answerList, List<ExamQuestion> questionList) {
        if (answerList == null || questionList == null) {
            return;
        }
        int answerCount = answerList.size();
        for (int i = 0; i < questionList.size(); i++) {
            ExamQuestion question = questionList.get(i);
            if (question.getTotalScore() == null || question.getTotalScore() == 0) {
                // 跳过填充试题
                continue;
            }
            // 有实际作答才需要进行选项分析
            if (answerCount > i) {
                findCounter(getKey(student, question), question).process(answerList.get(i));
            }
        }
    }

    public String getKey(ExamStudent student, ExamQuestion question) {
        return question.getSubjectCode() + "\t" + question.isObjective() + "\t"
                + StringUtils.trimToEmpty(question.getPaperType()) + "\t" + question.getMainNumber() + "\t"
                + question.getSubNumber();
    }

    public void save() {
        ReportSubjectQuestionService questionService = SpringContextHolder.getBean(ReportSubjectQuestionService.class);
        ReportSubjectService subjectService = SpringContextHolder.getBean(ReportSubjectService.class);
        for (String key : this.counters.keySet()) {
            String s[] = key.split("\t");
            if (s.length > 4) {
                String subjectCode = s[0];
                String paperType = StringUtils.trimToNull(s[2]);
                Integer mainNumber = Integer.parseInt(s[3]);
                String subNumber = s[4];
                OptionCounter optionCounter = this.counters.get(key);
                Set<String> optionSet = optionMap.get(subjectCode);
                if (optionSet == null) {
                    optionSet = new HashSet<String>();
                }
                JSONObject options = new JSONObject();
                for (String option : optionCounter.getCounter().keySet()) {
                    options.accumulate(option, optionCounter.getCounter().get(option));
                    optionSet.add(option);
                }
                ReportSubjectQuestion r = questionService.findOne(this.context.getExamId(), subjectCode, true,
                        paperType, mainNumber, subNumber);
                r.setOptions(options.toString());
                questionService.save(r);
                optionMap.put(subjectCode, optionSet);
            }
        }
        for (String subjectCode : optionMap.keySet()) {
            ReportSubject r = subjectService.findOne(this.context.getExamId(), subjectCode);
            Set<String> options = optionMap.get(subjectCode);
            options.remove(ANSWER);
            Set<String> sortSet = new TreeSet<String>(new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);
                }
            });
            sortSet.addAll(options);
            r.setOptions(StringUtils.join(sortSet, ANSWER_SPLIT));
            subjectService.save(r);
        }
    }

    private OptionCounter findCounter(String key, ExamQuestion question) {
        OptionCounter counter = counters.get(key);
        if (counter == null) {
            boolean muti = question.getMainTitle().indexOf("多项选择") >= 0 || question.getMainTitle().indexOf("多选") >= 0
                    || question.getMainTitle().indexOf("不定项选择") >= 0;
            counter = new OptionCounter(muti);
            counters.put(key, counter);
        }
        return counter;
    }

}
