xiatian 6 月之前
父節點
當前提交
29e19945eb

+ 152 - 150
src/main/java/cn/com/qmth/export/ExportGkProperty.java

@@ -25,154 +25,156 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import com.alibaba.fastjson.JSONObject;
 
 public class ExportGkProperty {
-	private static Logger logger = LogManager.getLogger(ExportGkProperty.class);
-	private static String dbName="guangkai_mdl";
-	private final static String sourceDir = "d:/guangkai/";
-	public static void main(String[] args) {
-		logger.debug("导出开始");
-		try {
-			dispose();
-		} catch (Exception e) {
-			logger.error(e.getCause(), e);
-		}
-		logger.debug("导出结束");
-	}
-	
-	private static void dispose() {
-		File dir=new File(sourceDir+"prop/");
-		if(dir.exists()) {
-			FileUtil.clearDirectory(sourceDir+"prop/");
-		}else {
-			dir.mkdirs();
-		}
-		Connection connect = null;
-
-		try {
-			Class.forName("com.mysql.cj.jdbc.Driver");
-
-			String url = "jdbc:mysql://localhost:3306/"+dbName+"?serverTimezone=GMT%2B8";
-
-			String user = "root";
-
-			String password = "123456";
-			connect = DriverManager.getConnection(url, user, password);
-			exportProperty(connect);
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (connect != null) {
-				try {
-					connect.close();
-				} catch (SQLException e) {
-				}
-			}
-		}
-	}
-
-	private static void exportProperty(Connection connect) throws InvalidFormatException, IOException, SQLException {
-		Set<String> subjectCodes=readSubject();
-		if(CollectionUtils.isEmpty(subjectCodes)) {
-			return;
-		}
-		System.out.println("总科目数:"+subjectCodes.size());
-		int total=0;
-		for(String code:subjectCodes) {
-			try {
-				List<PropertyDto> props=getProperty(connect, code);
-				if(CollectionUtils.isNotEmpty(props)) {
-					total++;
-					FileUtil.writeFile(sourceDir+"prop/", code+".json", JSONObject.toJSONString(props));
-				}else {
-					System.out.println("无文件:"+code);
-				}
-			}catch (Exception e) {
-				throw new RuntimeException("courseCode:"+code,e);
-			}
-		}
-		System.out.println("文件数:"+total);
-	}
-	private static Set<String> readSubject() {
-		Set<String> list = new HashSet<>();
-		XSSFWorkbook wb = null;
-		try {
-			wb = new XSSFWorkbook(sourceDir + "subject_info.xlsx");
-			XSSFSheet sheet = wb.getSheetAt(0);
-			int rows = sheet.getLastRowNum();
-			for (int i = 1; i <= rows; i++) {
-				XSSFRow row = sheet.getRow(i);
-				String code;
-				try {
-					code = row.getCell(1).getStringCellValue().trim();
-				} catch (Exception e) {
-					code = (row.getCell(1).getNumericCellValue()+"").trim();
-				}
-				list.add(code);
-			}
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (wb != null) {
-				try {
-					wb.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-		return list;
-	}
-	
-	private static List<PropertyDto> getProperty(Connection connect, String subjectCode) throws SQLException, IOException {
-		List<PropertyDto> as = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select qc.* from mdl_course c "
-					+" inner join mdl_context ct on c.id=ct.instanceid "
-					+" inner join mdl_question_categories qc on ct.id=qc.contextid "
-					+" where c.idnumber='"+subjectCode+"' "
-					+" order by qc.level,qc.sortorder,qc.id ";
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-			Map<Long,PropertyDto> map=new HashMap<>();
-			while (resultSet.next()) {
-				PropertyDto a = new PropertyDto();
-				a.setId(resultSet.getLong("id"));
-				a.setParentId(resultSet.getLong("parent"));
-				a.setName(resultSet.getString("name"));
-				map.put(a.getId(), a);
-				if(a.getParentId()!=0) {
-					PropertyDto parent=map.get(a.getParentId());
-					try {
-						if (parent.getParentId() == 0) {
-							as.add(a);
-						} else {
-							a.setName(parent.getName() + "|" + a.getName());
-							PropertyDto root = getRoot(map, a);
-							root.addSub(a);
-						} 
-					} catch (Exception e) {
-						throw e;
-					}
-				}
-			}
-			return as;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	
-	private static PropertyDto getRoot(Map<Long,PropertyDto> map,PropertyDto cur) {
-		PropertyDto parent=map.get(cur.getParentId());
-		if(parent.getParentId()==0) {
-			return cur;
-		}else {
-			return getRoot(map, parent);
-		}
-	}
+
+    private static Logger logger = LogManager.getLogger(ExportGkProperty.class);
+
+    private final static String sourceDir = Param.dataDir;
+
+    public static void main(String[] args) {
+        logger.debug("导出开始");
+        try {
+            dispose();
+        } catch (Exception e) {
+            logger.error(e.getCause(), e);
+        }
+        logger.debug("导出结束");
+    }
+
+    private static void dispose() {
+        File dir = new File(sourceDir + "prop/");
+        if (dir.exists()) {
+            FileUtil.clearDirectory(sourceDir + "prop/");
+        } else {
+            dir.mkdirs();
+        }
+        Connection connect = null;
+
+        try {
+            Class.forName("com.mysql.cj.jdbc.Driver");
+
+            String url = "jdbc:mysql://localhost:3306/" + Param.dbName + "?serverTimezone=GMT%2B8";
+
+            String user = "root";
+
+            String password = "123456";
+            connect = DriverManager.getConnection(url, user, password);
+            exportProperty(connect);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (connect != null) {
+                try {
+                    connect.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    private static void exportProperty(Connection connect) throws InvalidFormatException, IOException, SQLException {
+        Set<String> subjectCodes = readSubject();
+        if (CollectionUtils.isEmpty(subjectCodes)) {
+            return;
+        }
+        System.out.println("总科目数:" + subjectCodes.size());
+        int total = 0;
+        for (String code : subjectCodes) {
+            try {
+                List<PropertyDto> props = getProperty(connect, code);
+                if (CollectionUtils.isNotEmpty(props)) {
+                    total++;
+                    FileUtil.writeFile(sourceDir + "prop/", code + ".json", JSONObject.toJSONString(props));
+                } else {
+                    System.out.println("无文件:" + code);
+                }
+            } catch (Exception e) {
+                throw new RuntimeException("courseCode:" + code, e);
+            }
+        }
+        System.out.println("文件数:" + total);
+    }
+
+    private static Set<String> readSubject() {
+        Set<String> list = new HashSet<>();
+        XSSFWorkbook wb = null;
+        try {
+            wb = new XSSFWorkbook(sourceDir + "subject_info.xlsx");
+            XSSFSheet sheet = wb.getSheetAt(0);
+            int rows = sheet.getLastRowNum();
+            for (int i = 1; i <= rows; i++) {
+                XSSFRow row = sheet.getRow(i);
+                String code;
+                try {
+                    code = row.getCell(0).getStringCellValue().trim();
+                } catch (Exception e) {
+                    code = (row.getCell(0).getNumericCellValue() + "").trim();
+                }
+                list.add(code);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (wb != null) {
+                try {
+                    wb.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+        return list;
+    }
+
+    private static List<PropertyDto> getProperty(Connection connect, String subjectCode)
+            throws SQLException, IOException {
+        List<PropertyDto> as = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select qc.* from mdl_course c " + " inner join mdl_context ct on c.id=ct.instanceid "
+                    + " inner join mdl_question_categories qc on ct.id=qc.contextid " + " where c.idnumber='"
+                    + subjectCode + "' " + " order by qc.level,qc.sortorder,qc.id ";
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+            Map<Long, PropertyDto> map = new HashMap<>();
+            while (resultSet.next()) {
+                PropertyDto a = new PropertyDto();
+                a.setId(resultSet.getLong("id"));
+                a.setParentId(resultSet.getLong("parent"));
+                a.setName(resultSet.getString("name"));
+                map.put(a.getId(), a);
+                if (a.getParentId() != 0) {
+                    PropertyDto parent = map.get(a.getParentId());
+                    try {
+                        if (parent.getParentId() == 0) {
+                            as.add(a);
+                        } else {
+                            a.setName(parent.getName() + "|" + a.getName());
+                            PropertyDto root = getRoot(map, a);
+                            root.addSub(a);
+                        }
+                    } catch (Exception e) {
+                        throw e;
+                    }
+                }
+            }
+            return as;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private static PropertyDto getRoot(Map<Long, PropertyDto> map, PropertyDto cur) {
+        PropertyDto parent = map.get(cur.getParentId());
+        if (parent.getParentId() == 0) {
+            return cur;
+        } else {
+            return getRoot(map, parent);
+        }
+    }
 }

+ 58 - 51
src/main/java/cn/com/qmth/export/GkExportPaperByCourseCode3.java

@@ -1,64 +1,71 @@
 package cn.com.qmth.export;
 
 import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.Vector;
 import java.util.concurrent.atomic.AtomicInteger;
 
+import org.apache.commons.lang3.StringUtils;
 import org.apache.log4j.LogManager;
 import org.apache.log4j.Logger;
 
-/**moodle按课程导
+/**
+ * moodle按课程导
+ * 
  * @author Administrator
  *
  */
 public class GkExportPaperByCourseCode3 {
-	private static Logger logger = LogManager.getLogger(GkExportPaperByCourseCode3.class);
-	//试卷后缀
-	private static String paperSuff = "(240524)";
-	//数据库名
-	private static String dbName="guangkai_mdl";
-	private static AtomicInteger count=new AtomicInteger(0);
-	
-	private static AtomicInteger valid=new AtomicInteger(0);
-	
-	private static AtomicInteger imgValid=new AtomicInteger(0);
-	
-	private static AtomicInteger rectify=new AtomicInteger(0);
-	
-	public static void main(String[] args) {
-		logger.debug("导出开始");
-		Date start=new Date();
-		try {
-			MyProducer3 pro=new MyProducer3();
-			Map<String, Object> param=new HashMap<>();
-			param.put("paperSuff", paperSuff);
-			param.put("dbName", dbName);
-			pro.startDispose(MyConsumer3.class, 8, param);
-		} catch (Exception e) {
-			logger.error(e.getCause(), e);
-		}
-		logger.debug("导出结束,纠正:"+rectify);
-		logger.debug("导出结束,舍弃:"+valid);
-		logger.debug("导出结束,(图片)舍弃:"+imgValid);
-		Date end=new Date();
-		logger.debug("导出结束,耗时:"+((end.getTime()-start.getTime())/1000));
-	}
-
-
-	public static void  addDisposeCount() {
-		count.addAndGet(1);
-		logger.debug("处理了"+count);
-	}
-	
-	public static void  addRectify() {
-		rectify.addAndGet(1);
-	}
-	public static void  addValid() {
-		valid.addAndGet(1);
-	}
-	
-	public static void  addImgValid() {
-		imgValid.addAndGet(1);
-	}
+
+    private static Logger logger = LogManager.getLogger(GkExportPaperByCourseCode3.class);
+
+    private static AtomicInteger count = new AtomicInteger(0);
+
+    private static AtomicInteger valid = new AtomicInteger(0);
+
+    private static AtomicInteger imgValid = new AtomicInteger(0);
+
+    private static AtomicInteger rectify = new AtomicInteger(0);
+
+    private static Vector<String> noQuestion = new Vector<>();
+
+    public static void main(String[] args) {
+        logger.debug("导出开始");
+        Date start = new Date();
+        try {
+            MyProducer3 pro = new MyProducer3();
+            pro.startDispose(MyConsumer3.class, 8, null);
+        } catch (Exception e) {
+            logger.error(e.getCause(), e);
+        }
+        logger.debug("导出结束,纠正:" + rectify);
+        logger.debug("导出结束,舍弃:" + valid);
+        logger.debug("导出结束,(图片)舍弃:" + imgValid);
+        if (noQuestion.size() > 0) {
+            logger.debug("无试题:" + StringUtils.join(noQuestion, ","));
+        }
+        Date end = new Date();
+        logger.debug("导出结束,耗时:" + ((end.getTime() - start.getTime()) / 1000));
+    }
+
+    public static void addDisposeCount() {
+        count.addAndGet(1);
+        logger.debug("处理了" + count);
+    }
+
+    public static void addRectify() {
+        rectify.addAndGet(1);
+    }
+
+    public static void addValid() {
+        valid.addAndGet(1);
+    }
+
+    public static void addImgValid() {
+        imgValid.addAndGet(1);
+    }
+
+    public static void addNoQues(String code) {
+        noQuestion.add(code);
+    }
+
 }

+ 53 - 47
src/main/java/cn/com/qmth/export/GkExportPaperByCourseCode4.java

@@ -8,57 +8,63 @@ import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.log4j.LogManager;
 import org.apache.log4j.Logger;
 
-/**moodle按属性分试卷
+/**
+ * moodle按属性分试卷
+ * 
  * @author Administrator
  *
  */
 public class GkExportPaperByCourseCode4 {
-	private static Logger logger = LogManager.getLogger(GkExportPaperByCourseCode4.class);
-	//试卷后缀
-	private static String paperSuff = "(240524)";
-	//数据库名
-	private static String dbName="guangkai_mdl";
-	private static AtomicInteger count=new AtomicInteger(0);
-	
-	private static AtomicInteger valid=new AtomicInteger(0);
-	
-	private static AtomicInteger imgValid=new AtomicInteger(0);
-	
-	private static AtomicInteger rectify=new AtomicInteger(0);
-	
-	public static void main(String[] args) {
-		logger.debug("导出开始");
-		Date start=new Date();
-		try {
-			MyProducer4 pro=new MyProducer4();
-			Map<String, Object> param=new HashMap<>();
-			param.put("paperSuff", paperSuff);
-			param.put("dbName", dbName);
-			pro.startDispose(MyConsumer4.class, 8, param);
-		} catch (Exception e) {
-			logger.error(e.getCause(), e);
-		}
-		logger.debug("导出结束,纠正:"+rectify);
-		logger.debug("导出结束,舍弃:"+valid);
-		logger.debug("导出结束,(图片)舍弃:"+imgValid);
-		Date end=new Date();
-		logger.debug("导出结束,耗时:"+((end.getTime()-start.getTime())/1000));
-	}
 
+    private static Logger logger = LogManager.getLogger(GkExportPaperByCourseCode4.class);
 
-	public static void  addDisposeCount() {
-		count.addAndGet(1);
-		logger.debug("处理了"+count);
-	}
-	
-	public static void  addRectify() {
-		rectify.addAndGet(1);
-	}
-	public static void  addValid() {
-		valid.addAndGet(1);
-	}
-	
-	public static void  addImgValid() {
-		imgValid.addAndGet(1);
-	}
+    // 试卷后缀
+    private static String paperSuff = "(241128)";
+
+    // 数据库名
+    private static String dbName = "guangkai241128";
+
+    private static AtomicInteger count = new AtomicInteger(0);
+
+    private static AtomicInteger valid = new AtomicInteger(0);
+
+    private static AtomicInteger imgValid = new AtomicInteger(0);
+
+    private static AtomicInteger rectify = new AtomicInteger(0);
+
+    public static void main(String[] args) {
+        logger.debug("导出开始");
+        Date start = new Date();
+        try {
+            MyProducer4 pro = new MyProducer4();
+            Map<String, Object> param = new HashMap<>();
+            param.put("paperSuff", paperSuff);
+            param.put("dbName", dbName);
+            pro.startDispose(MyConsumer4.class, 8, param);
+        } catch (Exception e) {
+            logger.error(e.getCause(), e);
+        }
+        logger.debug("导出结束,纠正:" + rectify);
+        logger.debug("导出结束,舍弃:" + valid);
+        logger.debug("导出结束,(图片)舍弃:" + imgValid);
+        Date end = new Date();
+        logger.debug("导出结束,耗时:" + ((end.getTime() - start.getTime()) / 1000));
+    }
+
+    public static void addDisposeCount() {
+        count.addAndGet(1);
+        logger.debug("处理了" + count);
+    }
+
+    public static void addRectify() {
+        rectify.addAndGet(1);
+    }
+
+    public static void addValid() {
+        valid.addAndGet(1);
+    }
+
+    public static void addImgValid() {
+        imgValid.addAndGet(1);
+    }
 }

+ 474 - 471
src/main/java/cn/com/qmth/export/MyConsumer.java

@@ -23,475 +23,478 @@ import com.alibaba.fastjson.JSONException;
 import com.alibaba.fastjson.JSONObject;
 
 public class MyConsumer extends Consumer<PaperExportDto> {
-//	private static String[] sucStr = new String[] { "对", "正确", "√", "是", "True" };
-//	private static String[] errStr = new String[] { "错", "错误", "×", "不正确", "否", "False" };
-//	private static String paperSuff = "(231205)";
-	private int maxqc = 200;
-
-	private static String paperDir = "d:/guangkai/paper/";
-	private static String imgDir = "d:/guangkai";
-
-	private Pattern imgPat = Pattern.compile("<img[^<]+src=['\"]([^<\"]+)['\"][^<]*>");
-	
-	private Pattern xieGangPat = Pattern.compile("\\\\([^\"]|(\",))");
-
-	@Override
-	public void consume(PaperExportDto dto) {
-		Connection connect = null;
-		File sub = new File(paperDir + dto.getCourseCode() + "/");
-		sub.mkdir();
-		try {
-			Class.forName("com.mysql.cj.jdbc.Driver");
-
-			String url = "jdbc:mysql://localhost:3306/" + dto.getDbName() + "?serverTimezone=GMT%2B8";
-
-			String user = "root";
-
-			String password = "123456";
-			connect = DriverManager.getConnection(url, user, password);
-			exportPaper(connect, dto);
-			GkExportPaperByCourseCode.addDisposeCount();
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (connect != null) {
-				try {
-					connect.close();
-				} catch (SQLException e) {
-				}
-			}
-		}
-	}
-
-	private List<KdQuestion> of(List<QuestionVo> vos, List<QuestionVo> subvosList) {
-		List<KdQuestion> ret = new ArrayList<>();
-		Map<String, List<QuestionVo>> submap = new HashMap<>();
-		if (CollectionUtils.isNotEmpty(subvosList)) {
-			for (QuestionVo vo : subvosList) {
-				List<QuestionVo> tem = submap.get(vo.getPid());
-				if (tem == null) {
-					tem = new ArrayList<>();
-					submap.put(vo.getPid(), tem);
-				}
-				tem.add(vo);
-			}
-		}
-		for (QuestionVo vo : vos) {
-			try {
-				KdQuestion q = of(vo);
-				if (QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-					List<QuestionVo> subvos = submap.get(q.getId());
-					q.setScore((double) subvos.size());
-					List<Double> subScores = new ArrayList<>();
-					List<KdQuestion> subQues = new ArrayList<>();
-					q.setSubScores(subScores);
-					q.setSubQuestions(subQues);
-					int num = 0;
-					for (QuestionVo subvo : subvos) {
-						num++;
-						subScores.add(1.0);
-						KdQuestion subq = of(subvo);
-						subq.setId(null);
-						if (CusQuesStructType.cloze.equals(q.getCusType()) && StringUtils.isBlank(subq.getBody())) {
-							subq.setBody("___" + num + "___");
-						}
-						subQues.add(subq);
-					}
-				}
-				ret.add(q);
-			} catch (StatusException e) {
-				GkExportPaperByCourseCode.addValid();
-				continue;
-			}
-		}
-		return ret;
-	}
-
-	private String changeBlank(String text, int answerCount,String qid) {
-		StringBuffer buffer = new StringBuffer();
-		String regex = "<fillblank/>";
-
-		Pattern pattern = Pattern.compile(regex);
-		Matcher matcher = pattern.matcher(text);
-		// 使用find()方法查找匹配项
-		int num = 0;
-		while (matcher.find()) {
-			num++;
-			matcher.appendReplacement(buffer, "###");
-		}
-		matcher.appendTail(buffer);
-		if (answerCount != num) {
-			throw new StatusException("答案数不匹配:"+qid);
-		}
-		return buffer.toString();
-	}
-
-	private String changeCloze(String text) {
-		StringBuffer buffer = new StringBuffer();
-		String regex = "<fillblank/>";
-
-		Pattern pattern = Pattern.compile(regex);
-		Matcher matcher = pattern.matcher(text);
-		// 使用find()方法查找匹配项
-		int num = 0;
-		while (matcher.find()) {
-			num++;
-			matcher.appendReplacement(buffer, "___" + num + "___");
-		}
-		matcher.appendTail(buffer);
-		return buffer.toString();
-	}
-
-	private KdQuestion of(QuestionVo vo) {
-		KdQuestion q = new KdQuestion();
-		q.setCusType(vo.getqType());
-		q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
-		q.setTypeId(vo.getTypeId());
-		q.setDetailName(vo.getTypeName());
-		q.setBody(vo.getBody());
-		q.setDifficultyDegree(0.5);
-		q.setHaveAudio(false);
-		q.setId(vo.getQid());
-		q.setScore(1.0);
-		if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			List<KdQuesOption> options = new ArrayList<>();
-			q.setOptions(options);
-			int num = 0;
-			int answerCount = 0;
-			for (String a : vo.getAnswer().getSubArea()) {
-				num++;
-				KdQuesOption o = new KdQuesOption();
-				options.add(o);
-				o.setNumber(num);
-				o.setBody(a);
-				o.setSelect(vo.getAnswer().getAnswer().contains("" + (num - 1)));
-				if (o.getSelect()) {
-					answerCount++;
-				}
-			}
-			if (answerCount == 0) {
-				throw new StatusException("没有答案:"+q.getId());
-			}
-			if (answerCount > 1) {
-				throw new StatusException("答案过多");
-			}
-		} else if (QuesStructType.MULTIPLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			List<KdQuesOption> options = new ArrayList<>();
-			q.setOptions(options);
-			int num = 0;
-			int answerCount = 0;
-			for (String a : vo.getAnswer().getSubArea()) {
-				num++;
-				KdQuesOption o = new KdQuesOption();
-				options.add(o);
-				o.setNumber(num);
-				o.setBody(a);
-				o.setSelect(vo.getAnswer().getAnswer().contains("" + (num - 1)));
-				if (o.getSelect()) {
-					answerCount++;
-				}
-			}
-			if (answerCount == 0) {
-				throw new StatusException("没有答案");
-			}
-			if (answerCount > 10) {
-				throw new StatusException("答案超过10个:" + vo.getQid());
-			}
-		} else if (QuesStructType.BOOL_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			if (vo.getAnswer().getAnswer().contains("0")) {
-				q.setAnswer("正确");
-			} else if (vo.getAnswer().getAnswer().contains("1")) {
-				q.setAnswer("错误");
-			} else {
-				throw new StatusException("答案有误");
-			}
-		} else if (QuesStructType.FILL_BLANK_QUESTION.equals(q.getQuesStructType())) {
-			int aCount = 0;
-			List<String> tem = new ArrayList<>();
-			for (List<String> ss : vo.getfAnswer().getAnswer()) {
-				for (String s : ss) {
-					aCount++;
-					tem.add(s);
-				}
-			}
-			q.setAnswer(StringUtils.join(tem, "##"));
-			q.setBody(changeBlank(q.getBody(), aCount,q.getId()));
-		} else if (QuesStructType.TEXT_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			q.setAnswer(StringUtils.join(vo.getAnswer().getAnswer(), ""));
-		} else if (QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			if (CusQuesStructType.cloze.equals(q.getCusType())) {
-				q.setBody(changeCloze(q.getBody()));
-			}
-		} else {
-			throw new StatusException("题型有误");
-		}
-		disposeQuestionImg(q);
-		return q;
-	}
-
-	private List<QuestionVo> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
-		List<QuestionVo> qs = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select q.TYPE_ID typeId,f.name typeName,f.ANSWER_TYPE qType "
-					+ " ,q.ID qid,q.TITLE body,q.FATHER_ID pid " + " ,q.answer,q.SHOW_ORDER seq  "
-					+ " from pe_question_bank t  " + " INNER JOIN pe_questions q on t.id=q.BANK_ID "
-					+ " INNER JOIN pe_question_type f on f.id=q.TYPE_ID " + " where t.course_id='" + courseCode + "'";
-
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				QuestionVo q = new QuestionVo();
-				q.setQid(resultSet.getString("qid"));
-				q.setTypeId(resultSet.getString("typeId"));
-				q.setTypeName(resultSet.getString("typeName"));
-				q.setPid(resultSet.getString("pid"));
-				q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
-				q.setBody(resultSet.getString("body"));
-				q.setSeq(resultSet.getInt("seq"));
-				String an=resultSet.getString("answer");
-				try {
-					if (CusQuesStructType.fillblank.equals(q.getqType())) {
-						q.setfAnswer(JSONObject.parseObject(an, FillBlankAnswerVo.class));
-					} else {
-						q.setAnswer(JSONObject.parseObject(an, AnswerVo.class));
-					}
-				} catch (JSONException e) {
-					try {
-						System.out.println("old#############qid:" + q.getQid()+" "+an);
-						an=fomat(an);
-						System.out.println("new#############qid:" + q.getQid()+" "+an);
-						if (CusQuesStructType.fillblank.equals(q.getqType())) {
-							q.setfAnswer(JSONObject.parseObject(an, FillBlankAnswerVo.class));
-						} else {
-							q.setAnswer(JSONObject.parseObject(an, AnswerVo.class));
-						}
-						
-						GkExportPaperByCourseCode.addRectify();
-					} catch (Exception e1) {
-						GkExportPaperByCourseCode.addValid();
-						continue;
-					}
-				}
-				qs.add(q);
-			}
-			return qs;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	
-	private String fomat(String text) {
-		StringBuffer buffer = new StringBuffer();
-		Matcher matcher = xieGangPat.matcher(text);
-		// 使用find()方法查找匹配项
-		while (matcher.find()) {
-			String tem=matcher.group(1);
-			matcher.appendReplacement(buffer, "\\\\\\\\"+tem);
-		}
-		matcher.appendTail(buffer);
-		return buffer.toString();
-	}
-	
-//	public static void main(String[] args) {
-//		String s="a\"\\\",b\\h";
-//		System.out.println(s);
-//		System.out.println(fomat(s));
-//	}
-	
-	
-	private List<QuestionVo> getSubQuestion(Connection connect, String courseCode, List<String> pids)
-			throws SQLException, IOException {
-		List<QuestionVo> qs = new ArrayList<>();
-		if(CollectionUtils.isEmpty(pids)) {
-			return qs;
-		}
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select f.name typeName,f.ANSWER_TYPE qType " + " ,q.ID qid,q.TITLE body,q.FATHER_ID pid "
-					+ " ,q.answer,q.SHOW_ORDER seq  " + " from  pe_questions q  "
-					+ " INNER JOIN pe_question_type f on f.id=q.TYPE_ID " + " where q.FATHER_ID in ('"
-					+ StringUtils.join(pids, "','") + "') order by q.SHOW_ORDER";
-
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				QuestionVo q = new QuestionVo();
-				q.setQid(resultSet.getString("qid"));
-				q.setTypeName(resultSet.getString("typeName"));
-				q.setPid(resultSet.getString("pid"));
-				q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
-				q.setBody(resultSet.getString("body"));
-				q.setAnswer(JSONObject.parseObject(resultSet.getString("answer"), AnswerVo.class));
-				q.setSeq(resultSet.getInt("seq"));
-				qs.add(q);
-			}
-			return qs;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-
-	private void disposeQuestionImg(KdQuestion q) {
-		q.setBody(disposeImg(q.getBody(), q.getId()));
-		if (CollectionUtils.isNotEmpty(q.getOptions())) {
-			for (KdQuesOption o : q.getOptions()) {
-				o.setBody(disposeImg(o.getBody(), q.getId()));
-			}
-		}
-		q.setAnswer(disposeImg(q.getAnswer(), q.getId()));
-	}
-
-	private String disposeImg(String str, String qid) {
-		if (StringUtils.isBlank(str)) {
-			return str;
-		}
-		Matcher matcher = imgPat.matcher(str);
-		Map<String, String> srcMap = new HashMap<>();
-		while (matcher.find()) {
-			String imgSrc = matcher.group(1).trim();
-			if (imgSrc.startsWith("data:image/")) {
-
-			} else if (imgSrc.startsWith("/resourcefile/bdeditor")) {
-				if (srcMap.get(imgSrc) == null) {
-					File img = new File(imgDir + imgSrc);
-					if (!img.exists()) {
-						throw new StatusException("图片有误:" + qid);
-					}
-					String base64 = FileUtil.fileToBase64Src(img);
-					srcMap.put(imgSrc, base64);
-				}
-			} else if (imgSrc.toLowerCase().trim().startsWith("http")) {
-				if (srcMap.get(imgSrc) == null) {
-					File img = new File(imgDir + "/" + UUID.randomUUID() + ".png");
-					FileUtil.saveUrlAs(imgSrc, img.getAbsolutePath());
-					String base64 = FileUtil.fileToBase64Src(img);
-					img.delete();
-					srcMap.put(imgSrc, base64);
-				}
-			} else if (imgSrc.toLowerCase().trim().startsWith("/formula")) {
-				if (srcMap.get(imgSrc) == null) {
-					File img = new File(imgDir + "/" + UUID.randomUUID() + ".png");
-					FileUtil.saveUrlAs("https://ougd-exam.webtrn.cn" + imgSrc, img.getAbsolutePath());
-					String base64 = FileUtil.fileToBase64Src(img);
-					img.delete();
-					srcMap.put(imgSrc, base64);
-				}
-			} else {
-				throw new StatusException("图片有误:" + qid);
-			}
-		}
-		for (String imgSrc : srcMap.keySet()) {
-			str = str.replaceAll(imgSrc, srcMap.get(imgSrc));
-		}
-		return str;
-	}
-
-	private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
-		List<QuestionVo> vos = getQuestion(connect, dto.getCourseCode());
-		if (CollectionUtils.isEmpty(vos)) {
-			return;
-		}
-		List<String> pids = vos.stream().filter(e -> e.getqType().getTypeId() == 6).map(QuestionVo::getQid)
-				.collect(Collectors.toList());
-		List<QuestionVo> subvos = getSubQuestion(connect, dto.getCourseCode(), pids);
-		List<KdQuestion> qs = of(vos, subvos);
-//		fillProp(connect, qs);
-//		fillAnswer(connect, qs, dto.getCourseCode());
-
-		Map<DetailDto, List<KdQuestion>> qmap = new HashMap<>();
-		for (KdQuestion q : qs) {
-			DetailDto tem = new DetailDto(q.getTypeId(), q.getDetailName());
-			List<KdQuestion> list = qmap.get(tem);
-			if (list == null) {
-				list = new ArrayList<>();
-				qmap.put(tem, list);
-			}
-			list.add(q);
-		}
-		for (DetailDto qt : qmap.keySet()) {
-			createPapers(qmap.get(qt), qt, dto);
-		}
-	}
-
-	private void createPapers(List<KdQuestion> qs, DetailDto qt, PaperExportDto dto) {
-		if (qs == null || qs.size() == 0) {
-			return;
-		}
-		if (qs.size() <= maxqc) {
-			createPaper(qs, qt, dto, 1);
-		} else {
-			int size = qs.size();
-			int len = maxqc;
-			int count = (size + len - 1) / len;
-
-			for (int i = 0; i < count; i++) {
-				List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
-				createPaper(subList, qt, dto, i + 1);
-			}
-		}
-
-	}
-
-	private void createPaper(List<KdQuestion> qs, DetailDto qt, PaperExportDto dto, int indx) {
-		if (qs.size() == 0) {
-			return;
-		}
-		double score = 0.0;
-		int unit = 0;
-		for (KdQuestion q : qs) {
-			if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
-				unit = unit + q.getSubQuestions().size();
-			} else {
-				unit++;
-			}
-			score = Calculator.add(score, q.getScore(), 1);
-		}
-		String detailName = qt.getTypeName();
-		KdPaper paper = new KdPaper();
-		paper.setDetailCount(1);
-		paper.setUnitCount(unit);
-		paper.setTotalScore(score);
-		paper.setName(dto.getPaperSuff() + detailName + "_" + indx);
-		paper.setCourseCode(dto.getCourseCode());
-		List<KdDetail> des = new ArrayList<>();
-		KdDetail d = new KdDetail();
-		d.setName(detailName);
-		d.setNumber(1);
-		d.setQuestionCount(unit);
-		d.setTotalScore(score);
-		d.setQuestions(qs);
-		des.add(d);
-		paper.setDetails(des);
-		paper.setDetailCount(1);
-		paper.setUnitCount(qs.size());
-		File paperdir = new File(paperDir + dto.getCourseCode() + "/" + qt.getTypeId() + "/");
-		paperdir.mkdirs();
-		try {
-			FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper_" + indx + ".json", JSONObject.toJSONString(paper));
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	@Override
-	public void initResult() {
-
-	}
+
+    // private static String[] sucStr = new String[] { "对", "正确", "√", "是",
+    // "True" };
+    // private static String[] errStr = new String[] { "错", "错误", "×", "不正确",
+    // "否", "False" };
+    // private static String paperSuff = "(231205)";
+    private int maxqc = 200;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    private static String imgDir = Param.dataDir;
+
+    private Pattern imgPat = Pattern.compile("<img[^<]+src=['\"]([^<\"]+)['\"][^<]*>");
+
+    private Pattern xieGangPat = Pattern.compile("\\\\([^\"]|(\",))");
+
+    @Override
+    public void consume(PaperExportDto dto) {
+        Connection connect = null;
+        File sub = new File(paperDir + dto.getCourseCode() + "/");
+        sub.mkdir();
+        try {
+            Class.forName("com.mysql.cj.jdbc.Driver");
+
+            String url = "jdbc:mysql://localhost:3306/" + Param.dbName + "?serverTimezone=GMT%2B8";
+
+            String user = "root";
+
+            String password = "123456";
+            connect = DriverManager.getConnection(url, user, password);
+            exportPaper(connect, dto);
+            GkExportPaperByCourseCode.addDisposeCount();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (connect != null) {
+                try {
+                    connect.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    private List<KdQuestion> of(List<QuestionVo> vos, List<QuestionVo> subvosList) {
+        List<KdQuestion> ret = new ArrayList<>();
+        Map<String, List<QuestionVo>> submap = new HashMap<>();
+        if (CollectionUtils.isNotEmpty(subvosList)) {
+            for (QuestionVo vo : subvosList) {
+                List<QuestionVo> tem = submap.get(vo.getPid());
+                if (tem == null) {
+                    tem = new ArrayList<>();
+                    submap.put(vo.getPid(), tem);
+                }
+                tem.add(vo);
+            }
+        }
+        for (QuestionVo vo : vos) {
+            try {
+                KdQuestion q = of(vo);
+                if (QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+                    List<QuestionVo> subvos = submap.get(q.getId());
+                    q.setScore((double) subvos.size());
+                    List<Double> subScores = new ArrayList<>();
+                    List<KdQuestion> subQues = new ArrayList<>();
+                    q.setSubScores(subScores);
+                    q.setSubQuestions(subQues);
+                    int num = 0;
+                    for (QuestionVo subvo : subvos) {
+                        num++;
+                        subScores.add(1.0);
+                        KdQuestion subq = of(subvo);
+                        subq.setId(null);
+                        if (CusQuesStructType.cloze.equals(q.getCusType()) && StringUtils.isBlank(subq.getBody())) {
+                            subq.setBody("___" + num + "___");
+                        }
+                        subQues.add(subq);
+                    }
+                }
+                ret.add(q);
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode.addValid();
+                continue;
+            }
+        }
+        return ret;
+    }
+
+    private String changeBlank(String text, int answerCount, String qid) {
+        StringBuffer buffer = new StringBuffer();
+        String regex = "<fillblank/>";
+
+        Pattern pattern = Pattern.compile(regex);
+        Matcher matcher = pattern.matcher(text);
+        // 使用find()方法查找匹配项
+        int num = 0;
+        while (matcher.find()) {
+            num++;
+            matcher.appendReplacement(buffer, "###");
+        }
+        matcher.appendTail(buffer);
+        if (answerCount != num) {
+            throw new StatusException("答案数不匹配:" + qid);
+        }
+        return buffer.toString();
+    }
+
+    private String changeCloze(String text) {
+        StringBuffer buffer = new StringBuffer();
+        String regex = "<fillblank/>";
+
+        Pattern pattern = Pattern.compile(regex);
+        Matcher matcher = pattern.matcher(text);
+        // 使用find()方法查找匹配项
+        int num = 0;
+        while (matcher.find()) {
+            num++;
+            matcher.appendReplacement(buffer, "___" + num + "___");
+        }
+        matcher.appendTail(buffer);
+        return buffer.toString();
+    }
+
+    private KdQuestion of(QuestionVo vo) {
+        KdQuestion q = new KdQuestion();
+        q.setCusType(vo.getqType());
+        q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
+        q.setTypeId(vo.getTypeId());
+        q.setDetailName(vo.getTypeName());
+        q.setBody(vo.getBody());
+        q.setDifficultyDegree(0.5);
+        q.setHaveAudio(false);
+        q.setId(vo.getQid());
+        q.setScore(1.0);
+        if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            List<KdQuesOption> options = new ArrayList<>();
+            q.setOptions(options);
+            int num = 0;
+            int answerCount = 0;
+            for (String a : vo.getAnswer().getSubArea()) {
+                num++;
+                KdQuesOption o = new KdQuesOption();
+                options.add(o);
+                o.setNumber(num);
+                o.setBody(a);
+                o.setSelect(vo.getAnswer().getAnswer().contains("" + (num - 1)));
+                if (o.getSelect()) {
+                    answerCount++;
+                }
+            }
+            if (answerCount == 0) {
+                throw new StatusException("没有答案:" + q.getId());
+            }
+            if (answerCount > 1) {
+                throw new StatusException("答案过多");
+            }
+        } else if (QuesStructType.MULTIPLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            List<KdQuesOption> options = new ArrayList<>();
+            q.setOptions(options);
+            int num = 0;
+            int answerCount = 0;
+            for (String a : vo.getAnswer().getSubArea()) {
+                num++;
+                KdQuesOption o = new KdQuesOption();
+                options.add(o);
+                o.setNumber(num);
+                o.setBody(a);
+                o.setSelect(vo.getAnswer().getAnswer().contains("" + (num - 1)));
+                if (o.getSelect()) {
+                    answerCount++;
+                }
+            }
+            if (answerCount == 0) {
+                throw new StatusException("没有答案");
+            }
+            if (answerCount > 10) {
+                throw new StatusException("答案超过10个:" + vo.getQid());
+            }
+        } else if (QuesStructType.BOOL_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            if (vo.getAnswer().getAnswer().contains("0")) {
+                q.setAnswer("正确");
+            } else if (vo.getAnswer().getAnswer().contains("1")) {
+                q.setAnswer("错误");
+            } else {
+                throw new StatusException("答案有误");
+            }
+        } else if (QuesStructType.FILL_BLANK_QUESTION.equals(q.getQuesStructType())) {
+            int aCount = 0;
+            List<String> tem = new ArrayList<>();
+            for (List<String> ss : vo.getfAnswer().getAnswer()) {
+                for (String s : ss) {
+                    aCount++;
+                    tem.add(s);
+                }
+            }
+            q.setAnswer(StringUtils.join(tem, "##"));
+            q.setBody(changeBlank(q.getBody(), aCount, q.getId()));
+        } else if (QuesStructType.TEXT_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            q.setAnswer(StringUtils.join(vo.getAnswer().getAnswer(), ""));
+        } else if (QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            if (CusQuesStructType.cloze.equals(q.getCusType())) {
+                q.setBody(changeCloze(q.getBody()));
+            }
+        } else {
+            throw new StatusException("题型有误");
+        }
+        disposeQuestionImg(q);
+        return q;
+    }
+
+    private List<QuestionVo> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
+        List<QuestionVo> qs = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select q.TYPE_ID typeId,f.name typeName,f.ANSWER_TYPE qType "
+                    + " ,q.ID qid,q.TITLE body,q.FATHER_ID pid " + " ,q.answer,q.SHOW_ORDER seq  "
+                    + " from pe_question_bank t  " + " INNER JOIN pe_questions q on t.id=q.BANK_ID "
+                    + " INNER JOIN pe_question_type f on f.id=q.TYPE_ID " + " where t.course_id='" + courseCode + "'";
+
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                QuestionVo q = new QuestionVo();
+                q.setQid(resultSet.getString("qid"));
+                q.setTypeId(resultSet.getString("typeId"));
+                q.setTypeName(resultSet.getString("typeName"));
+                q.setPid(resultSet.getString("pid"));
+                q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
+                q.setBody(resultSet.getString("body"));
+                q.setSeq(resultSet.getInt("seq"));
+                String an = resultSet.getString("answer");
+                try {
+                    if (CusQuesStructType.fillblank.equals(q.getqType())) {
+                        q.setfAnswer(JSONObject.parseObject(an, FillBlankAnswerVo.class));
+                    } else {
+                        q.setAnswer(JSONObject.parseObject(an, AnswerVo.class));
+                    }
+                } catch (JSONException e) {
+                    try {
+                        System.out.println("old#############qid:" + q.getQid() + " " + an);
+                        an = fomat(an);
+                        System.out.println("new#############qid:" + q.getQid() + " " + an);
+                        if (CusQuesStructType.fillblank.equals(q.getqType())) {
+                            q.setfAnswer(JSONObject.parseObject(an, FillBlankAnswerVo.class));
+                        } else {
+                            q.setAnswer(JSONObject.parseObject(an, AnswerVo.class));
+                        }
+
+                        GkExportPaperByCourseCode.addRectify();
+                    } catch (Exception e1) {
+                        GkExportPaperByCourseCode.addValid();
+                        continue;
+                    }
+                }
+                qs.add(q);
+            }
+            return qs;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private String fomat(String text) {
+        StringBuffer buffer = new StringBuffer();
+        Matcher matcher = xieGangPat.matcher(text);
+        // 使用find()方法查找匹配项
+        while (matcher.find()) {
+            String tem = matcher.group(1);
+            matcher.appendReplacement(buffer, "\\\\\\\\" + tem);
+        }
+        matcher.appendTail(buffer);
+        return buffer.toString();
+    }
+
+    // public static void main(String[] args) {
+    // String s="a\"\\\",b\\h";
+    // System.out.println(s);
+    // System.out.println(fomat(s));
+    // }
+
+    private List<QuestionVo> getSubQuestion(Connection connect, String courseCode, List<String> pids)
+            throws SQLException, IOException {
+        List<QuestionVo> qs = new ArrayList<>();
+        if (CollectionUtils.isEmpty(pids)) {
+            return qs;
+        }
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select f.name typeName,f.ANSWER_TYPE qType " + " ,q.ID qid,q.TITLE body,q.FATHER_ID pid "
+                    + " ,q.answer,q.SHOW_ORDER seq  " + " from  pe_questions q  "
+                    + " INNER JOIN pe_question_type f on f.id=q.TYPE_ID " + " where q.FATHER_ID in ('"
+                    + StringUtils.join(pids, "','") + "') order by q.SHOW_ORDER";
+
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                QuestionVo q = new QuestionVo();
+                q.setQid(resultSet.getString("qid"));
+                q.setTypeName(resultSet.getString("typeName"));
+                q.setPid(resultSet.getString("pid"));
+                q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
+                q.setBody(resultSet.getString("body"));
+                q.setAnswer(JSONObject.parseObject(resultSet.getString("answer"), AnswerVo.class));
+                q.setSeq(resultSet.getInt("seq"));
+                qs.add(q);
+            }
+            return qs;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private void disposeQuestionImg(KdQuestion q) {
+        q.setBody(disposeImg(q.getBody(), q.getId()));
+        if (CollectionUtils.isNotEmpty(q.getOptions())) {
+            for (KdQuesOption o : q.getOptions()) {
+                o.setBody(disposeImg(o.getBody(), q.getId()));
+            }
+        }
+        q.setAnswer(disposeImg(q.getAnswer(), q.getId()));
+    }
+
+    private String disposeImg(String str, String qid) {
+        if (StringUtils.isBlank(str)) {
+            return str;
+        }
+        Matcher matcher = imgPat.matcher(str);
+        Map<String, String> srcMap = new HashMap<>();
+        while (matcher.find()) {
+            String imgSrc = matcher.group(1).trim();
+            if (imgSrc.startsWith("data:image/")) {
+
+            } else if (imgSrc.startsWith("/resourcefile/bdeditor")) {
+                if (srcMap.get(imgSrc) == null) {
+                    File img = new File(imgDir + imgSrc);
+                    if (!img.exists()) {
+                        throw new StatusException("图片有误:" + qid);
+                    }
+                    String base64 = FileUtil.fileToBase64Src(img);
+                    srcMap.put(imgSrc, base64);
+                }
+            } else if (imgSrc.toLowerCase().trim().startsWith("http")) {
+                if (srcMap.get(imgSrc) == null) {
+                    File img = new File(imgDir + "/" + UUID.randomUUID() + ".png");
+                    FileUtil.saveUrlAs(imgSrc, img.getAbsolutePath());
+                    String base64 = FileUtil.fileToBase64Src(img);
+                    img.delete();
+                    srcMap.put(imgSrc, base64);
+                }
+            } else if (imgSrc.toLowerCase().trim().startsWith("/formula")) {
+                if (srcMap.get(imgSrc) == null) {
+                    File img = new File(imgDir + "/" + UUID.randomUUID() + ".png");
+                    FileUtil.saveUrlAs("https://ougd-exam.webtrn.cn" + imgSrc, img.getAbsolutePath());
+                    String base64 = FileUtil.fileToBase64Src(img);
+                    img.delete();
+                    srcMap.put(imgSrc, base64);
+                }
+            } else {
+                throw new StatusException("图片有误:" + qid);
+            }
+        }
+        for (String imgSrc : srcMap.keySet()) {
+            str = str.replaceAll(imgSrc, srcMap.get(imgSrc));
+        }
+        return str;
+    }
+
+    private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
+        List<QuestionVo> vos = getQuestion(connect, dto.getCourseCode());
+        if (CollectionUtils.isEmpty(vos)) {
+            return;
+        }
+        List<String> pids = vos.stream().filter(e -> e.getqType().getTypeId() == 6).map(QuestionVo::getQid)
+                .collect(Collectors.toList());
+        List<QuestionVo> subvos = getSubQuestion(connect, dto.getCourseCode(), pids);
+        List<KdQuestion> qs = of(vos, subvos);
+        // fillProp(connect, qs);
+        // fillAnswer(connect, qs, dto.getCourseCode());
+
+        Map<DetailDto, List<KdQuestion>> qmap = new HashMap<>();
+        for (KdQuestion q : qs) {
+            DetailDto tem = new DetailDto(q.getTypeId(), q.getDetailName());
+            List<KdQuestion> list = qmap.get(tem);
+            if (list == null) {
+                list = new ArrayList<>();
+                qmap.put(tem, list);
+            }
+            list.add(q);
+        }
+        for (DetailDto qt : qmap.keySet()) {
+            createPapers(qmap.get(qt), qt, dto);
+        }
+    }
+
+    private void createPapers(List<KdQuestion> qs, DetailDto qt, PaperExportDto dto) {
+        if (qs == null || qs.size() == 0) {
+            return;
+        }
+        if (qs.size() <= maxqc) {
+            createPaper(qs, qt, dto, 1);
+        } else {
+            int size = qs.size();
+            int len = maxqc;
+            int count = (size + len - 1) / len;
+
+            for (int i = 0; i < count; i++) {
+                List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
+                createPaper(subList, qt, dto, i + 1);
+            }
+        }
+
+    }
+
+    private void createPaper(List<KdQuestion> qs, DetailDto qt, PaperExportDto dto, int indx) {
+        if (qs.size() == 0) {
+            return;
+        }
+        double score = 0.0;
+        int unit = 0;
+        for (KdQuestion q : qs) {
+            if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
+                unit = unit + q.getSubQuestions().size();
+            } else {
+                unit++;
+            }
+            score = Calculator.add(score, q.getScore(), 1);
+        }
+        String detailName = qt.getTypeName();
+        KdPaper paper = new KdPaper();
+        paper.setDetailCount(1);
+        paper.setUnitCount(unit);
+        paper.setTotalScore(score);
+        paper.setName(Param.paperPrefix + detailName + "_" + indx);
+        paper.setCourseCode(dto.getCourseCode());
+        List<KdDetail> des = new ArrayList<>();
+        KdDetail d = new KdDetail();
+        d.setName(detailName);
+        d.setNumber(1);
+        d.setQuestionCount(unit);
+        d.setTotalScore(score);
+        d.setQuestions(qs);
+        des.add(d);
+        paper.setDetails(des);
+        paper.setDetailCount(1);
+        paper.setUnitCount(qs.size());
+        File paperdir = new File(paperDir + dto.getCourseCode() + "/" + qt.getTypeId() + "/");
+        paperdir.mkdirs();
+        try {
+            FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper_" + indx + ".json", JSONObject.toJSONString(paper));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void initResult() {
+
+    }
 }

+ 343 - 341
src/main/java/cn/com/qmth/export/MyConsumer2.java

@@ -23,354 +23,356 @@ import org.apache.commons.lang3.StringUtils;
 import com.alibaba.fastjson.JSONObject;
 
 public class MyConsumer2 extends Consumer<PaperExportDto> {
-//	private static String[] sucStr = new String[] { "对", "正确", "√", "是", "True" };
-//	private static String[] errStr = new String[] { "错", "错误", "×", "不正确", "否", "False" };
-//	private static String paperSuff = "(231205)";
-	private int maxqc = 20000000;
-
-	private static String paperDir = "d:/guangkai/paper/";
-
-	private Pattern imgPat = Pattern.compile("<img[^<]+src=\"([^<\"]+)\"[^<]*>");
-
-	@Override
-	public void consume(PaperExportDto dto) {
-		Connection connect = null;
-		File sub = new File(paperDir + dto.getCourseCode() + "/");
-		sub.mkdir();
-		try {
-			Class.forName("com.mysql.cj.jdbc.Driver");
-
-			String url = "jdbc:mysql://localhost:3306/" + dto.getDbName() + "?serverTimezone=GMT%2B8";
-
-			String user = "root";
-
-			String password = "123456";
-			connect = DriverManager.getConnection(url, user, password);
-			exportPaper(connect, dto);
-			GkExportPaperByCourseCode2.addDisposeCount();
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (connect != null) {
-				try {
-					connect.close();
-				} catch (SQLException e) {
-				}
-			}
-		}
-	}
-
-	private List<KdQuestion> of(List<QuestionVo> vos,List<QuestionVo> subvosList) {
-		List<KdQuestion> ret=new ArrayList<>();
-		Map<String,List<QuestionVo>> submap=new HashMap<>();
-		if(CollectionUtils.isNotEmpty(subvosList)) {
-			for(QuestionVo vo:subvosList) {
-				List<QuestionVo> tem=submap.get(vo.getPid());
-				if(tem==null) {
-					tem=new ArrayList<>();
-					submap.put(vo.getPid(), tem);
-				}
-				tem.add(vo);
-			}
-		}
-		for(QuestionVo vo:vos) {
-			KdQuestion q=of(vo);
-			ret.add(q);
-			if(QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-				List<QuestionVo> subvos=submap.get(q.getId());
-				q.setScore((double)subvos.size());
-				List<Double> subScores=new ArrayList<>();
-				List<KdQuestion> subQues=new ArrayList<>();
-				q.setSubScores(subScores);
-				q.setSubQuestions(subQues);
-				int num=0;
-				for(QuestionVo subvo:subvos) {
-					num++;
-					subScores.add(1.0);
-					KdQuestion subq=of(subvo);
-					subq.setId(null);
-					if(CusQuesStructType.cloze.equals(q.getCusType())&&StringUtils.isBlank(subq.getBody())) {
-						subq.setBody("___"+num+"___");
-					}
-					subQues.add(subq);
-				}
-				if(CusQuesStructType.cloze.equals(q.getCusType())) {
-					q.setBody(changeCloze(q.getBody()));
-				}
-			}
-		}
-		return ret;
-	}
-	
-	private String changeCloze(String text) {
-		StringBuffer buffer = new StringBuffer();
+
+    // private static String[] sucStr = new String[] { "对", "正确", "√", "是",
+    // "True" };
+    // private static String[] errStr = new String[] { "错", "错误", "×", "不正确",
+    // "否", "False" };
+    // private static String paperSuff = "(231205)";
+    private int maxqc = 20000000;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    private Pattern imgPat = Pattern.compile("<img[^<]+src=\"([^<\"]+)\"[^<]*>");
+
+    @Override
+    public void consume(PaperExportDto dto) {
+        Connection connect = null;
+        File sub = new File(paperDir + dto.getCourseCode() + "/");
+        sub.mkdir();
+        try {
+            Class.forName("com.mysql.cj.jdbc.Driver");
+
+            String url = "jdbc:mysql://localhost:3306/" + Param.dbName + "?serverTimezone=GMT%2B8";
+
+            String user = "root";
+
+            String password = "123456";
+            connect = DriverManager.getConnection(url, user, password);
+            exportPaper(connect, dto);
+            GkExportPaperByCourseCode2.addDisposeCount();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (connect != null) {
+                try {
+                    connect.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    private List<KdQuestion> of(List<QuestionVo> vos, List<QuestionVo> subvosList) {
+        List<KdQuestion> ret = new ArrayList<>();
+        Map<String, List<QuestionVo>> submap = new HashMap<>();
+        if (CollectionUtils.isNotEmpty(subvosList)) {
+            for (QuestionVo vo : subvosList) {
+                List<QuestionVo> tem = submap.get(vo.getPid());
+                if (tem == null) {
+                    tem = new ArrayList<>();
+                    submap.put(vo.getPid(), tem);
+                }
+                tem.add(vo);
+            }
+        }
+        for (QuestionVo vo : vos) {
+            KdQuestion q = of(vo);
+            ret.add(q);
+            if (QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+                List<QuestionVo> subvos = submap.get(q.getId());
+                q.setScore((double) subvos.size());
+                List<Double> subScores = new ArrayList<>();
+                List<KdQuestion> subQues = new ArrayList<>();
+                q.setSubScores(subScores);
+                q.setSubQuestions(subQues);
+                int num = 0;
+                for (QuestionVo subvo : subvos) {
+                    num++;
+                    subScores.add(1.0);
+                    KdQuestion subq = of(subvo);
+                    subq.setId(null);
+                    if (CusQuesStructType.cloze.equals(q.getCusType()) && StringUtils.isBlank(subq.getBody())) {
+                        subq.setBody("___" + num + "___");
+                    }
+                    subQues.add(subq);
+                }
+                if (CusQuesStructType.cloze.equals(q.getCusType())) {
+                    q.setBody(changeCloze(q.getBody()));
+                }
+            }
+        }
+        return ret;
+    }
+
+    private String changeCloze(String text) {
+        StringBuffer buffer = new StringBuffer();
         String regex = "<fillblank/>";
 
         Pattern pattern = Pattern.compile(regex);
         Matcher matcher = pattern.matcher(text);
         // 使用find()方法查找匹配项
-        int num=0;
+        int num = 0;
         while (matcher.find()) {
-        	num++;
-        	matcher.appendReplacement(buffer, "___"+num+"___");
+            num++;
+            matcher.appendReplacement(buffer, "___" + num + "___");
         }
         matcher.appendTail(buffer);
         return buffer.toString();
-	}
-	
-	private KdQuestion of(QuestionVo vo) {
-		KdQuestion q=new KdQuestion();
-		q.setCusType(vo.getqType());
-		q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
-		if(QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			List<KdQuesOption> options=new ArrayList<>();
-			q.setOptions(options);
-			int num=0;
-			boolean cel=false;
-			for(String a:vo.getAnswer().getSubArea()) {
-				num++;
-				KdQuesOption o=new KdQuesOption();
-				options.add(o);
-				o.setNumber(num);
-				o.setBody(a);
-				o.setSelect(vo.getAnswer().getAnswer().contains(""+(num-1)));
-				if(o.getSelect()) {
-					cel=true;
-				}
-			}
-			if(!cel) {
-				throw new StatusException("没有答案");
-			}
-		}
-		if(!QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-			q.setAnswer(StringUtils.join(vo.getAnswer().getAnswer(),""));
-		}
-		q.setPid(vo.getPid());
-		q.setPname(vo.getPname());
-		q.setTname(vo.getTname());
-		q.setCname(vo.getCname());
-		q.setTypeId(vo.getTypeId());
-		q.setDetailName(vo.getTypeName());
-		q.setBody(vo.getBody());
-		if("101-204".equals(q.getTname())) {
-			q.setDifficultyDegree(YunkaiDifficulty.JIAORONGYI.getType());
-		}else if("301-404".equals(q.getTname())) {
-			q.setDifficultyDegree(YunkaiDifficulty.ZHONGDENG.getType());
-		}else if("501-504".equals(q.getTname())) {
-			q.setDifficultyDegree(YunkaiDifficulty.JIAONAN.getType());
-		}else {
-			if(StringUtils.isBlank(q.getPid())) {
-				throw new StatusException("错误");
-			}
-		}
-		q.setHaveAudio(false);
-		q.setId(vo.getQid());
-		q.setScore(1.0);
-		return q;
-	}
-
-	private List<QuestionVo> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
-		List<QuestionVo> qs = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select p.name pname,t.name tname,c.name cname, "
-					+" q.TYPE_ID typeId,f.name typeName,f.ANSWER_TYPE qType "
-					+" ,q.ID qid,q.TITLE body,q.FATHER_ID pid  "
-					+" ,q.answer,q.SHOW_ORDER seq    "
-					+" from pe_question_bank t  "
-					+" INNER JOIN pe_question_bank p on p.id=t.parent_id "
-					+" INNER JOIN pe_question_bank c on c.parent_id=t.id "
-					+" INNER JOIN pe_questions q on c.id=q.BANK_ID "
-					+" INNER JOIN pe_question_type f on f.id=q.TYPE_ID "
-					+" where t.name in('101-204','301-404','501-504') and c.name in('难度:1','难度:2') "
-					+" order by p.name,t.name,c.name ";
-
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				QuestionVo q = new QuestionVo();
-				q.setPname(resultSet.getString("pname"));
-				q.setTname(resultSet.getString("tname"));
-				q.setCname(resultSet.getString("cname"));
-				q.setQid(resultSet.getString("qid"));
-				q.setTypeId(resultSet.getString("typeId"));
-				q.setTypeName(resultSet.getString("typeName"));
-				q.setPid(resultSet.getString("pid"));
-				q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
-				q.setBody(disposeImg(resultSet.getString("body"), courseCode));
-				q.setAnswer(JSONObject.parseObject(resultSet.getString("answer"), AnswerVo.class));
-				q.setSeq(resultSet.getInt("seq"));
-				qs.add(q);
-			}
-			return qs;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-
-	private List<QuestionVo> getSubQuestion(Connection connect, String courseCode, List<String> pids)
-			throws SQLException, IOException {
-		List<QuestionVo> qs = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select f.name typeName,f.ANSWER_TYPE qType " + " ,q.ID qid,q.TITLE body,q.FATHER_ID pid "
-					+ " ,q.answer,q.SHOW_ORDER seq  " + " from  pe_questions q  "
-					+ " INNER JOIN pe_question_type f on f.id=q.TYPE_ID " + " where q.FATHER_ID in ('"
-					+ StringUtils.join(pids, "','") + "') order by q.SHOW_ORDER";
-
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				QuestionVo q = new QuestionVo();
-				q.setQid(resultSet.getString("qid"));
-				q.setTypeName(resultSet.getString("typeName"));
-				q.setPid(resultSet.getString("pid"));
-				q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
-				q.setBody(disposeImg(resultSet.getString("body"), courseCode));
-				q.setAnswer(JSONObject.parseObject(resultSet.getString("answer"), AnswerVo.class));
-				q.setSeq(resultSet.getInt("seq"));
-				qs.add(q);
-			}
-			return qs;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-
-	private String disposeImg(String str, String courseCode) {
-		if (StringUtils.isBlank(str)) {
-			return str;
-		}
-		Matcher matcher = imgPat.matcher(str);
-		Map<String, String> srcMap = new HashMap<>();
-		while (matcher.find()) {
-			String imgSrc = matcher.group(1).trim();
-			if (imgSrc.toLowerCase().trim().startsWith("http")) {
-				if (srcMap.get(imgSrc) == null) {
-					String suff = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toLowerCase();
-					File img = new File(paperDir + courseCode + "/" + UUID.randomUUID() + "." + suff);
-					FileUtil.saveUrlAs(imgSrc, img.getAbsolutePath());
-					String base64 = FileUtil.fileToBase64Src(img);
-					img.delete();
-					srcMap.put(imgSrc, base64);
-				}
-			}
-		}
-		for (String imgSrc : srcMap.keySet()) {
-			str = str.replaceAll(imgSrc, srcMap.get(imgSrc));
-		}
-		return str;
-	}
-
-
-	private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
-		List<QuestionVo> vos = getQuestion(connect, dto.getCourseCode());
-		if (CollectionUtils.isEmpty(vos)) {
-			return;
-		}
-		List<String> pids = vos.stream().filter(e -> e.getqType().getTypeId() == 6).map(QuestionVo::getQid)
-				.collect(Collectors.toList());
-		List<QuestionVo> subvos = getSubQuestion(connect, dto.getCourseCode(),pids);
-		List<KdQuestion> qs=of(vos,subvos);
-//		fillProp(connect, qs);
-//		fillAnswer(connect, qs, dto.getCourseCode());
-
-		Map<DetailDto2, List<KdQuestion>> qmap = new HashMap<>();
-		for (KdQuestion q : qs) {
-			DetailDto2 tem=new DetailDto2(q.getPname(),q.getTname());
-			List<KdQuestion> list = qmap.get(tem);
-			if (list == null) {
-				list = new ArrayList<>();
-				qmap.put(tem, list);
-			}
-			list.add(q);
-		}
-		for (DetailDto2 qt : qmap.keySet()) {
-			createPapers(qmap.get(qt), qt, dto);
-		}
-	}
-
-	private void createPapers(List<KdQuestion> qs, DetailDto2 qt, PaperExportDto dto) {
-		if (qs == null || qs.size() == 0) {
-			return;
-		}
-		if (qs.size() <= maxqc) {
-			createPaper(qs, qt, dto, 1);
-		} else {
-			int size = qs.size();
-			int len = maxqc;
-			int count = (size + len - 1) / len;
-
-			for (int i = 0; i < count; i++) {
-				List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
-				createPaper(subList, qt, dto, i + 1);
-			}
-		}
-
-	}
-
-	private void createPaper(List<KdQuestion> qs, DetailDto2 qt, PaperExportDto dto, int indx) {
-		if (qs.size() == 0) {
-			return;
-		}
-		double score=0.0;
-		int unit=0;
-		for(KdQuestion q:qs) {
-			if(CollectionUtils.isNotEmpty(q.getSubQuestions())) {
-				unit=unit+q.getSubQuestions().size();
-			}else {
-				unit++;
-			}
-			score=Calculator.add(score, q.getScore(),1);
-		}
-		String detailName = qt.getPname();
-		KdPaper paper = new KdPaper();
-		paper.setDetailCount(1);
-		paper.setUnitCount(unit);
-		paper.setTotalScore(score);
-//		paper.setName(dto.getPaperSuff() + qt.getPname()+qt.getTname() + "_" + indx);
-		paper.setName(dto.getPaperSuff() + qt.getPname()+qt.getTname());
-		paper.setCourseCode(dto.getCourseCode());
-		List<KdDetail> des = new ArrayList<>();
-		KdDetail d = new KdDetail();
-		d.setName(detailName);
-		d.setNumber(1);
-		d.setQuestionCount(unit);
-		d.setTotalScore(score);
-		d.setQuestions(qs);
-		des.add(d);
-		paper.setDetails(des);
-		paper.setDetailCount(1);
-		paper.setUnitCount(qs.size());
-		try {
-			File paperdir = new File(paperDir + dto.getCourseCode() + "/" + MD5Util.encoder(qt.getPname()+qt.getTname())+ "/");
-			paperdir.mkdirs();
-			FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper.json", JSONObject.toJSONString(paper));
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		} catch (NoSuchAlgorithmException e) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	@Override
-	public void initResult() {
-
-	}
+    }
+
+    private KdQuestion of(QuestionVo vo) {
+        KdQuestion q = new KdQuestion();
+        q.setCusType(vo.getqType());
+        q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
+        if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            List<KdQuesOption> options = new ArrayList<>();
+            q.setOptions(options);
+            int num = 0;
+            boolean cel = false;
+            for (String a : vo.getAnswer().getSubArea()) {
+                num++;
+                KdQuesOption o = new KdQuesOption();
+                options.add(o);
+                o.setNumber(num);
+                o.setBody(a);
+                o.setSelect(vo.getAnswer().getAnswer().contains("" + (num - 1)));
+                if (o.getSelect()) {
+                    cel = true;
+                }
+            }
+            if (!cel) {
+                throw new StatusException("没有答案");
+            }
+        }
+        if (!QuesStructType.NESTED_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+            q.setAnswer(StringUtils.join(vo.getAnswer().getAnswer(), ""));
+        }
+        q.setPid(vo.getPid());
+        q.setPname(vo.getPname());
+        q.setTname(vo.getTname());
+        q.setCname(vo.getCname());
+        q.setTypeId(vo.getTypeId());
+        q.setDetailName(vo.getTypeName());
+        q.setBody(vo.getBody());
+        if ("101-204".equals(q.getTname())) {
+            q.setDifficultyDegree(YunkaiDifficulty.JIAORONGYI.getType());
+        } else if ("301-404".equals(q.getTname())) {
+            q.setDifficultyDegree(YunkaiDifficulty.ZHONGDENG.getType());
+        } else if ("501-504".equals(q.getTname())) {
+            q.setDifficultyDegree(YunkaiDifficulty.JIAONAN.getType());
+        } else {
+            if (StringUtils.isBlank(q.getPid())) {
+                throw new StatusException("错误");
+            }
+        }
+        q.setHaveAudio(false);
+        q.setId(vo.getQid());
+        q.setScore(1.0);
+        return q;
+    }
+
+    private List<QuestionVo> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
+        List<QuestionVo> qs = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select p.name pname,t.name tname,c.name cname, "
+                    + " q.TYPE_ID typeId,f.name typeName,f.ANSWER_TYPE qType "
+                    + " ,q.ID qid,q.TITLE body,q.FATHER_ID pid  " + " ,q.answer,q.SHOW_ORDER seq    "
+                    + " from pe_question_bank t  " + " INNER JOIN pe_question_bank p on p.id=t.parent_id "
+                    + " INNER JOIN pe_question_bank c on c.parent_id=t.id "
+                    + " INNER JOIN pe_questions q on c.id=q.BANK_ID "
+                    + " INNER JOIN pe_question_type f on f.id=q.TYPE_ID "
+                    + " where t.name in('101-204','301-404','501-504') and c.name in('难度:1','难度:2') "
+                    + " order by p.name,t.name,c.name ";
+
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                QuestionVo q = new QuestionVo();
+                q.setPname(resultSet.getString("pname"));
+                q.setTname(resultSet.getString("tname"));
+                q.setCname(resultSet.getString("cname"));
+                q.setQid(resultSet.getString("qid"));
+                q.setTypeId(resultSet.getString("typeId"));
+                q.setTypeName(resultSet.getString("typeName"));
+                q.setPid(resultSet.getString("pid"));
+                q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
+                q.setBody(disposeImg(resultSet.getString("body"), courseCode));
+                q.setAnswer(JSONObject.parseObject(resultSet.getString("answer"), AnswerVo.class));
+                q.setSeq(resultSet.getInt("seq"));
+                qs.add(q);
+            }
+            return qs;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private List<QuestionVo> getSubQuestion(Connection connect, String courseCode, List<String> pids)
+            throws SQLException, IOException {
+        List<QuestionVo> qs = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select f.name typeName,f.ANSWER_TYPE qType " + " ,q.ID qid,q.TITLE body,q.FATHER_ID pid "
+                    + " ,q.answer,q.SHOW_ORDER seq  " + " from  pe_questions q  "
+                    + " INNER JOIN pe_question_type f on f.id=q.TYPE_ID " + " where q.FATHER_ID in ('"
+                    + StringUtils.join(pids, "','") + "') order by q.SHOW_ORDER";
+
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                QuestionVo q = new QuestionVo();
+                q.setQid(resultSet.getString("qid"));
+                q.setTypeName(resultSet.getString("typeName"));
+                q.setPid(resultSet.getString("pid"));
+                q.setqType(CusQuesStructType.valueOf(resultSet.getString("qType")));
+                q.setBody(disposeImg(resultSet.getString("body"), courseCode));
+                q.setAnswer(JSONObject.parseObject(resultSet.getString("answer"), AnswerVo.class));
+                q.setSeq(resultSet.getInt("seq"));
+                qs.add(q);
+            }
+            return qs;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private String disposeImg(String str, String courseCode) {
+        if (StringUtils.isBlank(str)) {
+            return str;
+        }
+        Matcher matcher = imgPat.matcher(str);
+        Map<String, String> srcMap = new HashMap<>();
+        while (matcher.find()) {
+            String imgSrc = matcher.group(1).trim();
+            if (imgSrc.toLowerCase().trim().startsWith("http")) {
+                if (srcMap.get(imgSrc) == null) {
+                    String suff = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toLowerCase();
+                    File img = new File(paperDir + courseCode + "/" + UUID.randomUUID() + "." + suff);
+                    FileUtil.saveUrlAs(imgSrc, img.getAbsolutePath());
+                    String base64 = FileUtil.fileToBase64Src(img);
+                    img.delete();
+                    srcMap.put(imgSrc, base64);
+                }
+            }
+        }
+        for (String imgSrc : srcMap.keySet()) {
+            str = str.replaceAll(imgSrc, srcMap.get(imgSrc));
+        }
+        return str;
+    }
+
+    private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
+        List<QuestionVo> vos = getQuestion(connect, dto.getCourseCode());
+        if (CollectionUtils.isEmpty(vos)) {
+            return;
+        }
+        List<String> pids = vos.stream().filter(e -> e.getqType().getTypeId() == 6).map(QuestionVo::getQid)
+                .collect(Collectors.toList());
+        List<QuestionVo> subvos = getSubQuestion(connect, dto.getCourseCode(), pids);
+        List<KdQuestion> qs = of(vos, subvos);
+        // fillProp(connect, qs);
+        // fillAnswer(connect, qs, dto.getCourseCode());
+
+        Map<DetailDto2, List<KdQuestion>> qmap = new HashMap<>();
+        for (KdQuestion q : qs) {
+            DetailDto2 tem = new DetailDto2(q.getPname(), q.getTname());
+            List<KdQuestion> list = qmap.get(tem);
+            if (list == null) {
+                list = new ArrayList<>();
+                qmap.put(tem, list);
+            }
+            list.add(q);
+        }
+        for (DetailDto2 qt : qmap.keySet()) {
+            createPapers(qmap.get(qt), qt, dto);
+        }
+    }
+
+    private void createPapers(List<KdQuestion> qs, DetailDto2 qt, PaperExportDto dto) {
+        if (qs == null || qs.size() == 0) {
+            return;
+        }
+        if (qs.size() <= maxqc) {
+            createPaper(qs, qt, dto, 1);
+        } else {
+            int size = qs.size();
+            int len = maxqc;
+            int count = (size + len - 1) / len;
+
+            for (int i = 0; i < count; i++) {
+                List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
+                createPaper(subList, qt, dto, i + 1);
+            }
+        }
+
+    }
+
+    private void createPaper(List<KdQuestion> qs, DetailDto2 qt, PaperExportDto dto, int indx) {
+        if (qs.size() == 0) {
+            return;
+        }
+        double score = 0.0;
+        int unit = 0;
+        for (KdQuestion q : qs) {
+            if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
+                unit = unit + q.getSubQuestions().size();
+            } else {
+                unit++;
+            }
+            score = Calculator.add(score, q.getScore(), 1);
+        }
+        String detailName = qt.getPname();
+        KdPaper paper = new KdPaper();
+        paper.setDetailCount(1);
+        paper.setUnitCount(unit);
+        paper.setTotalScore(score);
+        // paper.setName(dto.getPaperSuff() + qt.getPname()+qt.getTname() + "_"
+        // + indx);
+        paper.setName(Param.paperPrefix + qt.getPname() + qt.getTname());
+        paper.setCourseCode(dto.getCourseCode());
+        List<KdDetail> des = new ArrayList<>();
+        KdDetail d = new KdDetail();
+        d.setName(detailName);
+        d.setNumber(1);
+        d.setQuestionCount(unit);
+        d.setTotalScore(score);
+        d.setQuestions(qs);
+        des.add(d);
+        paper.setDetails(des);
+        paper.setDetailCount(1);
+        paper.setUnitCount(qs.size());
+        try {
+            File paperdir = new File(
+                    paperDir + dto.getCourseCode() + "/" + MD5Util.encoder(qt.getPname() + qt.getTname()) + "/");
+            paperdir.mkdirs();
+            FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper.json", JSONObject.toJSONString(paper));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void initResult() {
+
+    }
 }

+ 408 - 409
src/main/java/cn/com/qmth/export/MyConsumer3.java

@@ -23,413 +23,412 @@ import org.apache.commons.lang3.StringUtils;
 import com.alibaba.fastjson.JSONObject;
 
 public class MyConsumer3 extends Consumer<PaperExportDto> {
-//	private static String[] sucStr = new String[] { "对", "正确", "√", "是", "True" };
-//	private static String[] errStr = new String[] { "错", "错误", "×", "不正确", "否", "False" };
-//	private static String paperSuff = "(231205)";
-	private int maxqc = 200000;
-
-	private static String paperDir = "d:/guangkai/paper/";
-	private static String imgDir = "d:/guangkai/files/";
-
-	private static Pattern imgPat = Pattern.compile("<img[^<]+src=['\"]([^<\"]+)['\"][^<]*>");
-	
-//	private Pattern xieGangPat = Pattern.compile("\\\\([^\"]|(\",))");
-
-	@Override
-	public void consume(PaperExportDto dto) {
-		Connection connect = null;
-		File sub = new File(paperDir + dto.getCourseCode() + "/");
-		sub.mkdir();
-		try {
-			Class.forName("com.mysql.cj.jdbc.Driver");
-
-			String url = "jdbc:mysql://localhost:3306/" + dto.getDbName() + "?serverTimezone=GMT%2B8";
-
-			String user = "root";
-
-			String password = "123456";
-			connect = DriverManager.getConnection(url, user, password);
-			exportPaper(connect, dto);
-			GkExportPaperByCourseCode.addDisposeCount();
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (connect != null) {
-				try {
-					connect.close();
-				} catch (SQLException e) {
-				}
-			}
-		}
-	}
-
-	private List<KdQuestion> of(List<QuestionVo3> vos) {
-		List<KdQuestion> ret = new ArrayList<>();
-		for (QuestionVo3 vo : vos) {
-			try {
-				KdQuestion q = of(vo);
-				ret.add(q);
-			} catch (StatusException e) {
-				GkExportPaperByCourseCode.addValid();
-				continue;
-			}
-		}
-		return ret;
-	}
-
-
-
-	private KdQuestion of(QuestionVo3 vo) {
-		KdQuestion q = new KdQuestion();
-		q.setPropIds(new ArrayList<>());
-		q.getPropIds().add(vo.getCategory());
-		q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
-		q.setBody(vo.getBody());
-		q.setDifficultyDegree(0.5);
-		q.setHaveAudio(false);
-		q.setId(vo.getQid().toString());
-		q.setScore(1.0);
-		return q;
-	}
-
-	private List<QuestionVo3> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
-		List<QuestionVo3> qs = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select q.* from mdl_course c "
-					+" inner join mdl_context ct on ct.instanceid=c.id "
-					+" inner join mdl_question_categories qc on qc.contextid=ct.id "
-					+" inner join mdl_question q on q.category=qc.id "
-					+" where c.idnumber='"+courseCode+"' and q.qtype in('multichoice','multichoiceset','truefalse') "
-					+" and q.parent=0 ";
-
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				QuestionVo3 q = new QuestionVo3();
-				q.setQid(resultSet.getLong("id"));
-				q.setPid(resultSet.getLong("parent"));
-				q.setCategory(resultSet.getLong("category"));
-				q.setqType(CusQuesStructType3.valueOf(resultSet.getString("qType")));
-				q.setBody(resultSet.getString("questiontext"));
-				qs.add(q);
-			}
-			return qs;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	
-	
-//	public static void main(String[] args) {
-//		String s="a\"\\\",b\\h";
-//		System.out.println(s);
-//		System.out.println(fomat(s));
-//	}
-	
-	
-
-	private void disposeQuestionImg(Connection connect,String courseCode,KdQuestion q) throws NumberFormatException, SQLException {
-		q.setBody(disposeImg(connect, courseCode, "questiontext", q.getBody(), Long.valueOf(q.getId())));
-		if (CollectionUtils.isNotEmpty(q.getOptions())) {
-			for (KdQuesOption o : q.getOptions()) {
-				o.setBody(disposeImg(connect, courseCode, "answer", o.getBody(), Long.valueOf(o.getId())));
-			}
-		}
-	}
-
-	private String disposeImg(Connection connect,String courseCode,String filearea,String str, Long itemId) throws SQLException {
-		if (StringUtils.isBlank(str)) {
-			return str;
-		}
-		Matcher matcher = imgPat.matcher(str);
-		Map<String, String> srcMap = new HashMap<>();
-		while (matcher.find()) {
-			String imgSrc = matcher.group(1).trim();
-			if (imgSrc.startsWith("data:image/")) {
-
-			} else if (imgSrc.startsWith("@@PLUGINFILE@@")) {
-				if (srcMap.get(imgSrc) == null) {
-					File img = getImage(connect, imgSrc, courseCode, itemId, filearea);
-					String base64 = FileUtil.fileToBase64Src(img);
-					srcMap.put(imgSrc, base64);
-				}
-			}else {
-				throw new StatusException("图片有误:" + itemId);
-			}
-		}
-		for (String imgSrc : srcMap.keySet()) {
-			str = str.replaceAll(imgSrc.replaceAll("\\?", "\\\\?"), srcMap.get(imgSrc));
-		}
-		return str;
-	}
-	
-	
-	
-	private File getImage(Connection connect,String imgSrc,String courseCode,Long itemId,String filearea) throws SQLException {
-		String fileName=getFileName(imgSrc);
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String hash = null;
-			int count=0;
-			String sql = " select * from mdl_files where itemid = " + itemId + " and source='" + fileName
-					+ "' and component = 'question' and filearea = '"+filearea+"' ";
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				count++;
-				hash = resultSet.getString("contenthash");
-			}
-			if(count!=1) {
-				throw new StatusException("图片有误:" + itemId+filearea);
-			}
-			String suff = fileName.substring(fileName.lastIndexOf("."));
-			File file = new File(imgDir + courseCode + "/" + hash + suff);
-			if (!file.exists()) {
-				throw new StatusException("图片有误:" + itemId+filearea);
-			}
-			return file;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	private String getFileName(String s) {
-		int end = s.length();
-		int f = s.indexOf("?");
-		if (f != -1) {
-			end = f;
-		}
-		try {
-			return URLDecoder.decode(s.substring(s.lastIndexOf("/") + 1, end), "utf-8");
-		} catch (UnsupportedEncodingException e) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
-		List<QuestionVo3> vos = getQuestion(connect, dto.getCourseCode());
-		if (CollectionUtils.isEmpty(vos)) {
-			return;
-		}
-		List<KdQuestion> qs = of(vos);
-		fillAnswer(connect, qs, dto.getCourseCode());
-
-		Map<QuesStructType, List<KdQuestion>> qmap = new HashMap<>();
-		for (KdQuestion q : qs) {
-			if(q.isValid()) {
-				List<KdQuestion> list = qmap.get(q.getQuesStructType());
-				if (list == null) {
-					list = new ArrayList<>();
-					qmap.put(q.getQuesStructType(), list);
-				}
-				list.add(q);
-			}
-		}
-		for (QuesStructType qt : qmap.keySet()) {
-			createPapers(qmap.get(qt), qt, dto);
-		}
-	}
-
-	private void fillAnswer(Connection connect, List<KdQuestion> qs, String courseCode) throws NumberFormatException, SQLException {
-		List<Answer> qps = new BatchGetDataUtil<Answer, KdQuestion>() {
-
-			@Override
-			protected List<Answer> getData(List<KdQuestion> paramList) {
-				return getAnswerBatch(connect, paramList);
-			}
-		}.getDataForBatch(qs, 200);
-		if (CollectionUtils.isEmpty(qps)) {
-			return;
-		}
-
-		Map<Long, List<Answer>> map = new HashMap<>();
-		for (Answer qp : qps) {
-			List<Answer> list = map.get(qp.getQuestionId());
-			if (list == null) {
-				list = new ArrayList<>();
-				map.put(qp.getQuestionId(), list);
-			}
-			list.add(qp);
-		}
-
-		for (KdQuestion q : qs) {
-			try {
-				List<Answer> as=map.get(Long.valueOf(q.getId()));
-				if (CollectionUtils.isEmpty(as)) {
-					throw new StatusException("没有答案:"+q.getId());
-				}
-				if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-					List<KdQuesOption> options = new ArrayList<>();
-					q.setOptions(options);
-					int num = 0;
-					int answerCount = 0;
-					for (Answer a : as) {
-						num++;
-						KdQuesOption o = new KdQuesOption();
-						options.add(o);
-						o.setId(a.getaId());
-						o.setNumber(num);
-						o.setBody(a.getBody());
-						o.setSelect(a.getFraction()>0);
-						if (o.getSelect()) {
-							answerCount++;
-						}
-					}
-					if (answerCount == 0) {
-						throw new StatusException("没有答案:"+q.getId());
-					}
-					if (answerCount > 1) {
-						q.setQuesStructType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
-					}
-				} else if (QuesStructType.BOOL_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-					for (Answer a : as) {
-						if (a.getFraction() > 0) {
-							q.setAnswer("对".equals(a.getBody().trim()) ? "正确" : "错误");
-							break;
-						}
-					}
-					if(StringUtils.isBlank(q.getAnswer())) {
-						throw new StatusException("答案有误:"+q.getId());
-					}
-				} else {
-					throw new StatusException("题型有误:"+q.getId());
-				}
-			}catch (StatusException e) {
-				GkExportPaperByCourseCode3.addValid();
-				q.setValid(false);
-				continue;
-			}
-			try {
-				disposeQuestionImg(connect, courseCode, q);
-			} catch (StatusException e) {
-				GkExportPaperByCourseCode3.addImgValid();
-				q.setValid(false);
-				continue;
-			}
-		}
-		
-	}
-
-
-
-
-	private List<Answer> getAnswerBatch(Connection connect, List<KdQuestion> qs) {
-		List<Answer> as = new ArrayList<>();
-		List<Long> ids = qs.stream().map(e -> Long.valueOf(e.getId())).collect(Collectors.toList());
-		String idsstr = StringUtils.join(ids, ",");
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select t.id,t.question,t.answer,t.fraction  from mdl_question_answers t "
-					+ " where t.question in (" + idsstr + ")  ";
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				Answer a = new Answer();
-				a.setBody(resultSet.getString("answer"));
-				a.setFraction(resultSet.getDouble("fraction"));
-				a.setQuestionId(resultSet.getLong("question"));
-				a.setaId(resultSet.getLong("id"));
-				as.add(a);
-			}
-			return as;
-		} catch (Exception e1) {
-			throw new RuntimeException(e1);
-		} finally {
-			if (resultSet != null) {
-				try {
-					resultSet.close();
-				} catch (SQLException e1) {
-				}
-			}
-			if (preState != null) {
-				try {
-					preState.close();
-				} catch (SQLException e1) {
-				}
-			}
-		}
-	}
-	private void createPapers(List<KdQuestion> qs, QuesStructType qt, PaperExportDto dto) {
-		if (qs == null || qs.size() == 0) {
-			return;
-		}
-		if (qs.size() <= maxqc) {
-			createPaper(qs, qt, dto, 1);
-		} else {
-			int size = qs.size();
-			int len = maxqc;
-			int count = (size + len - 1) / len;
-
-			for (int i = 0; i < count; i++) {
-				List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
-				createPaper(subList, qt, dto, i + 1);
-			}
-		}
-
-	}
-
-	private void createPaper(List<KdQuestion> qs, QuesStructType qt, PaperExportDto dto, int indx) {
-		if (qs.size() == 0) {
-			return;
-		}
-		double score = 0.0;
-		int unit = 0;
-		for (KdQuestion q : qs) {
-			if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
-				unit = unit + q.getSubQuestions().size();
-			} else {
-				unit++;
-			}
-			score = Calculator.add(score, q.getScore(), 1);
-		}
-		String detailName = qt.getName();
-		KdPaper paper = new KdPaper();
-		paper.setDetailCount(1);
-		paper.setUnitCount(unit);
-		paper.setTotalScore(score);
-		paper.setName(dto.getPaperSuff() + detailName + "_" + indx);
-		paper.setCourseCode(dto.getCourseCode());
-		List<KdDetail> des = new ArrayList<>();
-		KdDetail d = new KdDetail();
-		d.setName(detailName);
-		d.setNumber(1);
-		d.setQuestionCount(unit);
-		d.setTotalScore(score);
-		d.setQuestions(qs);
-		des.add(d);
-		paper.setDetails(des);
-		paper.setDetailCount(1);
-		paper.setUnitCount(qs.size());
-		File paperdir = new File(paperDir + dto.getCourseCode() + "/" + qt.getId() + "/");
-		paperdir.mkdirs();
-		try {
-			FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper_" + indx + ".json", JSONObject.toJSONString(paper));
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	@Override
-	public void initResult() {
-
-	}
+
+    // private static String[] sucStr = new String[] { "对", "正确", "√", "是",
+    // "True" };
+    // private static String[] errStr = new String[] { "错", "错误", "×", "不正确",
+    // "否", "False" };
+    // private static String paperSuff = "(231205)";
+    private int maxqc = 200000;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    private static String imgDir = Param.dataDir + "questionfile/files/";
+
+    private static Pattern imgPat = Pattern.compile("<img[^<]+src=['\"]([^<\"]+)['\"][^<]*>");
+
+    // private Pattern xieGangPat = Pattern.compile("\\\\([^\"]|(\",))");
+
+    @Override
+    public void consume(PaperExportDto dto) {
+        Connection connect = null;
+        File sub = new File(paperDir + dto.getCourseCode() + "/");
+        sub.mkdir();
+        try {
+            Class.forName("com.mysql.cj.jdbc.Driver");
+
+            String url = "jdbc:mysql://localhost:3306/" + Param.dbName + "?serverTimezone=GMT%2B8";
+
+            String user = Param.dbUser;
+
+            String password = Param.dbPass;
+            connect = DriverManager.getConnection(url, user, password);
+            exportPaper(connect, dto);
+            GkExportPaperByCourseCode.addDisposeCount();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (connect != null) {
+                try {
+                    connect.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    private List<KdQuestion> of(List<QuestionVo3> vos) {
+        List<KdQuestion> ret = new ArrayList<>();
+        for (QuestionVo3 vo : vos) {
+            try {
+                KdQuestion q = of(vo);
+                ret.add(q);
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode.addValid();
+                continue;
+            }
+        }
+        return ret;
+    }
+
+    private KdQuestion of(QuestionVo3 vo) {
+        KdQuestion q = new KdQuestion();
+        q.setPropIds(new ArrayList<>());
+        q.getPropIds().add(vo.getCategory());
+        q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
+        q.setBody(vo.getBody());
+        q.setDifficultyDegree(0.5);
+        q.setHaveAudio(false);
+        q.setId(vo.getQid().toString());
+        q.setScore(1.0);
+        return q;
+    }
+
+    private List<QuestionVo3> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
+        List<QuestionVo3> qs = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select q.* from mdl_course c " + " inner join mdl_context ct on ct.instanceid=c.id "
+                    + " inner join mdl_question_categories qc on qc.contextid=ct.id "
+                    + " inner join mdl_question q on q.category=qc.id " + " where c.idnumber='" + courseCode
+                    + "' and q.qtype in('multichoice','multichoiceset','truefalse') " + " and q.parent=0 ";
+
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                QuestionVo3 q = new QuestionVo3();
+                q.setQid(resultSet.getLong("id"));
+                q.setPid(resultSet.getLong("parent"));
+                q.setCategory(resultSet.getLong("category"));
+                q.setqType(CusQuesStructType3.valueOf(resultSet.getString("qType")));
+                q.setBody(resultSet.getString("questiontext"));
+                qs.add(q);
+            }
+            return qs;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    // public static void main(String[] args) {
+    // String s="a\"\\\",b\\h";
+    // System.out.println(s);
+    // System.out.println(fomat(s));
+    // }
+
+    private void disposeQuestionImg(Connection connect, String courseCode, KdQuestion q)
+            throws NumberFormatException, SQLException {
+        q.setBody(disposeImg(connect, courseCode, "questiontext", q.getBody(), Long.valueOf(q.getId())));
+        if (CollectionUtils.isNotEmpty(q.getOptions())) {
+            for (KdQuesOption o : q.getOptions()) {
+                o.setBody(disposeImg(connect, courseCode, "answer", o.getBody(), Long.valueOf(o.getId())));
+            }
+        }
+    }
+
+    private String disposeImg(Connection connect, String courseCode, String filearea, String str, Long itemId)
+            throws SQLException {
+        if (StringUtils.isBlank(str)) {
+            return str;
+        }
+        Matcher matcher = imgPat.matcher(str);
+        Map<String, String> srcMap = new HashMap<>();
+        while (matcher.find()) {
+            String imgSrc = matcher.group(1).trim();
+            if (imgSrc.startsWith("data:image/")) {
+
+            } else if (imgSrc.startsWith("@@PLUGINFILE@@")) {
+                if (srcMap.get(imgSrc) == null) {
+                    File img = getImage(connect, imgSrc, courseCode, itemId, filearea);
+                    String base64 = FileUtil.fileToBase64Src(img);
+                    srcMap.put(imgSrc, base64);
+                }
+            } else {
+                throw new StatusException("图片有误:" + itemId);
+            }
+        }
+        for (String imgSrc : srcMap.keySet()) {
+            str = str.replaceAll(imgSrc.replaceAll("\\?", "\\\\?"), srcMap.get(imgSrc));
+        }
+        return str;
+    }
+
+    private File getImage(Connection connect, String imgSrc, String courseCode, Long itemId, String filearea)
+            throws SQLException {
+        String fileName = getFileName(imgSrc);
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String hash = null;
+            int count = 0;
+            String sql = " select * from mdl_files where itemid = " + itemId + " and source='" + fileName
+                    + "' and component = 'question' and filearea = '" + filearea + "' ";
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                count++;
+                hash = resultSet.getString("contenthash");
+            }
+            if (count != 1) {
+                throw new StatusException("图片有误:" + itemId + filearea);
+            }
+            String suff = fileName.substring(fileName.lastIndexOf("."));
+            File file = new File(imgDir + courseCode + "/" + hash + suff);
+            if (!file.exists()) {
+                throw new StatusException("图片有误:" + itemId + filearea);
+            }
+            return file;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private String getFileName(String s) {
+        int end = s.length();
+        int f = s.indexOf("?");
+        if (f != -1) {
+            end = f;
+        }
+        try {
+            return URLDecoder.decode(s.substring(s.lastIndexOf("/") + 1, end), "utf-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
+        List<QuestionVo3> vos = getQuestion(connect, dto.getCourseCode());
+        if (CollectionUtils.isEmpty(vos)) {
+            GkExportPaperByCourseCode3.addNoQues(dto.getCourseCode());
+            return;
+        }
+        List<KdQuestion> qs = of(vos);
+        fillAnswer(connect, qs, dto.getCourseCode());
+
+        Map<QuesStructType, List<KdQuestion>> qmap = new HashMap<>();
+        for (KdQuestion q : qs) {
+            if (q.isValid()) {
+                List<KdQuestion> list = qmap.get(q.getQuesStructType());
+                if (list == null) {
+                    list = new ArrayList<>();
+                    qmap.put(q.getQuesStructType(), list);
+                }
+                list.add(q);
+            }
+        }
+        for (QuesStructType qt : qmap.keySet()) {
+            createPapers(qmap.get(qt), qt, dto);
+        }
+    }
+
+    private void fillAnswer(Connection connect, List<KdQuestion> qs, String courseCode)
+            throws NumberFormatException, SQLException {
+        List<Answer> qps = new BatchGetDataUtil<Answer, KdQuestion>() {
+
+            @Override
+            protected List<Answer> getData(List<KdQuestion> paramList) {
+                return getAnswerBatch(connect, paramList);
+            }
+        }.getDataForBatch(qs, 200);
+        if (CollectionUtils.isEmpty(qps)) {
+            return;
+        }
+
+        Map<Long, List<Answer>> map = new HashMap<>();
+        for (Answer qp : qps) {
+            List<Answer> list = map.get(qp.getQuestionId());
+            if (list == null) {
+                list = new ArrayList<>();
+                map.put(qp.getQuestionId(), list);
+            }
+            list.add(qp);
+        }
+
+        for (KdQuestion q : qs) {
+            try {
+                List<Answer> as = map.get(Long.valueOf(q.getId()));
+                if (CollectionUtils.isEmpty(as)) {
+                    throw new StatusException("没有答案:" + q.getId());
+                }
+                if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+                    List<KdQuesOption> options = new ArrayList<>();
+                    q.setOptions(options);
+                    int num = 0;
+                    int answerCount = 0;
+                    for (Answer a : as) {
+                        num++;
+                        KdQuesOption o = new KdQuesOption();
+                        options.add(o);
+                        o.setId(a.getaId());
+                        o.setNumber(num);
+                        o.setBody(a.getBody());
+                        o.setSelect(a.getFraction() > 0);
+                        if (o.getSelect()) {
+                            answerCount++;
+                        }
+                    }
+                    if (answerCount == 0) {
+                        throw new StatusException("没有答案:" + q.getId());
+                    }
+                    if (answerCount > 1) {
+                        q.setQuesStructType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
+                    }
+                } else if (QuesStructType.BOOL_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+                    for (Answer a : as) {
+                        if (a.getFraction() > 0) {
+                            q.setAnswer("对".equals(a.getBody().trim()) ? "正确" : "错误");
+                            break;
+                        }
+                    }
+                    if (StringUtils.isBlank(q.getAnswer())) {
+                        throw new StatusException("答案有误:" + q.getId());
+                    }
+                } else {
+                    throw new StatusException("题型有误:" + q.getId());
+                }
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode3.addValid();
+                q.setValid(false);
+                continue;
+            }
+            try {
+                disposeQuestionImg(connect, courseCode, q);
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode3.addImgValid();
+                q.setValid(false);
+                continue;
+            }
+        }
+
+    }
+
+    private List<Answer> getAnswerBatch(Connection connect, List<KdQuestion> qs) {
+        List<Answer> as = new ArrayList<>();
+        List<Long> ids = qs.stream().map(e -> Long.valueOf(e.getId())).collect(Collectors.toList());
+        String idsstr = StringUtils.join(ids, ",");
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select t.id,t.question,t.answer,t.fraction  from mdl_question_answers t "
+                    + " where t.question in (" + idsstr + ")  ";
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                Answer a = new Answer();
+                a.setBody(resultSet.getString("answer"));
+                a.setFraction(resultSet.getDouble("fraction"));
+                a.setQuestionId(resultSet.getLong("question"));
+                a.setaId(resultSet.getLong("id"));
+                as.add(a);
+            }
+            return as;
+        } catch (Exception e1) {
+            throw new RuntimeException(e1);
+        } finally {
+            if (resultSet != null) {
+                try {
+                    resultSet.close();
+                } catch (SQLException e1) {
+                }
+            }
+            if (preState != null) {
+                try {
+                    preState.close();
+                } catch (SQLException e1) {
+                }
+            }
+        }
+    }
+
+    private void createPapers(List<KdQuestion> qs, QuesStructType qt, PaperExportDto dto) {
+        if (qs == null || qs.size() == 0) {
+            return;
+        }
+        if (qs.size() <= maxqc) {
+            createPaper(qs, qt, dto, 1);
+        } else {
+            int size = qs.size();
+            int len = maxqc;
+            int count = (size + len - 1) / len;
+
+            for (int i = 0; i < count; i++) {
+                List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
+                createPaper(subList, qt, dto, i + 1);
+            }
+        }
+
+    }
+
+    private void createPaper(List<KdQuestion> qs, QuesStructType qt, PaperExportDto dto, int indx) {
+        if (qs.size() == 0) {
+            return;
+        }
+        double score = 0.0;
+        int unit = 0;
+        for (KdQuestion q : qs) {
+            if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
+                unit = unit + q.getSubQuestions().size();
+            } else {
+                unit++;
+            }
+            score = Calculator.add(score, q.getScore(), 1);
+        }
+        String detailName = qt.getName();
+        KdPaper paper = new KdPaper();
+        paper.setDetailCount(1);
+        paper.setUnitCount(unit);
+        paper.setTotalScore(score);
+        paper.setName(Param.paperPrefix + detailName + "_" + indx);
+        paper.setCourseCode(dto.getCourseCode());
+        List<KdDetail> des = new ArrayList<>();
+        KdDetail d = new KdDetail();
+        d.setName(detailName);
+        d.setNumber(1);
+        d.setQuestionCount(unit);
+        d.setTotalScore(score);
+        d.setQuestions(qs);
+        des.add(d);
+        paper.setDetails(des);
+        paper.setDetailCount(1);
+        paper.setUnitCount(qs.size());
+        File paperdir = new File(paperDir + dto.getCourseCode() + "/" + qt.getId() + "/");
+        paperdir.mkdirs();
+        try {
+            FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper_" + indx + ".json", JSONObject.toJSONString(paper));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void initResult() {
+
+    }
 }

+ 412 - 413
src/main/java/cn/com/qmth/export/MyConsumer4.java

@@ -24,417 +24,416 @@ import org.apache.commons.lang3.StringUtils;
 import com.alibaba.fastjson.JSONObject;
 
 public class MyConsumer4 extends Consumer<PaperExportDto> {
-//	private static String[] sucStr = new String[] { "对", "正确", "√", "是", "True" };
-//	private static String[] errStr = new String[] { "错", "错误", "×", "不正确", "否", "False" };
-//	private static String paperSuff = "(231205)";
-	private int maxqc = 200000;
-
-	private static String paperDir = "d:/guangkai/paper/";
-	private static String imgDir = "d:/guangkai/files/";
-
-	private static Pattern imgPat = Pattern.compile("<img[^<]+src=['\"]([^<\"]+)['\"][^<]*>");
-	
-//	private Pattern xieGangPat = Pattern.compile("\\\\([^\"]|(\",))");
-
-	@Override
-	public void consume(PaperExportDto dto) {
-		Connection connect = null;
-		File sub = new File(paperDir + dto.getCourseCode() + "/");
-		sub.mkdir();
-		try {
-			Class.forName("com.mysql.cj.jdbc.Driver");
-
-			String url = "jdbc:mysql://localhost:3306/" + dto.getDbName() + "?serverTimezone=GMT%2B8";
-
-			String user = "root";
-
-			String password = "123456";
-			connect = DriverManager.getConnection(url, user, password);
-			exportPaper(connect, dto);
-			GkExportPaperByCourseCode.addDisposeCount();
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (connect != null) {
-				try {
-					connect.close();
-				} catch (SQLException e) {
-				}
-			}
-		}
-	}
-
-	private List<KdQuestion> of(List<QuestionVo4> vos) {
-		List<KdQuestion> ret = new ArrayList<>();
-		for (QuestionVo4 vo : vos) {
-			try {
-				KdQuestion q = of(vo);
-				ret.add(q);
-			} catch (StatusException e) {
-				GkExportPaperByCourseCode.addValid();
-				continue;
-			}
-		}
-		return ret;
-	}
-
-
-
-	private KdQuestion of(QuestionVo4 vo) {
-		KdQuestion q = new KdQuestion();
-		q.setPropIds(new ArrayList<>());
-		q.getPropIds().add(vo.getCategory());
-		q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
-		q.setBody(vo.getBody());
-		q.setDifficultyDegree(0.5);
-		q.setHaveAudio(false);
-		q.setId(vo.getQid().toString());
-		q.setScore(1.0);
-		q.setDetailName(vo.getCategoryName());
-		return q;
-	}
-
-	private List<QuestionVo4> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
-		List<QuestionVo4> qs = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select q.*,qc.name categoryName from mdl_course c "
-					+" inner join mdl_context ct on ct.instanceid=c.id "
-					+" inner join mdl_question_categories qc on qc.contextid=ct.id "
-					+" inner join mdl_question q on q.category=qc.id "
-					+" where c.idnumber='"+courseCode+"' and q.qtype in('multichoice','multichoiceset','truefalse') "
-					+" and q.parent=0 ";
-
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				QuestionVo4 q = new QuestionVo4();
-				q.setQid(resultSet.getLong("id"));
-				q.setPid(resultSet.getLong("parent"));
-				q.setCategory(resultSet.getLong("category"));
-				q.setCategoryName(resultSet.getString("categoryName"));
-				q.setqType(CusQuesStructType3.valueOf(resultSet.getString("qType")));
-				q.setBody(resultSet.getString("questiontext"));
-				qs.add(q);
-			}
-			return qs;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	
-	
-//	public static void main(String[] args) {
-//		String s="a\"\\\",b\\h";
-//		System.out.println(s);
-//		System.out.println(fomat(s));
-//	}
-	
-	
-
-	private void disposeQuestionImg(Connection connect,String courseCode,KdQuestion q) throws NumberFormatException, SQLException {
-		q.setBody(disposeImg(connect, courseCode, "questiontext", q.getBody(), Long.valueOf(q.getId())));
-		if (CollectionUtils.isNotEmpty(q.getOptions())) {
-			for (KdQuesOption o : q.getOptions()) {
-				o.setBody(disposeImg(connect, courseCode, "answer", o.getBody(), Long.valueOf(o.getId())));
-			}
-		}
-	}
-
-	private String disposeImg(Connection connect,String courseCode,String filearea,String str, Long itemId) throws SQLException {
-		if (StringUtils.isBlank(str)) {
-			return str;
-		}
-		Matcher matcher = imgPat.matcher(str);
-		Map<String, String> srcMap = new HashMap<>();
-		while (matcher.find()) {
-			String imgSrc = matcher.group(1).trim();
-			if (imgSrc.startsWith("data:image/")) {
-
-			} else if (imgSrc.startsWith("@@PLUGINFILE@@")) {
-				if (srcMap.get(imgSrc) == null) {
-					File img = getImage(connect, imgSrc, courseCode, itemId, filearea);
-					String base64 = FileUtil.fileToBase64Src(img);
-					srcMap.put(imgSrc, base64);
-				}
-			}else {
-				throw new StatusException("图片有误:" + itemId);
-			}
-		}
-		for (String imgSrc : srcMap.keySet()) {
-			str = str.replaceAll(imgSrc.replaceAll("\\?", "\\\\?"), srcMap.get(imgSrc));
-		}
-		return str;
-	}
-	
-	
-	
-	private File getImage(Connection connect,String imgSrc,String courseCode,Long itemId,String filearea) throws SQLException {
-		String fileName=getFileName(imgSrc);
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String hash = null;
-			int count=0;
-			String sql = " select * from mdl_files where itemid = " + itemId + " and source='" + fileName
-					+ "' and component = 'question' and filearea = '"+filearea+"' ";
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				count++;
-				hash = resultSet.getString("contenthash");
-			}
-			if(count!=1) {
-				throw new StatusException("图片有误:" + itemId+filearea);
-			}
-			String suff = fileName.substring(fileName.lastIndexOf("."));
-			File file = new File(imgDir + courseCode + "/" + hash + suff);
-			if (!file.exists()) {
-				throw new StatusException("图片有误:" + itemId+filearea);
-			}
-			return file;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	private String getFileName(String s) {
-		int end = s.length();
-		int f = s.indexOf("?");
-		if (f != -1) {
-			end = f;
-		}
-		try {
-			return URLDecoder.decode(s.substring(s.lastIndexOf("/") + 1, end), "utf-8");
-		} catch (UnsupportedEncodingException e) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
-		List<QuestionVo4> vos = getQuestion(connect, dto.getCourseCode());
-		if (CollectionUtils.isEmpty(vos)) {
-			return;
-		}
-		List<KdQuestion> qs = of(vos);
-		fillAnswer(connect, qs, dto.getCourseCode());
-
-		Map<DetailDto3, List<KdQuestion>> qmap = new HashMap<>();
-		for (KdQuestion q : qs) {
-			if(q.isValid()) {
-				DetailDto3 tem=new DetailDto3(null, q.getDetailName());
-				List<KdQuestion> list = qmap.get(tem);
-				if (list == null) {
-					tem.setTypeId(UUID.randomUUID().toString());
-					list = new ArrayList<>();
-					qmap.put(tem, list);
-				}
-				list.add(q);
-			}
-		}
-		for (DetailDto3 qt : qmap.keySet()) {
-			createPapers(qmap.get(qt), qt, dto);
-		}
-	}
-
-	private void fillAnswer(Connection connect, List<KdQuestion> qs, String courseCode) throws NumberFormatException, SQLException {
-		List<Answer> qps = new BatchGetDataUtil<Answer, KdQuestion>() {
-
-			@Override
-			protected List<Answer> getData(List<KdQuestion> paramList) {
-				return getAnswerBatch(connect, paramList);
-			}
-		}.getDataForBatch(qs, 200);
-		if (CollectionUtils.isEmpty(qps)) {
-			return;
-		}
-
-		Map<Long, List<Answer>> map = new HashMap<>();
-		for (Answer qp : qps) {
-			List<Answer> list = map.get(qp.getQuestionId());
-			if (list == null) {
-				list = new ArrayList<>();
-				map.put(qp.getQuestionId(), list);
-			}
-			list.add(qp);
-		}
-
-		for (KdQuestion q : qs) {
-			try {
-				List<Answer> as=map.get(Long.valueOf(q.getId()));
-				if (CollectionUtils.isEmpty(as)) {
-					throw new StatusException("没有答案:"+q.getId());
-				}
-				if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-					List<KdQuesOption> options = new ArrayList<>();
-					q.setOptions(options);
-					int num = 0;
-					int answerCount = 0;
-					for (Answer a : as) {
-						num++;
-						KdQuesOption o = new KdQuesOption();
-						options.add(o);
-						o.setId(a.getaId());
-						o.setNumber(num);
-						o.setBody(a.getBody());
-						o.setSelect(a.getFraction()>0);
-						if (o.getSelect()) {
-							answerCount++;
-						}
-					}
-					if (answerCount == 0) {
-						throw new StatusException("没有答案:"+q.getId());
-					}
-					if (answerCount > 1) {
-						q.setQuesStructType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
-					}
-				} else if (QuesStructType.BOOL_ANSWER_QUESTION.equals(q.getQuesStructType())) {
-					for (Answer a : as) {
-						if (a.getFraction() > 0) {
-							q.setAnswer("对".equals(a.getBody().trim()) ? "正确" : "错误");
-							break;
-						}
-					}
-					if(StringUtils.isBlank(q.getAnswer())) {
-						throw new StatusException("答案有误:"+q.getId());
-					}
-				} else {
-					throw new StatusException("题型有误:"+q.getId());
-				}
-			}catch (StatusException e) {
-				GkExportPaperByCourseCode3.addValid();
-				q.setValid(false);
-				continue;
-			}
-			try {
-				disposeQuestionImg(connect, courseCode, q);
-			} catch (StatusException e) {
-				GkExportPaperByCourseCode3.addImgValid();
-				q.setValid(false);
-				continue;
-			}
-		}
-		
-	}
-
-
-
-
-	private List<Answer> getAnswerBatch(Connection connect, List<KdQuestion> qs) {
-		List<Answer> as = new ArrayList<>();
-		List<Long> ids = qs.stream().map(e -> Long.valueOf(e.getId())).collect(Collectors.toList());
-		String idsstr = StringUtils.join(ids, ",");
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = " select t.id,t.question,t.answer,t.fraction  from mdl_question_answers t "
-					+ " where t.question in (" + idsstr + ")  ";
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				Answer a = new Answer();
-				a.setBody(resultSet.getString("answer"));
-				a.setFraction(resultSet.getDouble("fraction"));
-				a.setQuestionId(resultSet.getLong("question"));
-				a.setaId(resultSet.getLong("id"));
-				as.add(a);
-			}
-			return as;
-		} catch (Exception e1) {
-			throw new RuntimeException(e1);
-		} finally {
-			if (resultSet != null) {
-				try {
-					resultSet.close();
-				} catch (SQLException e1) {
-				}
-			}
-			if (preState != null) {
-				try {
-					preState.close();
-				} catch (SQLException e1) {
-				}
-			}
-		}
-	}
-	private void createPapers(List<KdQuestion> qs, DetailDto3 qt, PaperExportDto dto) {
-		if (qs == null || qs.size() == 0) {
-			return;
-		}
-		if (qs.size() <= maxqc) {
-			createPaper(qs, qt, dto, 1);
-		} else {
-			int size = qs.size();
-			int len = maxqc;
-			int count = (size + len - 1) / len;
-
-			for (int i = 0; i < count; i++) {
-				List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
-				createPaper(subList, qt, dto, i + 1);
-			}
-		}
-
-	}
-
-	private void createPaper(List<KdQuestion> qs, DetailDto3 qt, PaperExportDto dto, int indx) {
-		if (qs.size() == 0) {
-			return;
-		}
-		double score = 0.0;
-		int unit = 0;
-		for (KdQuestion q : qs) {
-			if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
-				unit = unit + q.getSubQuestions().size();
-			} else {
-				unit++;
-			}
-			score = Calculator.add(score, q.getScore(), 1);
-		}
-		String detailName = qt.getTypeName();
-		KdPaper paper = new KdPaper();
-		paper.setDetailCount(1);
-		paper.setUnitCount(unit);
-		paper.setTotalScore(score);
-		paper.setName(dto.getPaperSuff() + detailName + "_" + indx);
-		paper.setCourseCode(dto.getCourseCode());
-		List<KdDetail> des = new ArrayList<>();
-		KdDetail d = new KdDetail();
-		d.setName(detailName);
-		d.setNumber(1);
-		d.setQuestionCount(unit);
-		d.setTotalScore(score);
-		d.setQuestions(qs);
-		des.add(d);
-		paper.setDetails(des);
-		paper.setDetailCount(1);
-		paper.setUnitCount(qs.size());
-		File paperdir = new File(paperDir + dto.getCourseCode() + "/" + qt.getTypeId() + "/");
-		paperdir.mkdirs();
-		try {
-			FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper_" + indx + ".json", JSONObject.toJSONString(paper));
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	@Override
-	public void initResult() {
-
-	}
+
+    // private static String[] sucStr = new String[] { "对", "正确", "√", "是",
+    // "True" };
+    // private static String[] errStr = new String[] { "错", "错误", "×", "不正确",
+    // "否", "False" };
+    // private static String paperSuff = "(231205)";
+    private int maxqc = 200000;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    private static String imgDir = Param.dataDir + "files/";
+
+    private static Pattern imgPat = Pattern.compile("<img[^<]+src=['\"]([^<\"]+)['\"][^<]*>");
+
+    // private Pattern xieGangPat = Pattern.compile("\\\\([^\"]|(\",))");
+
+    @Override
+    public void consume(PaperExportDto dto) {
+        Connection connect = null;
+        File sub = new File(paperDir + dto.getCourseCode() + "/");
+        sub.mkdir();
+        try {
+            Class.forName("com.mysql.cj.jdbc.Driver");
+
+            String url = "jdbc:mysql://localhost:3306/" + Param.dbName + "?serverTimezone=GMT%2B8";
+
+            String user = "root";
+
+            String password = "123456";
+            connect = DriverManager.getConnection(url, user, password);
+            exportPaper(connect, dto);
+            GkExportPaperByCourseCode.addDisposeCount();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (connect != null) {
+                try {
+                    connect.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    private List<KdQuestion> of(List<QuestionVo4> vos) {
+        List<KdQuestion> ret = new ArrayList<>();
+        for (QuestionVo4 vo : vos) {
+            try {
+                KdQuestion q = of(vo);
+                ret.add(q);
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode.addValid();
+                continue;
+            }
+        }
+        return ret;
+    }
+
+    private KdQuestion of(QuestionVo4 vo) {
+        KdQuestion q = new KdQuestion();
+        q.setPropIds(new ArrayList<>());
+        q.getPropIds().add(vo.getCategory());
+        q.setQuesStructType(QuesStructType.getQuesStructTypeById(vo.getqType().getTypeId()));
+        q.setBody(vo.getBody());
+        q.setDifficultyDegree(0.5);
+        q.setHaveAudio(false);
+        q.setId(vo.getQid().toString());
+        q.setScore(1.0);
+        q.setDetailName(vo.getCategoryName());
+        return q;
+    }
+
+    private List<QuestionVo4> getQuestion(Connection connect, String courseCode) throws SQLException, IOException {
+        List<QuestionVo4> qs = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select q.*,qc.name categoryName from mdl_course c "
+                    + " inner join mdl_context ct on ct.instanceid=c.id "
+                    + " inner join mdl_question_categories qc on qc.contextid=ct.id "
+                    + " inner join mdl_question q on q.category=qc.id " + " where c.idnumber='" + courseCode
+                    + "' and q.qtype in('multichoice','multichoiceset','truefalse') " + " and q.parent=0 ";
+
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                QuestionVo4 q = new QuestionVo4();
+                q.setQid(resultSet.getLong("id"));
+                q.setPid(resultSet.getLong("parent"));
+                q.setCategory(resultSet.getLong("category"));
+                q.setCategoryName(resultSet.getString("categoryName"));
+                q.setqType(CusQuesStructType3.valueOf(resultSet.getString("qType")));
+                q.setBody(resultSet.getString("questiontext"));
+                qs.add(q);
+            }
+            return qs;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    // public static void main(String[] args) {
+    // String s="a\"\\\",b\\h";
+    // System.out.println(s);
+    // System.out.println(fomat(s));
+    // }
+
+    private void disposeQuestionImg(Connection connect, String courseCode, KdQuestion q)
+            throws NumberFormatException, SQLException {
+        q.setBody(disposeImg(connect, courseCode, "questiontext", q.getBody(), Long.valueOf(q.getId())));
+        if (CollectionUtils.isNotEmpty(q.getOptions())) {
+            for (KdQuesOption o : q.getOptions()) {
+                o.setBody(disposeImg(connect, courseCode, "answer", o.getBody(), Long.valueOf(o.getId())));
+            }
+        }
+    }
+
+    private String disposeImg(Connection connect, String courseCode, String filearea, String str, Long itemId)
+            throws SQLException {
+        if (StringUtils.isBlank(str)) {
+            return str;
+        }
+        Matcher matcher = imgPat.matcher(str);
+        Map<String, String> srcMap = new HashMap<>();
+        while (matcher.find()) {
+            String imgSrc = matcher.group(1).trim();
+            if (imgSrc.startsWith("data:image/")) {
+
+            } else if (imgSrc.startsWith("@@PLUGINFILE@@")) {
+                if (srcMap.get(imgSrc) == null) {
+                    File img = getImage(connect, imgSrc, courseCode, itemId, filearea);
+                    String base64 = FileUtil.fileToBase64Src(img);
+                    srcMap.put(imgSrc, base64);
+                }
+            } else {
+                throw new StatusException("图片有误:" + itemId);
+            }
+        }
+        for (String imgSrc : srcMap.keySet()) {
+            str = str.replaceAll(imgSrc.replaceAll("\\?", "\\\\?"), srcMap.get(imgSrc));
+        }
+        return str;
+    }
+
+    private File getImage(Connection connect, String imgSrc, String courseCode, Long itemId, String filearea)
+            throws SQLException {
+        String fileName = getFileName(imgSrc);
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String hash = null;
+            int count = 0;
+            String sql = " select * from mdl_files where itemid = " + itemId + " and source='" + fileName
+                    + "' and component = 'question' and filearea = '" + filearea + "' ";
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                count++;
+                hash = resultSet.getString("contenthash");
+            }
+            if (count != 1) {
+                throw new StatusException("图片有误:" + itemId + filearea);
+            }
+            String suff = fileName.substring(fileName.lastIndexOf("."));
+            File file = new File(imgDir + courseCode + "/" + hash + suff);
+            if (!file.exists()) {
+                throw new StatusException("图片有误:" + itemId + filearea);
+            }
+            return file;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private String getFileName(String s) {
+        int end = s.length();
+        int f = s.indexOf("?");
+        if (f != -1) {
+            end = f;
+        }
+        try {
+            return URLDecoder.decode(s.substring(s.lastIndexOf("/") + 1, end), "utf-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private void exportPaper(Connection connect, PaperExportDto dto) throws Exception {
+        List<QuestionVo4> vos = getQuestion(connect, dto.getCourseCode());
+        if (CollectionUtils.isEmpty(vos)) {
+            return;
+        }
+        List<KdQuestion> qs = of(vos);
+        fillAnswer(connect, qs, dto.getCourseCode());
+
+        Map<DetailDto3, List<KdQuestion>> qmap = new HashMap<>();
+        for (KdQuestion q : qs) {
+            if (q.isValid()) {
+                DetailDto3 tem = new DetailDto3(null, q.getDetailName());
+                List<KdQuestion> list = qmap.get(tem);
+                if (list == null) {
+                    tem.setTypeId(UUID.randomUUID().toString());
+                    list = new ArrayList<>();
+                    qmap.put(tem, list);
+                }
+                list.add(q);
+            }
+        }
+        for (DetailDto3 qt : qmap.keySet()) {
+            createPapers(qmap.get(qt), qt, dto);
+        }
+    }
+
+    private void fillAnswer(Connection connect, List<KdQuestion> qs, String courseCode)
+            throws NumberFormatException, SQLException {
+        List<Answer> qps = new BatchGetDataUtil<Answer, KdQuestion>() {
+
+            @Override
+            protected List<Answer> getData(List<KdQuestion> paramList) {
+                return getAnswerBatch(connect, paramList);
+            }
+        }.getDataForBatch(qs, 200);
+        if (CollectionUtils.isEmpty(qps)) {
+            return;
+        }
+
+        Map<Long, List<Answer>> map = new HashMap<>();
+        for (Answer qp : qps) {
+            List<Answer> list = map.get(qp.getQuestionId());
+            if (list == null) {
+                list = new ArrayList<>();
+                map.put(qp.getQuestionId(), list);
+            }
+            list.add(qp);
+        }
+
+        for (KdQuestion q : qs) {
+            try {
+                List<Answer> as = map.get(Long.valueOf(q.getId()));
+                if (CollectionUtils.isEmpty(as)) {
+                    throw new StatusException("没有答案:" + q.getId());
+                }
+                if (QuesStructType.SINGLE_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+                    List<KdQuesOption> options = new ArrayList<>();
+                    q.setOptions(options);
+                    int num = 0;
+                    int answerCount = 0;
+                    for (Answer a : as) {
+                        num++;
+                        KdQuesOption o = new KdQuesOption();
+                        options.add(o);
+                        o.setId(a.getaId());
+                        o.setNumber(num);
+                        o.setBody(a.getBody());
+                        o.setSelect(a.getFraction() > 0);
+                        if (o.getSelect()) {
+                            answerCount++;
+                        }
+                    }
+                    if (answerCount == 0) {
+                        throw new StatusException("没有答案:" + q.getId());
+                    }
+                    if (answerCount > 1) {
+                        q.setQuesStructType(QuesStructType.MULTIPLE_ANSWER_QUESTION);
+                    }
+                } else if (QuesStructType.BOOL_ANSWER_QUESTION.equals(q.getQuesStructType())) {
+                    for (Answer a : as) {
+                        if (a.getFraction() > 0) {
+                            q.setAnswer("对".equals(a.getBody().trim()) ? "正确" : "错误");
+                            break;
+                        }
+                    }
+                    if (StringUtils.isBlank(q.getAnswer())) {
+                        throw new StatusException("答案有误:" + q.getId());
+                    }
+                } else {
+                    throw new StatusException("题型有误:" + q.getId());
+                }
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode3.addValid();
+                q.setValid(false);
+                continue;
+            }
+            try {
+                disposeQuestionImg(connect, courseCode, q);
+            } catch (StatusException e) {
+                GkExportPaperByCourseCode3.addImgValid();
+                q.setValid(false);
+                continue;
+            }
+        }
+
+    }
+
+    private List<Answer> getAnswerBatch(Connection connect, List<KdQuestion> qs) {
+        List<Answer> as = new ArrayList<>();
+        List<Long> ids = qs.stream().map(e -> Long.valueOf(e.getId())).collect(Collectors.toList());
+        String idsstr = StringUtils.join(ids, ",");
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = " select t.id,t.question,t.answer,t.fraction  from mdl_question_answers t "
+                    + " where t.question in (" + idsstr + ")  ";
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                Answer a = new Answer();
+                a.setBody(resultSet.getString("answer"));
+                a.setFraction(resultSet.getDouble("fraction"));
+                a.setQuestionId(resultSet.getLong("question"));
+                a.setaId(resultSet.getLong("id"));
+                as.add(a);
+            }
+            return as;
+        } catch (Exception e1) {
+            throw new RuntimeException(e1);
+        } finally {
+            if (resultSet != null) {
+                try {
+                    resultSet.close();
+                } catch (SQLException e1) {
+                }
+            }
+            if (preState != null) {
+                try {
+                    preState.close();
+                } catch (SQLException e1) {
+                }
+            }
+        }
+    }
+
+    private void createPapers(List<KdQuestion> qs, DetailDto3 qt, PaperExportDto dto) {
+        if (qs == null || qs.size() == 0) {
+            return;
+        }
+        if (qs.size() <= maxqc) {
+            createPaper(qs, qt, dto, 1);
+        } else {
+            int size = qs.size();
+            int len = maxqc;
+            int count = (size + len - 1) / len;
+
+            for (int i = 0; i < count; i++) {
+                List<KdQuestion> subList = qs.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
+                createPaper(subList, qt, dto, i + 1);
+            }
+        }
+
+    }
+
+    private void createPaper(List<KdQuestion> qs, DetailDto3 qt, PaperExportDto dto, int indx) {
+        if (qs.size() == 0) {
+            return;
+        }
+        double score = 0.0;
+        int unit = 0;
+        for (KdQuestion q : qs) {
+            if (CollectionUtils.isNotEmpty(q.getSubQuestions())) {
+                unit = unit + q.getSubQuestions().size();
+            } else {
+                unit++;
+            }
+            score = Calculator.add(score, q.getScore(), 1);
+        }
+        String detailName = qt.getTypeName();
+        KdPaper paper = new KdPaper();
+        paper.setDetailCount(1);
+        paper.setUnitCount(unit);
+        paper.setTotalScore(score);
+        paper.setName(Param.paperPrefix + detailName + "_" + indx);
+        paper.setCourseCode(dto.getCourseCode());
+        List<KdDetail> des = new ArrayList<>();
+        KdDetail d = new KdDetail();
+        d.setName(detailName);
+        d.setNumber(1);
+        d.setQuestionCount(unit);
+        d.setTotalScore(score);
+        d.setQuestions(qs);
+        des.add(d);
+        paper.setDetails(des);
+        paper.setDetailCount(1);
+        paper.setUnitCount(qs.size());
+        File paperdir = new File(paperDir + dto.getCourseCode() + "/" + qt.getTypeId() + "/");
+        paperdir.mkdirs();
+        try {
+            FileUtil.writeFile(paperdir.getAbsolutePath(), "/paper_" + indx + ".json", JSONObject.toJSONString(paper));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void initResult() {
+
+    }
 }

+ 52 - 53
src/main/java/cn/com/qmth/export/MyProducer.java

@@ -12,59 +12,58 @@ import org.apache.poi.xssf.usermodel.XSSFRow;
 import org.apache.poi.xssf.usermodel.XSSFSheet;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
-
 public class MyProducer extends Producer {
-	private static Logger logger = LogManager.getLogger(MyProducer.class);
-	private static String dir = "d:/guangkai/";
-	private static String paperDir = "d:/guangkai/paper/";
 
-	@Override
-	protected void produce(Map<String, Object> param) throws Exception {
-		logger.info("***************************任务生产开始");
-		String paperSuff = (String)param.get("paperSuff");
-		String dbName = (String)param.get("dbName");
-		File excelFolder = new File(paperDir);
-		if (excelFolder.exists()) {
-			FileUtil.clearDirectory(paperDir);
-		} else {
-			excelFolder.mkdirs();
-		}
-		LinkedHashSet<String> cs = readSubject();
-		if (CollectionUtils.isEmpty(cs)) {
-			logger.debug("无数据导出");
-			return;
-		} else {
-			logger.debug(cs.size() + "个课程");
-		}
-		for (String c : cs) {
-			offer(new PaperExportDto(c, paperSuff,dbName));
-		}
-		logger.info("***************************任务生产结束");
-	}
-	
-	
-	private static LinkedHashSet<String> readSubject() {
-		LinkedHashSet<String> list = new LinkedHashSet<>();
-		XSSFWorkbook wb = null;
-		try {
-			wb = new XSSFWorkbook(dir + "subject_info.xlsx");
-			XSSFSheet sheet = wb.getSheetAt(0);
-			int rows = sheet.getLastRowNum();
-			for (int i = 1; i <= rows; i++) {
-				XSSFRow row = sheet.getRow(i);
-				String yunkaiCode = row.getCell(1).getStringCellValue().trim();
-				list.add(yunkaiCode);
-			}
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (wb != null) {
-				try {
-					wb.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-		return list;
-	}
+    private static Logger logger = LogManager.getLogger(MyProducer.class);
+
+    private static String dir = Param.dataDir;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    @Override
+    protected void produce(Map<String, Object> param) throws Exception {
+        logger.info("***************************任务生产开始");
+        File excelFolder = new File(paperDir);
+        if (excelFolder.exists()) {
+            FileUtil.clearDirectory(paperDir);
+        } else {
+            excelFolder.mkdirs();
+        }
+        LinkedHashSet<String> cs = readSubject();
+        if (CollectionUtils.isEmpty(cs)) {
+            logger.debug("无数据导出");
+            return;
+        } else {
+            logger.debug(cs.size() + "个课程");
+        }
+        for (String c : cs) {
+            offer(new PaperExportDto(c));
+        }
+        logger.info("***************************任务生产结束");
+    }
+
+    private static LinkedHashSet<String> readSubject() {
+        LinkedHashSet<String> list = new LinkedHashSet<>();
+        XSSFWorkbook wb = null;
+        try {
+            wb = new XSSFWorkbook(dir + "subject_info.xlsx");
+            XSSFSheet sheet = wb.getSheetAt(0);
+            int rows = sheet.getLastRowNum();
+            for (int i = 1; i <= rows; i++) {
+                XSSFRow row = sheet.getRow(i);
+                String yunkaiCode = row.getCell(1).getStringCellValue().trim();
+                list.add(yunkaiCode);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (wb != null) {
+                try {
+                    wb.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+        return list;
+    }
 }

+ 52 - 53
src/main/java/cn/com/qmth/export/MyProducer2.java

@@ -12,59 +12,58 @@ import org.apache.poi.xssf.usermodel.XSSFRow;
 import org.apache.poi.xssf.usermodel.XSSFSheet;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
-
 public class MyProducer2 extends Producer {
-	private static Logger logger = LogManager.getLogger(MyProducer2.class);
-	private static String dir = "d:/guangkai/";
-	private static String paperDir = "d:/guangkai/paper/";
 
-	@Override
-	protected void produce(Map<String, Object> param) throws Exception {
-		logger.info("***************************任务生产开始");
-		String paperSuff = (String)param.get("paperSuff");
-		String dbName = (String)param.get("dbName");
-		File excelFolder = new File(paperDir);
-		if (excelFolder.exists()) {
-			FileUtil.clearDirectory(paperDir);
-		} else {
-			excelFolder.mkdirs();
-		}
-		LinkedHashSet<String> cs = readSubject();
-		if (CollectionUtils.isEmpty(cs)) {
-			logger.debug("无数据导出");
-			return;
-		} else {
-			logger.debug(cs.size() + "个课程");
-		}
-		for (String c : cs) {
-			offer(new PaperExportDto(c, paperSuff,dbName));
-		}
-		logger.info("***************************任务生产结束");
-	}
-	
-	
-	private static LinkedHashSet<String> readSubject() {
-		LinkedHashSet<String> list = new LinkedHashSet<>();
-		XSSFWorkbook wb = null;
-		try {
-			wb = new XSSFWorkbook(dir + "subject_info.xlsx");
-			XSSFSheet sheet = wb.getSheetAt(0);
-			int rows = sheet.getLastRowNum();
-			for (int i = 1; i <= rows; i++) {
-				XSSFRow row = sheet.getRow(i);
-				String yunkaiCode = row.getCell(1).getStringCellValue().trim();
-				list.add(yunkaiCode);
-			}
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (wb != null) {
-				try {
-					wb.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-		return list;
-	}
+    private static Logger logger = LogManager.getLogger(MyProducer2.class);
+
+    private static String dir = Param.dataDir;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    @Override
+    protected void produce(Map<String, Object> param) throws Exception {
+        logger.info("***************************任务生产开始");
+        File excelFolder = new File(paperDir);
+        if (excelFolder.exists()) {
+            FileUtil.clearDirectory(paperDir);
+        } else {
+            excelFolder.mkdirs();
+        }
+        LinkedHashSet<String> cs = readSubject();
+        if (CollectionUtils.isEmpty(cs)) {
+            logger.debug("无数据导出");
+            return;
+        } else {
+            logger.debug(cs.size() + "个课程");
+        }
+        for (String c : cs) {
+            offer(new PaperExportDto(c));
+        }
+        logger.info("***************************任务生产结束");
+    }
+
+    private static LinkedHashSet<String> readSubject() {
+        LinkedHashSet<String> list = new LinkedHashSet<>();
+        XSSFWorkbook wb = null;
+        try {
+            wb = new XSSFWorkbook(dir + "subject_info.xlsx");
+            XSSFSheet sheet = wb.getSheetAt(0);
+            int rows = sheet.getLastRowNum();
+            for (int i = 1; i <= rows; i++) {
+                XSSFRow row = sheet.getRow(i);
+                String yunkaiCode = row.getCell(1).getStringCellValue().trim();
+                list.add(yunkaiCode);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (wb != null) {
+                try {
+                    wb.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+        return list;
+    }
 }

+ 53 - 58
src/main/java/cn/com/qmth/export/MyProducer3.java

@@ -12,64 +12,59 @@ import org.apache.poi.xssf.usermodel.XSSFRow;
 import org.apache.poi.xssf.usermodel.XSSFSheet;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
-
 public class MyProducer3 extends Producer {
-	private static Logger logger = LogManager.getLogger(MyProducer3.class);
-	private static String dir = "d:/guangkai/";
-	private static String paperDir = "d:/guangkai/paper/";
 
-	@Override
-	protected void produce(Map<String, Object> param) throws Exception {
-		logger.info("***************************任务生产开始");
-		String paperSuff = (String)param.get("paperSuff");
-		String dbName = (String)param.get("dbName");
-		File excelFolder = new File(paperDir);
-		if (excelFolder.exists()) {
-			FileUtil.clearDirectory(paperDir);
-		} else {
-			excelFolder.mkdirs();
-		}
-		LinkedHashSet<String> cs = readSubject();
-		if (CollectionUtils.isEmpty(cs)) {
-			logger.debug("无数据导出");
-			return;
-		} else {
-			logger.debug(cs.size() + "个课程");
-		}
-		for (String c : cs) {
-			offer(new PaperExportDto(c, paperSuff,dbName));
-		}
-		logger.info("***************************任务生产结束");
-	}
-	
-	
-	private static LinkedHashSet<String> readSubject() {
-		LinkedHashSet<String> list = new LinkedHashSet<>();
-		XSSFWorkbook wb = null;
-		try {
-			wb = new XSSFWorkbook(dir + "subject_info.xlsx");
-			XSSFSheet sheet = wb.getSheetAt(0);
-			int rows = sheet.getLastRowNum();
-			for (int i = 1; i <= rows; i++) {
-				XSSFRow row = sheet.getRow(i);
-				String yunkaiCode;
-				try {
-					yunkaiCode = row.getCell(1).getStringCellValue().trim();
-				} catch (Exception e) {
-					yunkaiCode = (row.getCell(1).getNumericCellValue()+"").trim();
-				}
-				list.add(yunkaiCode);
-			}
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (wb != null) {
-				try {
-					wb.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-		return list;
-	}
+    private static Logger logger = LogManager.getLogger(MyProducer3.class);
+
+    @Override
+    protected void produce(Map<String, Object> param) throws Exception {
+        logger.info("***************************任务生产开始");
+        File excelFolder = new File(Param.dataDir + "paper/");
+        if (excelFolder.exists()) {
+            FileUtil.clearDirectory(Param.dataDir + "paper/");
+        } else {
+            excelFolder.mkdirs();
+        }
+        LinkedHashSet<String> cs = readSubject();
+        if (CollectionUtils.isEmpty(cs)) {
+            logger.debug("无数据导出");
+            return;
+        } else {
+            logger.debug(cs.size() + "个课程");
+        }
+        for (String c : cs) {
+            offer(new PaperExportDto(c));
+        }
+        logger.info("***************************任务生产结束");
+    }
+
+    private static LinkedHashSet<String> readSubject() {
+        LinkedHashSet<String> list = new LinkedHashSet<>();
+        XSSFWorkbook wb = null;
+        try {
+            wb = new XSSFWorkbook(Param.dataDir + "subject_info.xlsx");
+            XSSFSheet sheet = wb.getSheetAt(0);
+            int rows = sheet.getLastRowNum();
+            for (int i = 1; i <= rows; i++) {
+                XSSFRow row = sheet.getRow(i);
+                String yunkaiCode;
+                try {
+                    yunkaiCode = row.getCell(0).getStringCellValue().trim();
+                } catch (Exception e) {
+                    yunkaiCode = (row.getCell(0).getNumericCellValue() + "").trim();
+                }
+                list.add(yunkaiCode);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (wb != null) {
+                try {
+                    wb.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+        return list;
+    }
 }

+ 57 - 58
src/main/java/cn/com/qmth/export/MyProducer4.java

@@ -12,64 +12,63 @@ import org.apache.poi.xssf.usermodel.XSSFRow;
 import org.apache.poi.xssf.usermodel.XSSFSheet;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
-
 public class MyProducer4 extends Producer {
-	private static Logger logger = LogManager.getLogger(MyProducer4.class);
-	private static String dir = "d:/guangkai/";
-	private static String paperDir = "d:/guangkai/paper/";
 
-	@Override
-	protected void produce(Map<String, Object> param) throws Exception {
-		logger.info("***************************任务生产开始");
-		String paperSuff = (String)param.get("paperSuff");
-		String dbName = (String)param.get("dbName");
-		File excelFolder = new File(paperDir);
-		if (excelFolder.exists()) {
-			FileUtil.clearDirectory(paperDir);
-		} else {
-			excelFolder.mkdirs();
-		}
-		LinkedHashSet<String> cs = readSubject();
-		if (CollectionUtils.isEmpty(cs)) {
-			logger.debug("无数据导出");
-			return;
-		} else {
-			logger.debug(cs.size() + "个课程");
-		}
-		for (String c : cs) {
-			offer(new PaperExportDto(c, paperSuff,dbName));
-		}
-		logger.info("***************************任务生产结束");
-	}
-	
-	
-	private static LinkedHashSet<String> readSubject() {
-		LinkedHashSet<String> list = new LinkedHashSet<>();
-		XSSFWorkbook wb = null;
-		try {
-			wb = new XSSFWorkbook(dir + "subject_info.xlsx");
-			XSSFSheet sheet = wb.getSheetAt(0);
-			int rows = sheet.getLastRowNum();
-			for (int i = 1; i <= rows; i++) {
-				XSSFRow row = sheet.getRow(i);
-				String yunkaiCode;
-				try {
-					yunkaiCode = row.getCell(1).getStringCellValue().trim();
-				} catch (Exception e) {
-					yunkaiCode = (row.getCell(1).getNumericCellValue()+"").trim();
-				}
-				list.add(yunkaiCode);
-			}
-		} catch (IOException e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (wb != null) {
-				try {
-					wb.close();
-				} catch (IOException e) {
-				}
-			}
-		}
-		return list;
-	}
+    private static Logger logger = LogManager.getLogger(MyProducer4.class);
+
+    private static String dir = Param.dataDir;
+
+    private static String paperDir = Param.dataDir + "paper/";
+
+    @Override
+    protected void produce(Map<String, Object> param) throws Exception {
+        logger.info("***************************任务生产开始");
+        File excelFolder = new File(paperDir);
+        if (excelFolder.exists()) {
+            FileUtil.clearDirectory(paperDir);
+        } else {
+            excelFolder.mkdirs();
+        }
+        LinkedHashSet<String> cs = readSubject();
+        if (CollectionUtils.isEmpty(cs)) {
+            logger.debug("无数据导出");
+            return;
+        } else {
+            logger.debug(cs.size() + "个课程");
+        }
+        for (String c : cs) {
+            offer(new PaperExportDto(c));
+        }
+        logger.info("***************************任务生产结束");
+    }
+
+    private static LinkedHashSet<String> readSubject() {
+        LinkedHashSet<String> list = new LinkedHashSet<>();
+        XSSFWorkbook wb = null;
+        try {
+            wb = new XSSFWorkbook(dir + "subject_info.xlsx");
+            XSSFSheet sheet = wb.getSheetAt(0);
+            int rows = sheet.getLastRowNum();
+            for (int i = 1; i <= rows; i++) {
+                XSSFRow row = sheet.getRow(i);
+                String yunkaiCode;
+                try {
+                    yunkaiCode = row.getCell(1).getStringCellValue().trim();
+                } catch (Exception e) {
+                    yunkaiCode = (row.getCell(1).getNumericCellValue() + "").trim();
+                }
+                list.add(yunkaiCode);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (wb != null) {
+                try {
+                    wb.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+        return list;
+    }
 }

+ 16 - 29
src/main/java/cn/com/qmth/export/PaperExportDto.java

@@ -1,33 +1,20 @@
 package cn.com.qmth.export;
 
 public class PaperExportDto {
-	private String courseCode;
-	private String paperSuff;
-	private String dbName;
-	public String getCourseCode() {
-		return courseCode;
-	}
-	public void setCourseCode(String courseCode) {
-		this.courseCode = courseCode;
-	}
-	public String getPaperSuff() {
-		return paperSuff;
-	}
-	public void setPaperSuff(String paperSuff) {
-		this.paperSuff = paperSuff;
-	}
-	
-	public String getDbName() {
-		return dbName;
-	}
-	public void setDbName(String dbName) {
-		this.dbName = dbName;
-	}
-	public PaperExportDto(String courseCode, String paperSuff, String dbName) {
-		super();
-		this.courseCode = courseCode;
-		this.paperSuff = paperSuff;
-		this.dbName = dbName;
-	}
-	
+
+    private String courseCode;
+
+    public String getCourseCode() {
+        return courseCode;
+    }
+
+    public void setCourseCode(String courseCode) {
+        this.courseCode = courseCode;
+    }
+
+    public PaperExportDto(String courseCode) {
+        super();
+        this.courseCode = courseCode;
+    }
+
 }

+ 14 - 0
src/main/java/cn/com/qmth/export/Param.java

@@ -0,0 +1,14 @@
+package cn.com.qmth.export;
+
+public class Param {
+
+    public static String dbUser = "root";
+
+    public static String dbPass = "123456";
+
+    public static String dbName = "guangkai241128";
+
+    public static String dataDir = "e:/files/guangkai/20241128/";
+
+    public static String paperPrefix = "(241128)";
+}

+ 113 - 111
src/main/java/cn/com/qmth/export/SetLevel.java

@@ -12,115 +12,117 @@ import java.util.List;
 import java.util.Map;
 
 public class SetLevel {
-	private static String dbName="guangkai_mdl";
-	public static void main(String[] args) {
-		System.out.println("开始处理");
-		Connection connect = null;
-
-		try {
-			Class.forName("com.mysql.cj.jdbc.Driver");
-
-			String url = "jdbc:mysql://localhost:3306/"+dbName+"?serverTimezone=GMT%2B8";
-
-			String user = "root";
-
-			String password = "123456";
-			connect = DriverManager.getConnection(url, user, password);
-			List<Knowledge> ks=getKnowledge(connect);
-			setLevel(ks);
-			if (ks.size() <= 1000) {
-				updateKnowledge(connect, ks);
-				System.out.println("处理:1");
-			} else {
-				int size = ks.size();
-				int len = 1000;
-				int count = (size + len - 1) / len;
-
-				for (int i = 0; i < count; i++) {
-					List<Knowledge> subList = ks.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
-					updateKnowledge(connect, subList);
-					System.out.println("处理:"+(i+1)+"/"+count);
-				}
-			}
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			if (connect != null) {
-				try {
-					connect.close();
-				} catch (SQLException e) {
-				}
-			}
-			System.out.println("结束处理");
-		}
-	}
-	
-	private static void updateKnowledge(Connection connect,List<Knowledge> ks) throws SQLException, IOException {
-		PreparedStatement preState = null;
-		try {
-			String sql = "update mdl_question_categories set level=? where id=?";
-			preState = connect.prepareStatement(sql);
-
-			for(Knowledge k:ks) {
-				preState.setInt(1, k.getLevel());
-				preState.setLong(2, k.getId());
-				preState.addBatch();
-			}
-			preState.executeBatch();
-			
-		} finally {
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
-	
-	private static void setLevel(List<Knowledge> ks) {
-		Map<Long,Knowledge> map=new HashMap<>();
-		for(Knowledge k:ks) {
-			map.put(k.getId(), k);
-		}
-		for(Knowledge k:ks) {
-			getAndSetLevel(map, k);
-		}
-	}
-	
-	private static void getAndSetLevel(Map<Long,Knowledge> map,Knowledge k) {
-		if(k.getParentId()==0) {
-			k.setLevel(0);
-		}else {
-			Knowledge pk=map.get(k.getParentId());
-			if(pk.getLevel()==null) {
-				getAndSetLevel(map, pk);
-			}
-			k.setLevel(pk.getLevel()+1);
-		}
-	}
-
-	private static List<Knowledge> getKnowledge(Connection connect) throws SQLException, IOException {
-		List<Knowledge> as = new ArrayList<>();
-		PreparedStatement preState = null;
-		ResultSet resultSet = null;
-		try {
-			String sql = "select id,parent from mdl_question_categories";
-			preState = connect.prepareStatement(sql);
-
-			resultSet = preState.executeQuery();
-
-			while (resultSet.next()) {
-				Knowledge a = new Knowledge();
-				a.setId(resultSet.getLong("id"));
-				a.setParentId(resultSet.getLong("parent"));
-				as.add(a);
-			}
-			return as;
-		} finally {
-			if (resultSet != null) {
-				resultSet.close();
-			}
-			if (preState != null) {
-				preState.close();
-			}
-		}
-	}
+
+    private static String dbName = "guangkai241128";
+
+    public static void main(String[] args) {
+        System.out.println("开始处理");
+        Connection connect = null;
+
+        try {
+            Class.forName("com.mysql.cj.jdbc.Driver");
+
+            String url = "jdbc:mysql://localhost:3306/" + dbName + "?serverTimezone=GMT%2B8";
+
+            String user = "root";
+
+            String password = "123456";
+            connect = DriverManager.getConnection(url, user, password);
+            List<Knowledge> ks = getKnowledge(connect);
+            setLevel(ks);
+            if (ks.size() <= 1000) {
+                updateKnowledge(connect, ks);
+                System.out.println("处理:1");
+            } else {
+                int size = ks.size();
+                int len = 1000;
+                int count = (size + len - 1) / len;
+
+                for (int i = 0; i < count; i++) {
+                    List<Knowledge> subList = ks.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
+                    updateKnowledge(connect, subList);
+                    System.out.println("处理:" + (i + 1) + "/" + count);
+                }
+            }
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (connect != null) {
+                try {
+                    connect.close();
+                } catch (SQLException e) {
+                }
+            }
+            System.out.println("结束处理");
+        }
+    }
+
+    private static void updateKnowledge(Connection connect, List<Knowledge> ks) throws SQLException, IOException {
+        PreparedStatement preState = null;
+        try {
+            String sql = "update mdl_question_categories set level=? where id=?";
+            preState = connect.prepareStatement(sql);
+
+            for (Knowledge k : ks) {
+                preState.setInt(1, k.getLevel());
+                preState.setLong(2, k.getId());
+                preState.addBatch();
+            }
+            preState.executeBatch();
+
+        } finally {
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
+
+    private static void setLevel(List<Knowledge> ks) {
+        Map<Long, Knowledge> map = new HashMap<>();
+        for (Knowledge k : ks) {
+            map.put(k.getId(), k);
+        }
+        for (Knowledge k : ks) {
+            getAndSetLevel(map, k);
+        }
+    }
+
+    private static void getAndSetLevel(Map<Long, Knowledge> map, Knowledge k) {
+        if (k.getParentId() == 0) {
+            k.setLevel(0);
+        } else {
+            Knowledge pk = map.get(k.getParentId());
+            if (pk.getLevel() == null) {
+                getAndSetLevel(map, pk);
+            }
+            k.setLevel(pk.getLevel() + 1);
+        }
+    }
+
+    private static List<Knowledge> getKnowledge(Connection connect) throws SQLException, IOException {
+        List<Knowledge> as = new ArrayList<>();
+        PreparedStatement preState = null;
+        ResultSet resultSet = null;
+        try {
+            String sql = "select id,parent from mdl_question_categories";
+            preState = connect.prepareStatement(sql);
+
+            resultSet = preState.executeQuery();
+
+            while (resultSet.next()) {
+                Knowledge a = new Knowledge();
+                a.setId(resultSet.getLong("id"));
+                a.setParentId(resultSet.getLong("parent"));
+                as.add(a);
+            }
+            return as;
+        } finally {
+            if (resultSet != null) {
+                resultSet.close();
+            }
+            if (preState != null) {
+                preState.close();
+            }
+        }
+    }
 }