package cn.com.qmth.examcloud.core.questions.service.export;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExamPaper;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExtractConfig;
import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetail;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailUnit;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuesOption;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.Block;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.ComputerTestOption;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.ComputerTestPaper;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.ComputerTestPaperDetail;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.ComputerTestQuestion;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.Section;
import cn.com.qmth.examcloud.core.questions.dao.entity.computerTestModel.Sections;
import cn.com.qmth.examcloud.core.questions.service.PaperDetailService;
import cn.com.qmth.examcloud.core.questions.service.PaperService;

/**
 * @author chenken
 * @date 2017年10月24日 下午2:29:09
 * @company QMTH
 * @description 构建机考数据包服务
 */
@Service("buildComputerTestJsonService")
public class BuildComputerTestJsonService {

    @Autowired
    private PaperService paperService;

    @Autowired
    private PaperDetailService paperDetailService;

    /**
     * 根据调卷规则构建机考数据包实体类
     *
     * @param extractConfig
     * @return
     */
    public List<ComputerTestPaper> buildComputerTestPapers(ExtractConfig extractConfig) {
        List<ExamPaper> examPapers = extractConfig.getExamPaperList();
        List<ComputerTestPaper> computerTestPapers = new ArrayList<ComputerTestPaper>();
        //循环得到试卷
        for (ExamPaper examPaper : examPapers) {
            Paper paper = examPaper.getPaper();
            //得到所有旧对象的大题对象
            List<PaperDetail> paperDetails = paperService.findPaperDetailsById(paper.getId());
            //通过 paper 对象 ，生成新的  ComputerTestPaper 对象
            ComputerTestPaper computerTestPaper = new ComputerTestPaper(paper, examPaper.getGroupCode());
            List<ComputerTestPaperDetail> details = new ArrayList<ComputerTestPaperDetail>();
            //遍历所有旧大题对象，得到小题对象的集合
            for (PaperDetail paperDetail : paperDetails) {
                List<PaperDetailUnit> paperDetailUnits = paperDetailService.getUnitsByPaperDetailId(paperDetail.getId());
                ComputerTestPaperDetail computerTestPaperDetail = new ComputerTestPaperDetail(paperDetail);
                List<ComputerTestQuestion> questions = new ArrayList<ComputerTestQuestion>();
                //遍历所有的小题对象
                for (int i = 0; i < paperDetailUnits.size(); i++) {
                    PaperDetailUnit paperDetailUnit = paperDetailUnits.get(i);
                    //根据旧的小题对象，生成新的小题对象
                    ComputerTestQuestion computerTestQuestion = new ComputerTestQuestion(paperDetailUnit);
                    //设置小题题号
                    computerTestQuestion.setNumber(i + 1);
                    //得到小题题干
                    computerTestQuestion.setBody(getBody(paperDetailUnit.getQuestion(), paperDetailUnit));
                    //得到小题所有选项
                    computerTestQuestion.setOptions(getOption(paperDetailUnit.getQuestion(), paperDetailUnit));
                    //查询小题中的 套题
                    List<Question> subQuestionsList = paperDetailUnit.getQuestion().getSubQuestions();
                    //判断这个小题中是否有套题
                    if (subQuestionsList != null && subQuestionsList.size() > 0) {
                        List<ComputerTestQuestion> subQuestions = new ArrayList<ComputerTestQuestion>();
                        //遍历每个套题
                        for (int j = 0; j < subQuestionsList.size(); j++) {
                            Question subQuestion = subQuestionsList.get(j);
                            ComputerTestQuestion subcomputerTestQuestion = new ComputerTestQuestion(subQuestion);
                            //设置套题中小题题号
                            subcomputerTestQuestion.setNumber(j + 1);
                            subcomputerTestQuestion.setBody(getBody(subQuestion, null));
                            subcomputerTestQuestion.setOptions(getOption(subQuestion, null));
                            subQuestions.add(subcomputerTestQuestion);
                        }
                        computerTestQuestion.setSubQuestions(subQuestions);
                    }
                    questions.add(computerTestQuestion);
                }
                computerTestPaperDetail.setQuestions(questions);
                //paperDetail中的题数(unitCount)可能不准确，这里以questions的实际size为准
                computerTestPaperDetail.setQuestionCount(questions.size());
                details.add(computerTestPaperDetail);
            }
            computerTestPaper.setDetails(details);
            computerTestPapers.add(computerTestPaper);
        }
        return computerTestPapers;
    }

    private Sections getBody(Question question, PaperDetailUnit paperDetailUnit) {
        Sections body = new Sections();
        List<Section> sections = new ArrayList<Section>();
        //得到小题题干
        String questionBodyString = question.getQuesBody();
        //得到小题题干行数
        String[] questionRowStrings = questionBodyString.split("</p>");
        for (int i = 0; i < questionRowStrings.length; i++) {
            Section section = new Section();
            //将小题题干拆分为Block集合
            section.setBlocks(disposeQuestionBodyOrOption(questionRowStrings[i], paperDetailUnit));
            sections.add(section);
        }
        body.setSections(sections);
        return body;
    }

    private List<ComputerTestOption> getOption(Question question, PaperDetailUnit paperDetailUnit) {
        //得到小题选项
        List<QuesOption> quesOptions = question.getQuesOptions();
        List<ComputerTestOption> options = new ArrayList<ComputerTestOption>();
        //遍历小题选项
        if (quesOptions != null && quesOptions.size() > 0) {
            for (QuesOption quesOption : quesOptions) {
                ComputerTestOption option = new ComputerTestOption();
                option.setNumber(new Integer(quesOption.getNumber()));
                option.setCorrect(quesOption.getIsCorrect() == 1 ? true : false);
                Sections body = new Sections();

                List<Section> sections = new ArrayList<Section>();
                //得到小题选项
                String optionString = quesOption.getOptionBody();
                String[] optionStrings = optionString.split("</p>");
                for (int i = 0; i < optionStrings.length; i++) {
                    Section section = new Section();
                    section.setBlocks(disposeQuestionBodyOrOption(optionStrings[i], paperDetailUnit));
                    sections.add(section);
                }
                body.setSections(sections);
                option.setBody(body);
                options.add(option);
            }
        }
        return options;
    }

    private List<Block> disposeQuestionBodyOrOption(String questionRow, PaperDetailUnit paperDetailUnit) {
        List<Block> blocks = new ArrayList<Block>();
        //去掉每行里面的<p>,<span>,</span>标签
        questionRow = questionRow.replaceAll("<p>", "")
                .replaceAll("</p>", "")
                .replaceAll("<span>", "")
                .replaceAll("</span>", "")
                .replaceAll("</a>", "");
        String[] questionRowStrings = questionRow.split("<|/>|>");
        for (int i = 0; i < questionRowStrings.length; i++) {
            Block block = new Block();
            //判断是否有图片
            if (questionRowStrings[i].startsWith("img")) {
                questionRowStrings[i] = "<" + questionRowStrings[i] + ">";
                Map<String, Object> param = new HashMap<>();
                //需要继续做截取，取到Parma
                block.setType("image");
                //获取图片的路径
                List<String> strSrcList = getImg(questionRowStrings[i], "src");
                if (strSrcList.size() > 0) {
                    String strSrc = strSrcList.get(0).replaceAll("src=\"", "").replaceAll("\"", "");
                    block.setValue(strSrc);
                }
                //获取图片的高度
                List<String> strHeightList = getImg(questionRowStrings[i], "height");
                if (strHeightList.size() > 0) {
                    String strHeight = strHeightList.get(0).replaceAll("height=\"", "").replaceAll("\"", "");
                    param.put("height", strHeight);
                }
                //获取图片的宽度
                List<String> strWidthList = getImg(questionRowStrings[i], "width");
                if (strHeightList.size() > 0) {
                    String strWidth = strWidthList.get(0).replaceAll("width=\"", "").replaceAll("\"", "");
                    param.put("width", strWidth);
                }
                block.setParam(param);
                blocks.add(block);
            } else if (questionRowStrings[i].startsWith("a")
                    && questionRowStrings[i].contains("id")
                    && questionRowStrings[i].contains("name")) {    //处理音频
                questionRowStrings[i] = "<" + questionRowStrings[i] + ">";
				/*if(paperDetailUnit == null){
					block.setPlayTime(-1);
				}else {
					List<AudioTimeConfig> audioTimeConfigs = audioTimeConfigRepo.findByPaperDetailUnit(paperDetailUnit);
					if(audioTimeConfigs != null && audioTimeConfigs.size()>0){
						if(audioTimeConfigs.get(0).getPlayTime() == null){
							block.setPlayTime(-1);
						}else {
							block.setPlayTime(audioTimeConfigs.get(0).getPlayTime());
						}
					}else {
						block.setPlayTime(-1);
					}
				}*/
                block.setType("audio");
                block.setValue(CommonUtils.getAttrValue(questionRowStrings[i], "id"));
                blocks.add(block);
            } else {
                block.setType("text");
                questionRowStrings[i] = questionRowStrings[i].replace("&nbsp;", "");//消除空格
                questionRowStrings[i] = questionRowStrings[i].replace("&quot;", "\"");//将&quot;转换成\"
                questionRowStrings[i] = questionRowStrings[i].replace("&lt;", "<");//将&lt;转换成<
                questionRowStrings[i] = questionRowStrings[i].replace("&gt;", ">");//将&gt;转换成>
                questionRowStrings[i] = questionRowStrings[i].replace("&amp;", "&");//将&amp;转换成&
                if (StringUtils.isNotBlank(questionRowStrings[i])) {
                    block.setValue(questionRowStrings[i]);
                    blocks.add(block);
                }
            }
        }
        return blocks;
    }

    /**
     * 获取图片里面的路径，长度，宽度
     *
     * @param s
     * @param str
     * @return
     */
    private List<String> getImg(String s, String str) {
        String regex;
        List<String> list = new ArrayList<String>();
        regex = str + "=\"(.*?)\"";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(s);
        while (ma.find()) {
            list.add(ma.group());
        }
        return list;
    }
}

