package ink.wgink.module.examine.listener.question;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @ClassName: TestQuestionExcelListener
 * @Description: 试题导入
 * @Author: WangGeng
 * @Date: 2021/4/2 21:08
 * @Version: 1.0
 **/
public abstract class QuestionExcelListener extends AnalysisEventListener<QuestionExcel> {

    private static final int MAX_QUESTIONS = 100;
    public static final String QUESTION_CHOICE = "选择题";
    public static final String QUESTION_TRUE_OR_FALSE = "判断题";
    public static final String QUESTION_FILL_IN_THE_BLANKS = "填空题";
    public static final String QUESTION_ANSWER = "解答题";

    public static final String QUESTION_CHOICE_NO = "无";
    public static final String QUESTION_CHOICE_SINGLE = "单选";
    public static final String QUESTION_CHOICE_MULTIPLE = "多选";
    private List<QuestionExcel> questionExcels = new ArrayList<>();

    @Override
    public void invoke(QuestionExcel questionExcel, AnalysisContext analysisContext) {
        if (questionExcel.getNo() != null) {
            // 序号不为空，加入试题列表
            questionExcels.add(questionExcel);
            // 如果是解答题
            if (StringUtils.equals(QUESTION_ANSWER, questionExcel.getType())) {
                return;
            }
            // 如果不是解答题
            List<String> options = new ArrayList<>();
            questionExcel.setOptions(options);
            // 空项则废弃
            options.add(questionExcel.getOption());
        } else {
            // 如果选项不为空
            questionExcels.get(questionExcels.size() - 1).getOptions().add(questionExcel.getOption());
        }
        if (questionExcels.size() >= MAX_QUESTIONS) {
            readList(questionExcels);
            questionExcels.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        readList(questionExcels);
        questionExcels.clear();
    }

    /**
     * 读取列表
     *
     * @param questionExcels
     */
    public abstract void readList(List<QuestionExcel> questionExcels);

}
