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

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.base.converter.utils.FileUtil;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperStatus;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
import cn.com.qmth.examcloud.core.questions.dao.PaperDetailRepo;
import cn.com.qmth.examcloud.core.questions.dao.PaperDetailUnitRepo;
import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
import cn.com.qmth.examcloud.core.questions.dao.QuesRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.Course;
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.service.QuesTypeNameService;
import cn.com.qmth.examcloud.core.questions.service.impl.CourseService;
import cn.com.qmth.examcloud.web.config.SystemProperties;

@Component
public class CqdxService {
	private static final Logger log = LoggerFactory.getLogger(CqdxService.class);
//	final Long rootOrgId = 1407L;
//	final String rootDir = "D:/paper/cqu/temps";
	@Autowired
	private CourseService courseService;
	@Autowired
	private QuesRepo quesRepo;
	@Autowired
	private PaperRepo paperRepo;
	@Autowired
	private PaperDetailRepo paperDetailRepo;
	@Autowired
	private PaperDetailUnitRepo paperDetailUnitRepo;
//	@Autowired
//	private QuesPkgPathRepo quesPkgPathRepo;
	@Autowired
	private QuesTypeNameService quesTypeNameService;
	@Autowired
	private SystemProperties systemProperties;

	public void bulidPaper(MultipartFile dataFile, User user, Long rootOrgId, String paperNameSuffix, String impType) {
		String tempDir = systemProperties.getTempDataDir();
		String dir = tempDir + File.separator + UUID.randomUUID() + File.separator;
		try {
			File dfile = new File(dir);
			dfile.mkdirs();
			File zfile = new File(dir + dataFile.getOriginalFilename());
			zfile.createNewFile();
			dataFile.transferTo(zfile);
			Map<Object, Object> paperInfoMap = this.readXml(zfile.getAbsolutePath(), paperNameSuffix, impType);
			// 查询课程
			Course course = courseService.getCourse(rootOrgId, paperInfoMap.get("courseCode").toString());
			// 初始化试卷
			Paper paper = initPaper(paperInfoMap, course, user);
			// 大题集合
			List<PaperDetail> paperDetails = initPaperDetails(paperInfoMap, paper, user);
			// 试题---资源 对应关系
			List<Question> questionLists = new ArrayList<>();

			// 定义小题集合
			List<PaperDetailUnit> paperDetailUnits;
			paperDetailUnits = initpaperDetailUnits(paper, paperDetails, questionLists, paperInfoMap, course, user);
			if (paperDetailUnits == null) {
				throw new StatusException("100001", "有错误的XML");
			}

			// 保存试题资源
//			quesPkgPathRepo.saveAll(questionMaps.values());
//			for (Map.Entry<Question, QuestionPkgPath> entry : questionMaps.entrySet()) {
//				entry.getKey().setQuesPkgPathId(entry.getValue().getId());
//			}
			quesRepo.saveAll(questionLists);
			paperRepo.save(paper);
			paperDetailRepo.saveAll(paperDetails);
			paperDetailUnitRepo.saveAll(paperDetailUnits);
			if (paperDetailUnits.size() > 0) {
				quesTypeNameService.saveQuesTypeName(paperDetailUnits);
			}
		} catch (StatusException e) {
			throw e;
		} catch (Exception e) {
			throw new StatusException("100002", "导入试卷失败:" + e.getMessage(), e);
		} finally {
			FileUtil.deleteFolder(dir);
		}
	}

	public void bulidPaper() throws Exception {
		// 获取所有xml的路径
//		List<String> files = this.loadFiles();

		// 试卷名称(后缀)
//		final String paperNameSuffix = "192";

//		int i = 0;
//		log.debug("XML的文件数：" + files.size());
//		for (String filePath : files) {
//			log.debug("第" + (++i) + "个xml文件开始处理,文件名为：" + filePath);

//            if (i < 30) {
//                continue;
//            }

//			Map<Object, Object> paperInfoMap = this.readXml(filePath, paperNameSuffix);
//			// 查询课程
//			Course course = courseService.getCourse(rootOrgId, paperInfoMap.get("courseCode").toString());
//			// 初始化试卷
//			Paper paper = initPaper(paperInfoMap, course);
//			// 大题集合
//			List<PaperDetail> paperDetails = initPaperDetails(paperInfoMap, paper);
//			// 试题---资源 对应关系
//			Map<Question, QuestionPkgPath> questionMaps = new HashMap<>();
//
//			// 定义小题集合
//			List<PaperDetailUnit> paperDetailUnits;
//			try {
//				paperDetailUnits = initpaperDetailUnits(paper, paperDetails, questionMaps, paperInfoMap, course);
//				if (paperDetailUnits == null) {
//					log.debug("-->有错误的XML:" + filePath);
//					break;
//				}
//			} catch (Exception e) {
//				log.debug("==>有错误的XML:" + filePath + " Error:" + e.getMessage());
//				break;
//			}
//
//			// 保存试题资源
//			quesPkgPathRepo.saveAll(questionMaps.values());
//			for (Map.Entry<Question, QuestionPkgPath> entry : questionMaps.entrySet()) {
//				entry.getKey().setQuesPkgPathId(entry.getValue().getId());
//			}
//			quesRepo.saveAll(questionMaps.keySet());
//			paperRepo.save(paper);
//			paperDetailRepo.saveAll(paperDetails);
//			paperDetailUnitRepo.saveAll(paperDetailUnits);
//
//			// 将正常文件移动到新目录
//			File okFile = new File(rootDir + "/" + filePath);
//			String newFilePath = rootDir + "/ok/" + okFile.getName();
//			File newFile = new File(newFilePath);
//			okFile.renameTo(newFile);
//
//			log.debug("第" + i + "个xml文件已经处理完,文件名为：" + filePath);
//		}
//		log.debug("处理完成...");
	}

	// 初始化试卷
	private Paper initPaper(Map<Object, Object> paperInfoMap, Course course, User user) {
		Paper paper = new Paper();
		paper.setName((String) paperInfoMap.get("name"));
		paper.setTitle((String) paperInfoMap.get("name"));
		paper.setPaperType(PaperType.IMPORT);
		paper.setPaperStatus(PaperStatus.DRAFT);
		paper.setOrgId(course.getOrgId());
		paper.setCreator(user.getDisplayName());
		paper.setTotalScore(Double.valueOf((String) paperInfoMap.get("totalScore")));
		paper.setCourse(course);
		paper.setCourseName(course.getName());
		paper.setCourseNo(course.getCode());
		paper.setCreateTime(CommonUtils.getCurDateTime());
		paper.setPaperDetailCount(Integer.valueOf((String) paperInfoMap.get("detailCount")));
		paper.setUnitCount(Integer.valueOf((String) paperInfoMap.get("unitCount")));
		paper.setDifficultyDegree(0.5);
		return paper;
	}

	// 初始化大题集合
	private List<PaperDetail> initPaperDetails(Map<Object, Object> paperInfoMap, Paper paper, User user) {
		// 定义大题集合
		List<PaperDetail> paperDetails = new ArrayList<PaperDetail>();
		int length = paperInfoMap.size() - 5;
		for (int i = 0; i < length; i++) {
			QuestionsTemp detailInfo = (QuestionsTemp) paperInfoMap.get(String.valueOf(i + 1));
			PaperDetail paperDetail = new PaperDetail();
			paperDetail.setPaper(paper);
			paperDetail.setNumber(Integer.valueOf(detailInfo.getNumber()));
			paperDetail.setName(detailInfo.getName());
			paperDetail.setScore(Double.valueOf(detailInfo.getTotalScore()));
			paperDetail.setUnitCount(Integer.valueOf(detailInfo.getCount()));
			paperDetail.setCreator(user.getDisplayName());
			paperDetail.setCreateTime(CommonUtils.getCurDateTime());
			paperDetails.add(paperDetail);
		}
		return paperDetails;
	}

	private String transProblemDocumentName(String problemDocumentName, String impType) {
		if ("old".equals(impType)) {
			String s1 = problemDocumentName.substring(0, 1);
			String s2 = problemDocumentName.substring(1);
			if ("A".equals(s1)) {
				return "G"+s2;
			}
			if ("B".equals(s1)) {
				return "H"+s2;
			}
			if ("C".equals(s1)) {
				return "I"+s2;
			}
		}
		return problemDocumentName;
	}

	public Map<Object, Object> readXml(String xmlPath, String paperNameSuffix, String impType) throws Exception {
		Map<Object, Object> paperInfoMap = new HashedMap<>();
		DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
		DocumentBuilder b = a.newDocumentBuilder();

		// “file:///”表示是本地计算机，否则报错“unknown protocol”
		Document document = b.parse("file:///" + xmlPath);
		NodeList exerciseDocuments = document.getElementsByTagName("ExerciseDocument");
		// 遍历exerciseDocument节点
		for (int i = 0; i < exerciseDocuments.getLength(); i++) {
			// 获取第一个exerciseDocument
			Node node = exerciseDocuments.item(i);
			// 获取exerciseDocument节点下的所有属性
			NamedNodeMap namedNodeMap = node.getAttributes();
			// 课程代码
			paperInfoMap.put("courseCode", namedNodeMap.getNamedItem("CourseId").getTextContent());
			// 试卷名称(后缀)
			paperInfoMap.put("name", namedNodeMap.getNamedItem("CourseName").getTextContent() + "(" + paperNameSuffix
					+ ")" + transProblemDocumentName(namedNodeMap.getNamedItem("ProblemDocumentName").getTextContent(),impType));
			// 试卷总分
			paperInfoMap.put("totalScore", namedNodeMap.getNamedItem("Score").getTextContent());
			// 大题数量
			paperInfoMap.put("detailCount", namedNodeMap.getNamedItem("ProblemCollectionCount").getTextContent());
			// 小题数量
			paperInfoMap.put("unitCount", namedNodeMap.getNamedItem("ProblemCount").getTextContent());
			// 获取ProblemCollection所有节点
			NodeList problemList = node.getChildNodes();
			for (int j = 0; j < problemList.getLength(); j++) {
				// 大题节点
				Node detailNode = problemList.item(j);
				if (detailNode.getNodeName().equals("ProblemCollection")) {
					Map<Object, Object> detailInfoMap = new HashedMap<Object, Object>();
					QuestionsTemp detailInfo = new QuestionsTemp();
					// 大题序号
					detailInfo.setNumber(detailNode.getAttributes().getNamedItem("Index").getTextContent());
					// 大题名称
					detailInfo.setName(detailNode.getAttributes().getNamedItem("ProblemTypeName").getTextContent());
					// 大题总分
					detailInfo.setTotalScore(detailNode.getAttributes().getNamedItem("Score").getTextContent());
					// 大题总数
					detailInfo.setCount(detailNode.getAttributes().getNamedItem("ProblemCount").getTextContent());
					// 获取所有Problem节点
					NodeList unitList = detailNode.getChildNodes();
					for (int k = 0; k < unitList.getLength(); k++) {
						Node unitNode = unitList.item(k);
						if (unitNode.getNodeName().equals("Problem")) {
							QuestionsTemp unitInfo = new QuestionsTemp();
							// 小题分数
							unitInfo.setScore(unitNode.getAttributes().getNamedItem("Score").getTextContent());
							// 小题序号
							unitInfo.setNumber(unitNode.getAttributes().getNamedItem("Index").getTextContent());
							// 小题题型
							String type = unitNode.getAttributes().getNamedItem("ProblemClassType").getTextContent();
							// 获取题目文本节点
							NodeList unitInfoList = unitNode.getChildNodes();
							for (int z = 0; z < unitInfoList.getLength(); z++) {
								Node unitInfoNode = unitInfoList.item(z);
								if (unitInfoNode.getNodeName().equals("Content")) {
									// 小题题干
									unitInfo.setBody(unitInfoNode.getTextContent());
								}
								// 选择题
								if (unitInfoNode.getNodeName().equals("ChoiceItem")) {
									NodeList optionsInfoList = unitInfoNode.getChildNodes();
									String answer = "";
									if (type.equals("MonomialChoice")) {
										unitInfo.setType(QuesStructType.SINGLE_ANSWER_QUESTION);
									}
									if (type.equals("MultipleChoice")) {
										unitInfo.setType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
									}
									Map<Object, Object> options = new HashedMap<Object, Object>();
									for (int u = 0; u < optionsInfoList.getLength(); u++) {
										Node optionsInfoNode = optionsInfoList.item(u);
										if (optionsInfoNode.getNodeName().equals("Options")) {
											// 所有选项节点
											NodeList optionInfoList = optionsInfoNode.getChildNodes();
											for (int r = 0; r < optionInfoList.getLength(); r++) {
												Node optionInfoNode = optionInfoList.item(r);
												if (optionInfoNode.getNodeName().equals("Option")) {
													// 选项序号,内容
													options.put(optionInfoNode.getAttributes().getNamedItem("Index")
															.getTextContent(), optionInfoNode.getTextContent());
													if (optionInfoNode.getAttributes().getNamedItem("Selected")
															.getTextContent().equals("True")) {
														if (StringUtils.isBlank(answer)) {
															answer = optionInfoNode.getAttributes()
																	.getNamedItem("Index").getTextContent();
														} else {
															answer = answer + "," + optionInfoNode.getAttributes()
																	.getNamedItem("Index").getTextContent();
														}
													}
												}
											}
											// 小题选项
											unitInfo.setOptions(options);
											unitInfo.setAnswer(answer);
										}
									}
								}
								// 完形填空,单选类的阅读理解
								if (unitInfoNode.getNodeName().equals("ChoiceItems")) {
									unitInfo.setType(QuesStructType.NESTED_ANSWER_QUESTION);
									Map<Object, Object> subQues = new HashedMap<Object, Object>();
									Map<Object, Object> subOptions = new HashedMap<Object, Object>();
									NodeList choiceItemsList = unitInfoNode.getChildNodes();
									int number = 1;
									for (int h = 0; h < choiceItemsList.getLength(); h++) {
										Node subUnitInfoNode = choiceItemsList.item(h);
										String answer = "";
										if (subUnitInfoNode.getNodeName().equals("ChoiceItem")) {
											// 每一个子题选项
											QuestionsTemp subUnit = new QuestionsTemp();
											NodeList subOptionsInfoList = subUnitInfoNode.getChildNodes();
											for (int hu = 0; hu < subOptionsInfoList.getLength(); hu++) {
												Node subOptionsInfoNode = subOptionsInfoList.item(hu);
												if (subOptionsInfoNode.getNodeName().equals("Options")) {
													// 所有选项节点
													NodeList subOptionInfoList = subOptionsInfoNode.getChildNodes();
													for (int hr = 0; hr < subOptionInfoList.getLength(); hr++) {
														Node subOptionInfoNode = subOptionInfoList.item(hr);
														if (subOptionInfoNode.getNodeName().equals("Option")) {
															// 子题选项序号,内容
															subOptions.put(
																	subOptionInfoNode.getAttributes()
																			.getNamedItem("Index").getTextContent(),
																	subOptionInfoNode.getTextContent());
															if (subOptionInfoNode.getAttributes()
																	.getNamedItem("Selected").getTextContent()
																	.equals("True")) {
																if (StringUtils.isBlank(answer)) {
																	answer = subOptionInfoNode.getAttributes()
																			.getNamedItem("Index").getTextContent();
																} else {
																	answer = answer + ","
																			+ subOptionInfoNode.getAttributes()
																					.getNamedItem("Index")
																					.getTextContent();
																}
															}
														}
													}
													// 子题选项
													subUnit.setOptions(subOptions);
													// 子题答案
													subUnit.setAnswer(answer);
													if (answer.contains(",")) {
														subUnit.setType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
													} else {
														subUnit.setType(QuesStructType.SINGLE_ANSWER_QUESTION);
													}
												}
												if (subOptionsInfoNode.getNodeName().equals("Content")) {
													subUnit.setBody(subOptionsInfoNode.getTextContent());
												}
												if (subOptionsInfoNode.getNodeName().equals("Answer")) {
													subUnit.setType(QuesStructType.TEXT_ANSWER_QUESTION);
													subUnit.setAnswer(subOptionsInfoNode.getTextContent());
												}
											}
											if (StringUtils.isBlank(subUnit.getBody())) {
												subUnit.setBody("__________");
											}
											subUnit.setNumber(String.valueOf(number));
											subQues.put(subUnit.getNumber(), subUnit);
											number++;
										}
									}
									unitInfo.setSubQues(subQues);
								}
								// 普通答案
								if (unitInfoNode.getNodeName().equals("Answer")) {
									// 判断题
									if (type.equals("TrueOrFalse")) {
										unitInfo.setType(QuesStructType.BOOL_ANSWER_QUESTION);
										String answerString = unitInfoNode.getTextContent();
										if (answerString.contains("False")) {
											unitInfo.setAnswer("错误");
										} else {
											unitInfo.setAnswer("正确");
										}
									}
									// 主观题
									if (type.equals("EssayQuestion")) {
										unitInfo.setType(QuesStructType.TEXT_ANSWER_QUESTION);
										unitInfo.setAnswer(unitInfoNode.getTextContent());
									}
								}
							}
							// 添加小题到大题
							detailInfoMap.put(unitInfo.getNumber(), unitInfo);
						}
					}
					detailInfo.setQues(detailInfoMap);
					// 添加大题到试卷
					paperInfoMap.put(detailInfo.getNumber(), detailInfo);
				}
			}
		}
		return paperInfoMap;
	}

	// 初始化小题集合
	private List<PaperDetailUnit> initpaperDetailUnits(Paper paper, List<PaperDetail> paperDetails,
			List<Question> questionLists, Map<Object, Object> paperInfoMap, Course course, User user)
			throws Exception {
		List<PaperDetailUnit> paperDetailUnits = new ArrayList<PaperDetailUnit>();
		int detailCount = paperDetails.size();
		int nm = 0;
		for (int i = 0; i < detailCount; i++) {
			PaperDetail detail = paperDetails.get(i);
			QuestionsTemp detailTemp = (QuestionsTemp) paperInfoMap.get(String.valueOf(i + 1));
			Map<Object, Object> detailInfoMap = detailTemp.getQues();
			int quesCount = detailInfoMap.size();
			for (int j = 0; j < quesCount; j++) {
//				WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
				QuestionsTemp quesTemp = (QuestionsTemp) detailInfoMap.get(String.valueOf(j + 1));
				Question question = new Question();
				question.setCreateTime(CommonUtils.getCurDateTime());
				question.setScore(Double.valueOf(quesTemp.getScore()));
				question.setCourse(course);
				question.setOrgId(course.getOrgId());
				question.setHasAudio(false);
				question.setDifficulty("中");
				question.setDifficultyDegree(0.5);
				question.setPublicity(true);
				question.setQuestionType(quesTemp.getType());

				String body = imgList(quesTemp.getBody());
				question.setQuesBody(replaceBlank(body));
				try {
//					question.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesBody())));
				} catch (Exception e) {
					log.error("错误题干信息：" + question.getQuesBody());
					throw new IllegalArgumentException("题干信息错误！"+e.getMessage());
				}
				if (question.getQuestionType() == QuesStructType.BOOL_ANSWER_QUESTION) {
					question.setQuesAnswer(quesTemp.getAnswer());
//					question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml("<p>" + question.getQuesAnswer() + "</p>")));
				} else {
					question.setQuesAnswer(imgList(quesTemp.getAnswer()));
					try {
//						question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(question.getQuesAnswer())));
					} catch (Exception e) {
						log.error("错误答案信息：" + question.getQuesAnswer());
						throw new IllegalArgumentException("答案信息错误！"+e.getMessage());
					}
				}
				// 存在选项
				if (question.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
						|| question.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
					List<QuesOption> quesOptions = new ArrayList<QuesOption>();
					Map<Object, Object> optionMap = quesTemp.getOptions();
					int optionCount = optionMap.size();
					for (int k = 0; k < optionCount; k++) {
						QuesOption quesOption = new QuesOption();
						quesOption.setNumber(String.valueOf(k + 1));

						String optionBody = imgList((String) optionMap.get(String.valueOf(k + 1)));
						if (optionBody.startsWith("<p><p") || optionBody.startsWith("<P><P")) {
							quesOption.setOptionBody(replaceFirstP(optionBody));
						} else {
							quesOption.setOptionBody(optionBody);
						}

						try {
//							quesOption.setOptionBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(quesOption.getOptionBody())));
						} catch (Exception e) {
							log.error("错误的选项：" + quesOption.getOptionBody());
							throw new IllegalArgumentException("选项信息错误！"+e.getMessage());
						}
						if (question.getQuesAnswer().contains(String.valueOf(k + 1))) {
							quesOption.setIsCorrect((short) 1);
						} else {
							quesOption.setIsCorrect((short) 0);
						}
						quesOptions.add(quesOption);
					}
					question.setQuesOptions(quesOptions);
					String[] answers = question.getQuesAnswer().replaceAll("<p>", "").replaceAll("</p>", "")
							.replaceAll("<P>", "").replaceAll("</P>", "").split(",");
					String answer = "";
					for (int a = 0; a < answers.length; a++) {
						char c1 = (char) (Integer.valueOf(answers[a]) + 64);
						if (a == 0) {
							answer = String.valueOf(c1);
						} else {
							answer = answer + "," + c1;
						}
					}
					question.setQuesAnswer("<p>" + answer + "</p>");
//					question.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(question.getQuesAnswer())));
				}
				// 存在子题
				if (question.getQuestionType() == QuesStructType.NESTED_ANSWER_QUESTION) {
					List<Question> subQuestions = new ArrayList<>();
					int subQuesCount = quesTemp.getSubQues().size();
					BigDecimal totalScore = BigDecimal.valueOf(question.getScore());
					BigDecimal sum = BigDecimal.valueOf(subQuesCount);
					double score = totalScore.divide(sum).doubleValue();
					for (int s = 0; s < subQuesCount; s++) {
						QuestionsTemp subQuesTmp = (QuestionsTemp) quesTemp.getSubQues().get(String.valueOf(s + 1));
						Question subQuestion = new Question();
						subQuestion.setId(new ObjectId().toString());
						subQuestion.setQuestionType(subQuesTmp.getType());
						subQuestion.setDifficulty("中");
						subQuestion.setDifficultyDegree(0.5);
						subQuestion.setPublicity(true);
						subQuestion.setScore(score);

						String subBody = imgList(subQuesTmp.getBody());
						question.setQuesBody(replaceBlank(body));
						subQuestion.setQuesBody(subBody);

//						subQuestion.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(subQuestion.getQuesBody())));
						subQuestion.setQuesAnswer(imgList(subQuesTmp.getAnswer()));
//						subQuestion.setQuesBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(subQuestion.getQuesAnswer())));
						// 存在选项
						if (subQuestion.getQuestionType() == QuesStructType.SINGLE_ANSWER_QUESTION
								|| subQuestion.getQuestionType() == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
							List<QuesOption> subQuesOptions = new ArrayList<QuesOption>();
							Map<Object, Object> subOptionMap = subQuesTmp.getOptions();
							int subOptionCount = subOptionMap.size();
							for (int k = 0; k < subOptionCount; k++) {
								QuesOption subQuesOption = new QuesOption();
								subQuesOption.setNumber(String.valueOf(k));

								String optionBody = imgList((String) subOptionMap.get(String.valueOf(k + 1)));
								if (optionBody.startsWith("<p><p") || optionBody.startsWith("<P><P")) {
									subQuesOption.setOptionBody(replaceFirstP(optionBody));
								} else {
									subQuesOption.setOptionBody(optionBody);
								}

//								subQuesOption.setOptionBodyWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml(subQuesOption.getOptionBody())));
								if (subQuestion.getQuesAnswer().contains(String.valueOf(k + 1))) {
									subQuesOption.setIsCorrect((short) 1);
								} else {
									subQuesOption.setIsCorrect((short) 0);
								}
								subQuesOptions.add(subQuesOption);
							}
							subQuestion.setQuesOptions(subQuesOptions);
							String[] answers = subQuestion.getQuesAnswer().replaceAll("<p>", "").replaceAll("</p>", "")
									.replaceAll("<P>", "").replaceAll("</P>", "").split(",");
							String answer = "";
							for (int a = 0; a < answers.length; a++) {
								char c1 = (char) (Integer.valueOf(answers[a]) + 64);
								if (a == 0) {
									answer = String.valueOf(c1);
								} else {
									answer = answer + "," + c1;
								}
							}
							subQuestion.setQuesAnswer(answer);
//							subQuestion.setQuesAnswerWord(DocxProcessUtil.html2Docx(wordMLPackage,CommonUtils.formatHtml("<p>" + subQuestion.getQuesAnswer() + "</p>")));
						}
						subQuestions.add(subQuestion);
					}
					question.setSubQuestions(subQuestions);
				}
//				byte[] pkgByte = DocxProcessUtil.getPkgByte(wordMLPackage);
//				QuestionPkgPath quesPkgPath = new QuestionPkgPath(pkgByte);
				questionLists.add(question);
				// 包装小题
				PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
				paperDetailUnit.setPaper(paper);
				paperDetailUnit.setNumber(nm + 1);
				paperDetailUnit.setScore(question.getScore());
				paperDetailUnit.setPaperDetail(detail);
				paperDetailUnit.setQuestionType(question.getQuestionType());
				paperDetailUnit.setCreator(user.getDisplayName());
				paperDetailUnit.setCreateTime(CommonUtils.getCurDateTime());
				paperDetailUnit.setQuestion(question);
				paperDetailUnits.add(paperDetailUnit);
				paperDetailUnit.setPaperType(PaperType.IMPORT);
				nm++;
			}
		}
		return paperDetailUnits;
	}

	public String imgList(String str) throws Exception {
		if (StringUtils.isBlank(str)) {
			str = "<p></p>";
		}
		str = str.trim().replace("<br>", "").replace("</br>", "");
		if (!str.contains("<p>") && !str.contains("</P>")) {
			str = "<p>" + str + "</p>";
		}
		// 先处理span标签
		List<String> spans = parseSpans(str);
		if (spans != null && spans.size() > 0) {
			for (String span : spans) {
				str = str.replace(span, "").replace("</span>", "").replace("</SPAN>", "");
			}
		}
		str = str.replace("<o:p>", "").replace("</o:p>", "").replace("border=0", "").replace("class=MsoNormal", "")
				.replace("&phiv;", "").replace("</SPAN>", "");
		// 获取img标签
		List<String> srcList = ImgDataUtils.parseImages(str);
		if (srcList != null && srcList.size() > 0) {
			for (String img : srcList) {
				// 获取height,width值
				List<String> height = getTagAHei(img);
				List<String> width = getTagAWid(img);
				List<String> parseImageSrc = ImgDataUtils.parseImageSrc(img);
				if (parseImageSrc != null && parseImageSrc.size() > 0) {
					String src = parseImageSrc.get(0).replace("{ResourcePath}", "http://file.5any.com/UniversityV4.0");
					String url = regexCH(src);
					log.info("img url:" + url);
					url = url.replaceAll("\\\\", "/");

					String base64 = ImgDataUtils.loadImageToBase64(url);
					if (base64 == null) {
						throw new Exception("图片下载失败！" + url);
					} else {
						if (src.contains("jpg")) {
							str = str.replace(parseImageSrc.get(0), "data:image/jpg;base64," + base64);
						} else {
							str = str.replace(parseImageSrc.get(0), "data:image/png;base64," + base64);
						}
						if (height != null && height.size() > 0) {
							str = str.replace("height=" + height.get(0), "height=\"" + height.get(0) + "\"");
						}
						if (width != null && width.size() > 0) {
							str = str.replace("width=" + width.get(0), "width=\"" + width.get(0) + "\"");
						}
					}
				}
			}
		}
		return str.replace("<IMG", "<img");
	}

	// 將url路徑中的中文转码
	public String regexCH(String str) throws UnsupportedEncodingException {
		StringBuffer s = new StringBuffer();
		Pattern pat = Pattern.compile("[\u4E00-\u9FA5]");
		Matcher mat = pat.matcher(str);
		while (mat.find()) {
			s.append(mat.group());
		}
		String url = java.net.URLEncoder.encode(s.toString(), "utf-8");
		return str.replace(s.toString(), url);
	}

//	public List<String> loadFiles() {
	// 获取某文件夹下所有XML文件的路径
//		List<String> paths = new ArrayList<>();
//		File dir = new File(rootDir);
//		this.loadMoreFiles(dir, paths);
//		return paths;
//	}

	private void loadMoreFiles(File file, List<String> paths) {
		if (file.isDirectory()) {
			File[] subFiles = file.listFiles();
			for (File subFile : subFiles) {
				this.loadMoreFiles(subFile, paths);
			}
		} else {
			String path = file.getPath().replaceAll("\\\\", "/");

			if (file.getName().endsWith(".xml")) {
				paths.add(path);
			} else {
				log.error("无效文件：" + path);
			}
		}
	}

	public static List<String> parseSpans(String content) {
		if (content == null) {
			return new ArrayList<>();
		}
		List<String> spans = new ArrayList<>();
		String reg = "<(span|SPAN)(.*?)(/>|>)";
		Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(content);
		while (matcher.find()) {
			String span = matcher.group();
			spans.add(span);
		}
		return spans;
	}

	public List<String> getTagAHei(String htmlString) {
		List<String> list = new ArrayList<String>();
		Pattern p = Pattern.compile("<IMG[^<>]*\\s+height=([0-9A-Za-z-_.]+)\\s*");
		Matcher m = p.matcher(htmlString);
		while (m.find()) {
			String str = m.group(1);
			list.add(str);
		}
		return list;
	}

	public List<String> getTagAWid(String htmlString) {
		List<String> list = new ArrayList<String>();
		Pattern p = Pattern.compile("<IMG[^<>]*\\s+width=([0-9A-Za-z-_.]+)\\s*");
		Matcher m = p.matcher(htmlString);
		while (m.find()) {
			String str = m.group(1);
			list.add(str);
		}
		return list;
	}

	/**
	 * 将[BLANK] 替换为 ###
	 */
	public static String replaceBlank(String str) {
		if (str == null) {
			return null;
		}
		str=str.replaceAll("<div>", "<p>");
		str=str.replaceAll("</div>", "</p>");
		return str.replaceAll("[BLANK]", "###");
	}

	/**
	 * 替换首个P标签
	 */
	public static String replaceFirstP(String str) {
		if (str == null) {
			return null;
		}
		if (str.startsWith("<p>") && str.endsWith("</p>")) {
			// 去掉头<p >
			str = str.replaceFirst("<p>", "");
			// 去掉尾</p>
			int index = str.lastIndexOf("</p>");
			if (index > 0) {
				str = str.substring(0, index);
			}
		}
		return str;
	}

}