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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;

import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.base.Model;
import cn.com.qmth.examcloud.core.questions.base.converter.utils.FileUtil;
import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
import cn.com.qmth.examcloud.core.questions.dao.QuestionAudioRepo;
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.QuestionAudio;
import cn.com.qmth.examcloud.core.questions.service.ExportThemisPaperService;
import cn.com.qmth.examcloud.core.questions.service.PaperDetailService;
import cn.com.qmth.examcloud.core.questions.service.PaperService;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisAnswer;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisAnswerContent;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisAnswerDetail;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisBlock;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisSubjectiveAnswer;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisOption;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisPaper;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisPaperAndAnswer;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisPaperDetail;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisQuestion;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisSection;
import cn.com.qmth.examcloud.core.questions.service.themispaper.ThemisSections;
import cn.com.qmth.examcloud.support.filestorage.FileStorageUtil;

@Service("exportThemisPaperService")
public class ExportThemisPaperServiceImpl implements ExportThemisPaperService {

	private static final Logger LOG = LoggerFactory.getLogger(ExportThemisPaperServiceImpl.class);

	@Autowired
	private PaperService paperService;

	@Autowired
	private PaperDetailService paperDetailService;
	@Autowired
	private QuestionAudioRepo questionAudioRepo;

	@Override
	public void downloadAudio(ThemisPaper pa, String paperDirectory) {
		String attDirectory = paperDirectory + File.separator + "attachment" + File.separator;
		File attDir = new File(attDirectory);
		if (!attDir.exists()) {
			attDir.mkdirs();
		}
		int count = 0;
		// 取到所有大题
		List<ThemisPaperDetail> details = pa.getDetails();
		if (details != null && details.size() > 0) {
			for (ThemisPaperDetail detail : details) {
				// 取到所有小题集合
				List<ThemisQuestion> questions = detail.getQuestions();
				if (questions != null && questions.size() > 0) {
					for (ThemisQuestion question : questions) {
//						int bodyNum = 1;
						// 取到题干
						ThemisSections body = question.getBody();
						List<ThemisSection> sections = body.getSections();
						for (ThemisSection section : sections) {
							List<ThemisBlock> blocks = section.getBlocks();
							if (blocks != null && blocks.size() > 0) {
								for (ThemisBlock block : blocks) {
									if (block.getType().equals("audio")) {
										String val=block.getValue().toString();
										String id = val.substring(0, val.lastIndexOf("."));
										QuestionAudio questionAudio = Model.of(questionAudioRepo.findById(id));
										String audioFileName = questionAudio.getId() + "."
												+ questionAudio.getFileSuffixes();
										File file = new File(attDirectory + audioFileName);
										// 通用存储
										FileStorageUtil.saveUrlAs(FileStorageUtil.realPath(questionAudio.getFileUrl()),
												file);
										count++;
//										bodyNum++;
									}
								}
							}
						}
						// 取到选项
						List<ThemisOption> options = question.getOptions();
						if (options != null && options.size() > 0) {
							for (ThemisOption computerTestOption : options) {
//								int optionNum = 1;
								// 获取选项主体
								ThemisSections optionBody = computerTestOption.getBody();
								List<ThemisSection> optionSections = optionBody.getSections();
								if (optionSections != null && optionSections.size() > 0) {
									for (ThemisSection optionSection : optionSections) {
										List<ThemisBlock> blocks = optionSection.getBlocks();
										if (blocks != null && blocks.size() > 0) {
											for (ThemisBlock block : blocks) {
												if (block.getType().equals("audio")) {
													String val=block.getValue().toString();
													String id = val.substring(0, val.lastIndexOf("."));
													QuestionAudio questionAudio = Model
															.of(questionAudioRepo.findById(id));
													String audioFileName = questionAudio.getId() + "."
															+ questionAudio.getFileSuffixes();
													File file = new File(attDirectory + audioFileName);
													// 通用存储
													FileStorageUtil.saveUrlAs(
															FileStorageUtil.realPath(questionAudio.getFileUrl()), file);
													count++;
//													optionNum++;
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		if (count == 0) {
			FileUtil.deleteFolder(attDirectory);
		}
	}

	@Override
	public void makePaperAnswerToJsonFile(ThemisPaperAndAnswer pa, String jsonDirectoryPath) {
		makeAnswerToJsonFile(pa.getAnswer(), jsonDirectoryPath);
		makePaperToJsonFile(pa.getPaper(), jsonDirectoryPath);
	}

	@SuppressWarnings("deprecation")
	private void makeAnswerToJsonFile(ThemisAnswer pa, String jsonDirectoryPath) {
		// 创建新的JSON文件
		File file = new File(jsonDirectoryPath + File.separator + "answer.json");
		// 将对象转成 json对象
		Gson gson = new Gson();
		String strJSON = gson.toJson(pa);

		strJSON = CommonUtils.replaceUnicodeStr(strJSON);
		// 生成文件流写入JSON文件
		FileOutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(file);
			byte b[] = strJSON.getBytes("UTF-8");
			outputStream.write(b);
			outputStream.flush();
		} catch (FileNotFoundException e) {
			LOG.error(e.getMessage(), e);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(outputStream);
		}
	}

	@SuppressWarnings("deprecation")
	private void makePaperToJsonFile(ThemisPaper pa, String jsonDirectoryPath) {
		// 创建新的JSON文件
		File file = new File(jsonDirectoryPath + File.separator + "paper.json");
		// 将对象转成 json对象
		Gson gson = new Gson();
		String strJSON = gson.toJson(pa);

		strJSON = CommonUtils.replaceUnicodeStr(strJSON);
		// 生成文件流写入JSON文件
		FileOutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(file);
			byte b[] = strJSON.getBytes("UTF-8");
			outputStream.write(b);
			outputStream.flush();
		} catch (FileNotFoundException e) {
			LOG.error(e.getMessage(), e);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(outputStream);
		}
	}

	@Override
	public ThemisPaperAndAnswer buildPaperAndAnswer(Paper paper) {
		// 得到所有旧对象的大题对象
		List<PaperDetail> paperDetails = paperService.findPaperDetailsById(paper.getId());
		// 通过 paper 对象 ，生成新的 ComputerTestPaper 对象
		ThemisPaper computerTestPaper = new ThemisPaper(paper, "");
		ThemisAnswer themisAnswer = new ThemisAnswer();
		List<ThemisPaperDetail> details = new ArrayList<>();
		List<ThemisAnswerDetail> answerdetails = new ArrayList<>();
		// 遍历所有旧大题对象，得到小题对象的集合
		for (PaperDetail paperDetail : paperDetails) {
			List<PaperDetailUnit> paperDetailUnits = paperDetailService.getUnitsByPaperDetailId(paperDetail.getId());
			ThemisPaperDetail computerTestPaperDetail = new ThemisPaperDetail(paperDetail);
			ThemisAnswerDetail answerDetail = new ThemisAnswerDetail(paperDetail);
			List<ThemisQuestion> questions = new ArrayList<>();
			List<ThemisAnswerContent> answers = new ArrayList<>();
			// 遍历所有的小题对象
			for (int i = 0; i < paperDetailUnits.size(); i++) {
				PaperDetailUnit paperDetailUnit = paperDetailUnits.get(i);
				// 根据旧的小题对象，生成新的小题对象
				ThemisQuestion computerTestQuestion = new ThemisQuestion(paperDetailUnit);
				ThemisAnswerContent themisAnswerContent = new ThemisAnswerContent(paperDetailUnit);
				// 设置小题题号
				computerTestQuestion.setNumber(i + 1);
				themisAnswerContent.setNumber(i + 1);
				// 得到小题题干
				if(computerTestQuestion.getStructType()==4) {
					computerTestQuestion.setBody(getFillBlankBody(paperDetailUnit.getQuestion().getQuesBody(), computerTestPaper));
				}else if(computerTestQuestion.getStructType()==6){
					computerTestQuestion.setBody(getNestedBody(paperDetailUnit.getQuestion().getQuesBody(), computerTestPaper));
				}else {
					computerTestQuestion.setBody(getBody(paperDetailUnit.getQuestion().getQuesBody(), computerTestPaper));
				}
				// 得到小题所有选项
				computerTestQuestion.setOptions(getOption(paperDetailUnit.getQuestion(), computerTestPaper));
				// 得到小题的答案
				if (paperDetailUnit.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
						|| paperDetailUnit.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
					themisAnswerContent.setAnswer(getSelectAnswer(paperDetailUnit.getQuestion()));
				} else if (paperDetailUnit.getQuestionType() == QuesStructType.BOOL_ANSWER_QUESTION) {
					themisAnswerContent.setAnswer(getBoolAnswer(paperDetailUnit.getQuestion()));
				} else if (paperDetailUnit.getQuestionType() == QuesStructType.FILL_BLANK_QUESTION) {
					themisAnswerContent.setAnswer(getFillBlankAnswer(paperDetailUnit.getQuestion()));
				} else {
					themisAnswerContent
							.setAnswer(getAnswer(paperDetailUnit.getQuestion().getQuesAnswer(), computerTestPaper));
				}
				// 查询小题中的 套题
				List<Question> subQuestionsList = paperDetailUnit.getQuestion().getSubQuestions();
				// 判断这个小题中是否有套题
				if (subQuestionsList != null && subQuestionsList.size() > 0) {
					List<ThemisQuestion> subQuestions = new ArrayList<>();
					List<ThemisAnswerContent> subAnswers = new ArrayList<>();
					// 遍历每个套题
					for (int j = 0; j < subQuestionsList.size(); j++) {
						Question subQuestion = subQuestionsList.get(j);
						ThemisQuestion subcomputerTestQuestion = new ThemisQuestion(subQuestion);
						ThemisAnswerContent subthemisAnswerContent = new ThemisAnswerContent(subQuestion);
						// 设置套题中小题题号
						subcomputerTestQuestion.setNumber(j + 1);
						subthemisAnswerContent.setNumber(j + 1);
						
						if(subcomputerTestQuestion.getStructType()==4) {
							subcomputerTestQuestion.setBody(getFillBlankBody(subQuestion.getQuesBody(), computerTestPaper));
						}else if(computerTestQuestion.getStructType()==6){
							subcomputerTestQuestion.setBody(getNestedBody(subQuestion.getQuesBody(), computerTestPaper));
						}else {
							subcomputerTestQuestion.setBody(getBody(subQuestion.getQuesBody(), computerTestPaper));
						}
						subcomputerTestQuestion.setOptions(getOption(subQuestion, computerTestPaper));
						if (subQuestion.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
								|| subQuestion.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
							subthemisAnswerContent.setAnswer(getSelectAnswer(subQuestion));
						} else if (subQuestion.getQuestionType() == QuesStructType.BOOL_ANSWER_QUESTION) {
							subthemisAnswerContent.setAnswer(getBoolAnswer(subQuestion));
						} else if (subQuestion.getQuestionType() == QuesStructType.FILL_BLANK_QUESTION) {
							subthemisAnswerContent.setAnswer(getFillBlankAnswer(subQuestion));
						} else {
							subthemisAnswerContent.setAnswer(getAnswer(subQuestion.getQuesAnswer(), computerTestPaper));
						}
						subQuestions.add(subcomputerTestQuestion);
						subAnswers.add(subthemisAnswerContent);
					}
					computerTestQuestion.setSubQuestions(subQuestions);
					themisAnswerContent.setSubQuestions(subAnswers);
				}
				questions.add(computerTestQuestion);
				answers.add(themisAnswerContent);
			}
			computerTestPaperDetail.setQuestions(questions);
			answerDetail.setQuestions(answers);
			// paperDetail中的题数(unitCount)可能不准确，这里以questions的实际size为准
			computerTestPaperDetail.setQuestionCount(questions.size());
			details.add(computerTestPaperDetail);
			answerdetails.add(answerDetail);
		}
		computerTestPaper.setDetails(details);
		themisAnswer.setDetails(answerdetails);

		ThemisPaperAndAnswer ret = new ThemisPaperAndAnswer();
		computerTestPaper.setId(null);
		ret.setPaper(computerTestPaper);
		ret.setAnswer(themisAnswer);
		return ret;
	}
	private ThemisSections getBody(String str, ThemisPaper computerTestPaper) {
		ThemisSections body = new ThemisSections();
		List<ThemisSection> sections = new ArrayList<>();
		// 得到小题题干或者答案行数
		if (StringUtils.isBlank(str)) {
			return body;
		}
		String[] questionRowStrings = str.split("</p>");
		for (int i = 0; i < questionRowStrings.length; i++) {
			List<ThemisBlock> blocks = disposeQuestionBodyOrOption(questionRowStrings[i], computerTestPaper);
			if (blocks != null && blocks.size() > 0) {
				ThemisSection section = new ThemisSection();
				// 将小题题干拆分为Block集合
				section.setBlocks(blocks);
				sections.add(section);
			}
		}
		body.setSections(sections);
		return body;
	}
	private ThemisSections getFillBlankBody(String str, ThemisPaper computerTestPaper) {
		ThemisSections body = new ThemisSections();
		List<ThemisSection> sections = new ArrayList<>();
		// 得到小题题干或者答案行数
		if (StringUtils.isBlank(str)) {
			return body;
		}
		String[] questionRowStrings = str.split("</p>");
		for (int i = 0; i < questionRowStrings.length; i++) {
			List<ThemisBlock> blocks = disposeFillBlankQuestionBody(questionRowStrings[i], computerTestPaper);
			if (blocks != null && blocks.size() > 0) {
				ThemisSection section = new ThemisSection();
				// 将小题题干拆分为Block集合
				section.setBlocks(blocks);
				sections.add(section);
			}
		}
		body.setSections(sections);
		return body;
	}
	
	private List<ThemisSubjectiveAnswer> getAnswer(String str, ThemisPaper computerTestPaper) {
		List<ThemisSection> sections = new ArrayList<>();
		// 得到小题题干或者答案行数
		if (StringUtils.isBlank(str)) {
			return null;
		}
		String[] questionRowStrings = str.split("</p>");
		for (int i = 0; i < questionRowStrings.length; i++) {
			List<ThemisBlock> blocks = disposeQuestionBodyOrOption(questionRowStrings[i], computerTestPaper);
			if (blocks != null && blocks.size() > 0) {
				ThemisSection section = new ThemisSection();
				// 将小题题干拆分为Block集合
				section.setBlocks(blocks);
				sections.add(section);
			}
		}
		List<ThemisSubjectiveAnswer> ans=new ArrayList<>();
		ThemisSubjectiveAnswer an=new ThemisSubjectiveAnswer();
		ans.add(an);
		an.setIndex(1);
		an.setSections(sections);
		return ans;
	}
	private String changeCloze(String text) {
		StringBuffer buffer = new StringBuffer();
        String regex = "##(\\d)##";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        // 使用find()方法查找匹配项
        while (matcher.find()) {
        	matcher.appendReplacement(buffer, "__"+matcher.group(1)+"__");
        }
        return buffer.toString();
	}
	private ThemisSections getNestedBody(String str, ThemisPaper computerTestPaper) {
		ThemisSections body = new ThemisSections();
		List<ThemisSection> sections = new ArrayList<>();
		// 得到小题题干或者答案行数
		if (StringUtils.isBlank(str)) {
			return body;
		}
		String[] questionRowStrings = str.split("</p>");
		for (int i = 0; i < questionRowStrings.length; i++) {
			List<ThemisBlock> blocks = disposeNestedQuestionBody(questionRowStrings[i], computerTestPaper);
			if (blocks != null && blocks.size() > 0) {
				ThemisSection section = new ThemisSection();
				// 将小题题干拆分为Block集合
				section.setBlocks(blocks);
				sections.add(section);
			}
		}
		body.setSections(sections);
		return body;
	}
	private List<ThemisBlock> disposeNestedQuestionBody(String questionRow, ThemisPaper computerTestPaper) {
		List<ThemisBlock> blocks = new ArrayList<>();
		// 去掉每行里面的<p>,<span>,</span>标签
		questionRow = questionRow.replaceAll("<p>", "").replaceAll("</p>", "").replaceAll("<span>", "")
				.replaceAll("</span>", "").replaceAll("</a>", "");
		String[] questionRowStrings = questionRow.split("<|/>|>");
		boolean hasAudio = false;
		for (int i = 0; i < questionRowStrings.length; i++) {
			ThemisBlock block = new ThemisBlock();
			String rowStr = questionRowStrings[i];
			// 判断是否有图片
			if (rowStr.startsWith("img")) {
				rowStr = "<" + rowStr + ">";
				Map<String, Object> param = new HashMap<>();
				// 需要继续做截取，取到Parma
				block.setType("image");
				// 获取图片的路径
				List<String> strSrcList = getImg(rowStr, "src");
				if (strSrcList.size() > 0) {
					String strSrc = strSrcList.get(0).replaceAll("src=\"", "").replaceAll("\"", "");
					block.setValue(strSrc);
				}
				// 获取图片的高度
				List<String> strHeightList = getImg(rowStr, "height");
				if (strHeightList.size() > 0) {
					String strHeight = strHeightList.get(0).replaceAll("height=\"", "").replaceAll("\"", "");
					param.put("height", strHeight);
				}
				// 获取图片的宽度
				List<String> strWidthList = getImg(rowStr, "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 (rowStr.startsWith("a") && rowStr.contains("id") && rowStr.contains("name")) { // 处理音频
				rowStr = "<" + rowStr + ">";
				block.setType("audio");
				String id=CommonUtils.getAttrValue(rowStr, "id");
				QuestionAudio questionAudio = Model.of(questionAudioRepo.findById(id));
				block.setValue(questionAudio.getId() + "."+ questionAudio.getFileSuffixes());
				blocks.add(block);
				hasAudio = true;
			} else {
				block.setType("text");
				rowStr = rowStr.replace("&nbsp;", "");// 消除空格
				rowStr = rowStr.replace("&quot;", "\"");// 将&quot;转换成\"
				rowStr = rowStr.replace("&lt;", "<");// 将&lt;转换成<
				rowStr = rowStr.replace("&gt;", ">");// 将&gt;转换成>
				rowStr = rowStr.replace("&amp;", "&");// 将&amp;转换成&
				if (StringUtils.isNotBlank(rowStr)) {
					block.setValue(changeCloze(rowStr));
					blocks.add(block);
				}
			}
		}
		if (hasAudio) {
			computerTestPaper.setHasAudio(hasAudio);
		}
		return blocks;
	}
	
	private List<ThemisBlock> disposeFillBlankQuestionBody(String questionRow, ThemisPaper computerTestPaper) {
		List<ThemisBlock> blocks = new ArrayList<>();
		// 去掉每行里面的<p>,<span>,</span>标签
		questionRow = questionRow.replaceAll("<p>", "").replaceAll("</p>", "").replaceAll("<span>", "")
				.replaceAll("</span>", "").replaceAll("</a>", "");
		String[] questionRowStrings = questionRow.split("<|/>|>");
		boolean hasAudio = false;
		int blankIndex=0;
		for (int i = 0; i < questionRowStrings.length; i++) {
			ThemisBlock block = new ThemisBlock();
			String rowStr = questionRowStrings[i];
			// 判断是否有图片
			if (rowStr.startsWith("img")) {
				rowStr = "<" + rowStr + ">";
				Map<String, Object> param = new HashMap<>();
				// 需要继续做截取，取到Parma
				block.setType("image");
				// 获取图片的路径
				List<String> strSrcList = getImg(rowStr, "src");
				if (strSrcList.size() > 0) {
					String strSrc = strSrcList.get(0).replaceAll("src=\"", "").replaceAll("\"", "");
					block.setValue(strSrc);
				}
				// 获取图片的高度
				List<String> strHeightList = getImg(rowStr, "height");
				if (strHeightList.size() > 0) {
					String strHeight = strHeightList.get(0).replaceAll("height=\"", "").replaceAll("\"", "");
					param.put("height", strHeight);
				}
				// 获取图片的宽度
				List<String> strWidthList = getImg(rowStr, "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 (rowStr.startsWith("a") && rowStr.contains("id") && rowStr.contains("name")) { // 处理音频
				rowStr = "<" + rowStr + ">";
				block.setType("audio");
				String id=CommonUtils.getAttrValue(rowStr, "id");
				QuestionAudio questionAudio = Model.of(questionAudioRepo.findById(id));
				block.setValue(questionAudio.getId() + "."+ questionAudio.getFileSuffixes());
				blocks.add(block);
				hasAudio = true;
			} else {
				rowStr = rowStr.replace("&nbsp;", "");// 消除空格
				rowStr = rowStr.replace("&quot;", "\"");// 将&quot;转换成\"
				rowStr = rowStr.replace("&lt;", "<");// 将&lt;转换成<
				rowStr = rowStr.replace("&gt;", ">");// 将&gt;转换成>
				rowStr = rowStr.replace("&amp;", "&");// 将&amp;转换成&
		        
				String regex = "###";

		        Pattern pattern = Pattern.compile(regex);
		        Matcher matcher = pattern.matcher(rowStr);
		        int indexStart=0;
		        // 使用find()方法查找匹配项
		        while (matcher.find()) {
		        	blankIndex++;
		            String content=rowStr.substring(indexStart, matcher.start());
		            if(StringUtils.isNotEmpty(content)) {
		            	ThemisBlock temblock = new ThemisBlock();
			            temblock.setType("text");
			            temblock.setValue(content);
						blocks.add(temblock);
		            }
		            ThemisBlock blankblock = new ThemisBlock();
		            blankblock.setType("cloze");
		            blankblock.setValue(blankIndex);
		            blocks.add(blankblock);
		            indexStart=matcher.start()+regex.length();
		        }
		        if(indexStart<rowStr.length()) {
		        	// 输出最后一个分隔符之后的字符串
			        String content=rowStr.substring(indexStart, rowStr.length());
		            if(StringUtils.isNotEmpty(content)) {
		            	ThemisBlock temblock = new ThemisBlock();
			            temblock.setType("text");
			            temblock.setValue(content);
						blocks.add(temblock);
		            }
		        }
			}
		}
		if (hasAudio) {
			computerTestPaper.setHasAudio(hasAudio);
		}
		return blocks;
	}
	

	private List<ThemisBlock> disposeQuestionBodyOrOption(String questionRow, ThemisPaper computerTestPaper) {
		List<ThemisBlock> blocks = new ArrayList<>();
		// 去掉每行里面的<p>,<span>,</span>标签
		questionRow = questionRow.replaceAll("<p>", "").replaceAll("</p>", "").replaceAll("<span>", "")
				.replaceAll("</span>", "").replaceAll("</a>", "");
		String[] questionRowStrings = questionRow.split("<|/>|>");
		boolean hasAudio = false;
		for (int i = 0; i < questionRowStrings.length; i++) {
			ThemisBlock block = new ThemisBlock();
			String rowStr = questionRowStrings[i];
			// 判断是否有图片
			if (rowStr.startsWith("img")) {
				rowStr = "<" + rowStr + ">";
				Map<String, Object> param = new HashMap<>();
				// 需要继续做截取，取到Parma
				block.setType("image");
				// 获取图片的路径
				List<String> strSrcList = getImg(rowStr, "src");
				if (strSrcList.size() > 0) {
					String strSrc = strSrcList.get(0).replaceAll("src=\"", "").replaceAll("\"", "");
					block.setValue(strSrc);
				}
				// 获取图片的高度
				List<String> strHeightList = getImg(rowStr, "height");
				if (strHeightList.size() > 0) {
					String strHeight = strHeightList.get(0).replaceAll("height=\"", "").replaceAll("\"", "");
					param.put("height", strHeight);
				}
				// 获取图片的宽度
				List<String> strWidthList = getImg(rowStr, "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 (rowStr.startsWith("a") && rowStr.contains("id") && rowStr.contains("name")) { // 处理音频
				rowStr = "<" + rowStr + ">";
				block.setType("audio");
				String id=CommonUtils.getAttrValue(rowStr, "id");
				QuestionAudio questionAudio = Model.of(questionAudioRepo.findById(id));
				block.setValue(questionAudio.getId() + "."+ questionAudio.getFileSuffixes());
				blocks.add(block);
				hasAudio = true;
			} else {
				block.setType("text");
				rowStr = rowStr.replace("&nbsp;", "");// 消除空格
				rowStr = rowStr.replace("&quot;", "\"");// 将&quot;转换成\"
				rowStr = rowStr.replace("&lt;", "<");// 将&lt;转换成<
				rowStr = rowStr.replace("&gt;", ">");// 将&gt;转换成>
				rowStr = rowStr.replace("&amp;", "&");// 将&amp;转换成&
				if (StringUtils.isNotBlank(rowStr)) {
					block.setValue(rowStr);
					blocks.add(block);
				}
			}
		}
		if (hasAudio) {
			computerTestPaper.setHasAudio(hasAudio);
		}
		return blocks;
	}

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

	private List<ThemisOption> getOption(Question question, ThemisPaper computerTestPaper) {
		// 得到小题选项
		List<QuesOption> quesOptions = question.getQuesOptions();
		List<ThemisOption> options = new ArrayList<>();
		// 遍历小题选项
		if (quesOptions != null && quesOptions.size() > 0) {
			for (QuesOption quesOption : quesOptions) {
				ThemisOption option = new ThemisOption();
				option.setNumber(new Integer(quesOption.getNumber()));
				ThemisSections body = new ThemisSections();

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

	private JsonArray getSelectAnswer(Question question) {
		// 得到小题选项
		List<QuesOption> quesOptions = question.getQuesOptions();
		int index = 0;
		// 遍历小题选项
		if (quesOptions != null && quesOptions.size() > 0) {
			JsonArray ja = new JsonArray();
			for (QuesOption quesOption : quesOptions) {
				index++;
				if (quesOption.getIsCorrect() == 1) {
					ja.add(index);
				}
			}
			if (ja.size() > 0) {
				return ja;
			} else {
				return null;
			}
		}
		return null;
	}

	private Boolean getBoolAnswer(Question question) {
		String as = question.getQuesAnswer();
		if (StringUtils.isBlank(as)) {
			return null;
		}
		if (as.contains("正确")) {
			return true;
		} else {
			return false;
		}
	}

	private void getSectionElement(Node ce, StringBuilder sb) {
		if (("span".equals(ce.nodeName()) || "p".equals(ce.nodeName())) && ce.childNodeSize() > 0) {
			for (Node e : ce.childNodes()) {
				getSectionElement(e, sb);
			}
		} else {
			if (ce instanceof TextNode) {
				TextNode tn = (TextNode) ce;
				String text = tn.text();
				sb.append(text);
			} else if (ce instanceof Element) {
				if ("img".equals(ce.nodeName())) {
					Element el = (Element) ce;
					sb.append(el.outerHtml());
				} else {
					Element el = (Element) ce;
					sb.append(el.text());
				}
			}
		}
	}

	private List<ThemisSubjectiveAnswer> getFillBlankAnswer(Question question) {
		String html = question.getQuesAnswer();
		if (StringUtils.isBlank(html)) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		Document doc = Jsoup.parse(html);
		Element b = doc.body();
		for (Node ce : b.childNodes()) {
			getSectionElement(ce, sb);
		}

		if (StringUtils.isBlank(sb.toString())) {
			return null;
		}
		List<ThemisSubjectiveAnswer> tas = new ArrayList<>();
		String[] sbs = sb.toString().split("##");
		int index = 0;
		for (String an : sbs) {
			index++;
			ThemisSubjectiveAnswer ta = new ThemisSubjectiveAnswer();
			ta.setIndex(index);
			List<ThemisSection> sections = new ArrayList<>();
			ThemisSection sec = new ThemisSection();
			List<ThemisBlock> blocks = new ArrayList<>();
			Document subdoc = Jsoup.parse(an);
			for (Node ce : subdoc.body().childNodes()) {
				ThemisBlock block = new ThemisBlock();
				if (ce instanceof TextNode) {
					TextNode tn = (TextNode) ce;
					String text = tn.text();
					block.setType("text");
					block.setValue(text);
				} else if (ce instanceof Element) {
					if ("img".equals(ce.nodeName())) {
						Element el = (Element) ce;
						block.setType("image");
						block.setValue(el.attr("src"));
						String h = el.attr("height");
						String w = el.attr("width");
						if (StringUtils.isNotBlank(w) && StringUtils.isNotBlank(h)) {
							Map<String, Object> param = new HashMap<String, Object>();
							param.put("height", h);
							param.put("width", w);
							block.setParam(param);
						}
					} else {
						Element el = (Element) ce;
						block.setType("text");
						block.setValue(el.text());
					}
				}
				blocks.add(block);
			}
			sec.setBlocks(blocks);
			sections.add(sec);
			ta.setSections(sections);
			tas.add(ta);
		}
		return tas;
	}
}