You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 KiB

public class StudentCount {

/** 班级对应学生人数折线图 */
public static String createBarJson(Map<String, Object> data) {
	Set<String> set = data.keySet();
	
	GsonOption option = new GsonOption();
	option.title().text("班级学生数量统计").x(X.center).y(Y.top).borderWidth(1).textStyle().color("#438EB9");
	option.toolbox().show(true).feature(Tool.mark, Tool.restore, new MagicType(Magic.bar, Magic.line), Tool.saveAsImage).x(X.right).y(Y.top);
	//数据默认触发, 鼠标移入显示竖线  trigger(Trigger.axis)
	option.tooltip().formatter("{b} {c}人").trigger(Trigger.axis);
	option.legend().data("班级总人数").x(X.center).y(Y.bottom).borderWidth(1);
	Line line = new Line("班级总人数");
	//值轴
	ValueAxis valueAxis = new ValueAxis();
	valueAxis.axisLabel().formatter("{value}人").textStyle().color("#438EB9");
	//valueAxis.min(0);
	option.yAxis(valueAxis);
	//类目轴
	CategoryAxis categoryAxis = new CategoryAxis();
	//interval(0):设置横轴信息全部显示
	//rotate(-30):设置 -30 度角倾斜显示
	categoryAxis.axisLabel().interval(0).rotate(-30).textStyle().color("#438EB9");
	for (String className : set) {
		categoryAxis.data(className);
		ClassInfo classInfo = (ClassInfo)data.get(className);
		line.data(classInfo.getClassId());
	}
	option.xAxis(categoryAxis);
	line.smooth(true);
	option.series(line);
	option.grid().x(100);
	System.out.println(option.toString());
	return option.toString();
}

} public class StudentExamInfoCharts { public static String createExamCountBarJson(List examInfos) { GsonOption option = new GsonOption(); option.title().text("学生考试次数统计").x(X.center).y(Y.top).borderWidth(1).textStyle().color("#438EB9"); option.toolbox().show(true).feature(Tool.mark, Tool.restore, new MagicType(Magic.bar, Magic.line), Tool.saveAsImage).x(X.right).y(Y.top); option.tooltip().show(true).formatter("{b} {c}次"); option.legend().data("学生考试次数统计").x(X.center).y(Y.bottom); Bar bar = new Bar(); //值轴 ValueAxis valueAxis = new ValueAxis(); //设置y轴不出现小数值 valueAxis.interval(1); valueAxis.axisLabel().formatter("{value} 次"); option.yAxis(valueAxis); //类目轴 CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.axisLabel().interval(0); for (StudentExamInfo studentExamInfo : examInfos) { bar.data(studentExamInfo.getExamSum()); categoryAxis.data(studentExamInfo.getStudentName()); } bar.barCategoryGap("20"); option.xAxis(categoryAxis); option.series(bar); return option.toString(); } public static String createAvgCountLineJson(List examInfos) { GsonOption option = new GsonOption(); option.title().text("学生考试平均成绩统计").x(X.center).y(Y.top).borderWidth(1).textStyle().color("#438EB9"); option.toolbox().show(true).feature(Tool.mark, Tool.restore, new MagicType(Magic.bar, Magic.line), Tool.saveAsImage).x(X.right).y(Y.top); option.tooltip().show(true).trigger(Trigger.axis).axisPointer().type(PointerType.cross).crossStyle().color("#999"); option.legend().data("考试次数", "平均分").x(X.center).y(Y.bottom); Line line = new Line("考试次数").smooth(true); Bar bar = new Bar("平均分"); //值轴 ValueAxis valueAxis = new ValueAxis(); //设置y轴不出现小数值 valueAxis.interval(1); valueAxis.axisLabel().formatter("{value} 次"); ValueAxis valueAxis1 = new ValueAxis(); valueAxis1.interval(1); valueAxis1.axisLabel().formatter("{value} 分"); option.yAxis(valueAxis, valueAxis1); //类目轴 CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.axisLabel().interval(0); for (StudentExamInfo studentExamInfo : examInfos) { if (studentExamInfo.getAvgScore() != null || studentExamInfo.getExamSum() != 0) { bar.data(studentExamInfo.getAvgScore()/studentExamInfo.getExamSum()); } else { bar.data("暂无记录"); } line.data(studentExamInfo.getExamSum()); categoryAxis.data(studentExamInfo.getStudentName()); } //实现双 y 轴,使用 yAxisIndex() 指定应用到哪个 y 轴 bar.barCategoryGap("20").yAxisIndex(1); option.xAxis(categoryAxis); option.series(bar, line); return option.toString(); } public static String createStudentExamLineJson(List examInfos) { GsonOption option = new GsonOption(); option.title().text("学生考试试卷得分统计").x(X.center).y(Y.top).borderWidth(1).textStyle().color("#438EB9"); option.toolbox().show(true).feature(Tool.mark, Tool.restore, new MagicType(Magic.bar, Magic.line), Tool.saveAsImage).x(X.right).y(Y.top); option.tooltip().show(true).formatter("{b} {c}分").trigger(Trigger.axis); option.legend().data("得分").x(X.center).y(Y.bottom); Line line = new Line("试卷得分"); //值轴 ValueAxis valueAxis = new ValueAxis(); //设置y轴不出现小数值 valueAxis.interval(1); valueAxis.axisLabel().formatter("{value} 分"); option.yAxis(valueAxis); //类目轴 CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.axisLabel().interval(0).rotate(-30);

	for (StudentExamInfo studentExamInfo : examInfos) {
		line.data(studentExamInfo.getExamScore());
		categoryAxis.data(studentExamInfo.getExamPaperName());
	}
	option.xAxis(categoryAxis);
	option.series(line);
	System.out.println(option.toString());
	return option.toString();
}

} public class AdminHomeHandler { @Autowired ExamPaperInfoService examPaperInfoService; @Autowired SubjectInfoService subjectInfoService; @Autowired TeacherInfoService teacherInfoService; @Autowired StudentInfoService studentInfoService; @Autowired Gson gson; private Logger logger = Logger.getLogger(AdminHomeHandler.class); @RequestMapping("/homeInfo") public void homeInfo(HttpServletResponse response) throws IOException { logger.info("加载后台首页相关数据"); int examPaperTotal = examPaperInfoService.getExamPpaerTotal(); int subjectTotal = subjectInfoService.getSubjectTotal(); int teacherTotal = teacherInfoService.getTeacherTotal(); int studentTotal = studentInfoService.getStudentTotal(); String json = "{"examPaperTotal":"+examPaperTotal+", " + ""subjectTotal":"+subjectTotal+", " + ""teacherTotal":"+teacherTotal+", " + ""studentTotal":"+studentTotal+"}"; response.getWriter().print(json); } } public class ClassInfoHandler { @Autowired private ClassInfoService classInfoService; @Autowired private GradeInfoService gradeInfoService; @Autowired private TeacherInfoService teacherInfoService; @Autowired private TeacherInfo teacher; @Autowired private ClassInfo classInfo; @Autowired private Gson gson; private Logger logger = Logger.getLogger(ClassInfoHandler.class); @RequestMapping(value="/classes", method=RequestMethod.GET) public ModelAndView getClasses(@RequestParam(value="gradeId", required=false) Integer gradeId, @RequestParam(value="className", required=false) String className, @RequestParam(value="classId", required=false) Integer classId) { logger.info("获取班级集合 条件gradeId "+gradeId+", 班级编号:"+classId+", 班级:"+className); ModelAndView model = new ModelAndView(); ClassInfo classInfo = new ClassInfo(); /处理查询条件/ if (gradeId != null) { GradeInfo gradeInfo = new GradeInfo(); gradeInfo.setGradeId(gradeId); classInfo.setGrade(gradeInfo); } if (classId != null) classInfo.setClassId(classId); if (className != null) { if (className.trim() != "") classInfo.setClassName(className); } List classes = classInfoService.getClasses(classInfo); model.setViewName("admin/classes"); model.addObject("classes", classes); return model; } @RequestMapping("/preAddClass") public ModelAndView preAddClass() { logger.info("预添加班级信息"); ModelAndView model = new ModelAndView(); //获取年级信息 List grades = gradeInfoService.getGrades(); model.setViewName("admin/classedit"); model.addObject("grades", grades); //获取不是班主任的教师 teacher.setIsWork(0); Map<String, Object> map = new HashMap<String, Object>(); map.put("startIndex", null); map.put("pageShow", null); map.put("teacher", teacher); List teachers = teacherInfoService.getTeachers(map); model.addObject("teachers", teachers); model.addObject("editClass", new ClassInfo()); return model; } @RequestMapping(value="/class", method=RequestMethod.POST) public String isAddClass(ClassInfo classInfo, HttpServletRequest request) { logger.info("添加班级信息 "+classInfo); //修改教师班主任状态 String returnMsg = isChangeTeacherWork(1, classInfo.getTeacher().getTeacherId()); if (returnMsg != null) { request.setAttribute("error", "修改教师班主任状态 对应教师编号有误"); return "error"; } //添加 int row = classInfoService.isAddClass(classInfo); if (row < 1) { logger.error("班级 "+classInfo+" 删除失败"); request.setAttribute("error", "班级 "+classInfo.getClassName()+" 添加失败,请稍后再试!"); return "../error"; } return "redirect:/classes"; } @RequestMapping(value="/del/class/{classId}", method=RequestMethod.DELETE) public String isDelClass(@PathVariable("classId") Integer classId, HttpServletRequest request) { logger.info("删除班级 "+classId);

	//将删除班级对于之前班主任改为 非班主任状态
	//需要在删除班级之前修改,如果先删除了班级,再根据班级获取教师编号,就不能获取
	ClassInfo delClass = classInfoService.getClassById(classId);
	String returnMsg = isChangeTeacherWork(0, delClass.getTeacher().getTeacherId());
	if (returnMsg != null) {
		request.setAttribute("error", "修改教师班主任状态 对应教师编号有误");
		return "error";
	}
	//删除
	int row = classInfoService.isDelClass(classId);
	if (row < 1) {
		logger.error("班级 "+classId+" 删除失败");
		request.setAttribute("error", "班级删除失败,请稍后再试!");
		return "../error";
	}
	return "redirect:/classes";
}
@RequestMapping(value="edit/class/{classId}", method=RequestMethod.GET)
public ModelAndView preUpdateClass(@PathVariable("classId") Integer classId) {
	logger.info("预修改班级处理");
	ModelAndView model = new ModelAndView();
	//获取要修改班级
	ClassInfo classInfo = classInfoService.getClassById(classId);
	model.setViewName("/admin/classedit");
	model.addObject("editClass", classInfo);
	List<GradeInfo> grades = gradeInfoService.getGrades();
	//获取不是班主任的教师
	teacher.setIsWork(0);
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("startIndex", null);
	map.put("pageShow", null);
	map.put("teacher", teacher);
	List<TeacherInfo> teachers = teacherInfoService.getTeachers(map);
	//如果没有可用班主任
	if (teachers.size() == 0 || teachers == null) {
		teacher.setTeacherId(classInfo.getTeacher().getTeacherId());
		teacher.setTeacherName("暂无剩余教师");
		teachers.add(teacher);
	}
	model.addObject("teachers", teachers);
	model.addObject("grades", grades);
	return model;
}
@RequestMapping(value="edit/class/class", method=RequestMethod.PUT)
public String isUpdateClass(ClassInfo classInfo, HttpServletRequest request, 
		@RequestParam(value="lastTeacher", required=false) Integer lastTeacherId) {
	//修改上一教师不为班主任状态
	if (lastTeacherId != null) {
		String returnMsg = isChangeTeacherWork(0, lastTeacherId);
		if (returnMsg != null) {
			request.setAttribute("error", "修改教师班主任状态 对应教师编号有误");
			return "/error";
		}
	}
	//修改当前教师为班主任状态
	String returnMsg = isChangeTeacherWork(1, classInfo.getTeacher().getTeacherId());
	if (returnMsg != null) {
		request.setAttribute("error", "修改教师班主任状态 对应教师编号有误");
		return "/error";
  }
	logger.info("修改班级 "+classInfo);
	
	int row = classInfoService.isUpdateClass(classInfo);
	if (row < 1) {
		logger.error("班级 "+classInfo+" 修改失败");
		
		request.setAttribute("error", "班级修改失败,请稍后再试!");
		return "../error";
	}
	
	return "redirect:/classes";
}
@RequestMapping(value="/gradeclass/{gradeId}", method=RequestMethod.GET)
public void getClassesByGradeId(@PathVariable("gradeId") Integer gradeId,
		HttpServletResponse response) throws IOException {
	logger.info("获取年级 "+gradeId+" 下的班级集合");
	
	List<ClassInfo> classes = classInfoService.getClassByGradeId(gradeId);
	
	String json = gson.toJson(classes);
	response.getWriter().print(json);
}

isChangeTeacherWork(int status, Integer teacherId) { logger.info("修改教师 "+teacherId+" 的状态为 "+status); teacher.setIsWork(status); if (teacherId == null) { logger.error("修改教师班主任状态 对应教师编号有误"); return "修改教师班主任状态 对应教师编号有误"; } teacher.setTeacherId(teacherId); int row = teacherInfoService.updateTeacherIsWork(teacher); return null; } @RequestMapping("/stuCount") public void getStudentCountForClass( @RequestParam(value="gradeId", required=false) Integer gradeId, HttpServletResponse response) throws IOException { Map<String, Object> map = classInfoService.getStudentCountForClass(gradeId); String json = StudentCount.createBarJson(map); response.getWriter().print(json); } @RequestMapping("/preStudentCount") public ModelAndView preStudentCount() { ModelAndView model = new ModelAndView(); //获取年级信息 List grades = gradeInfoService.getGrades(); model.setViewName("admin/charts/studentCount"); model.addObject("grades", grades); return model; } } public class CourseInfoHandler { @Autowired private CourseInfoService courseInfoService; @Autowired private GradeInfoService gradeInfoService;

private Logger logger = Logger.getLogger(CourseInfoHandler.class);

/**
 * 获取科目信息
 * @param gradeId 年级编号
 * @param division 分科情况
 * @return
 */
@RequestMapping("/courses")
public ModelAndView getCourses(@RequestParam(value="gradeId", required=false) Integer gradeId,
		@RequestParam(value="division", required=false) Integer division) {
	logger.info("获取科目集合 年级条件 "+gradeId+" 分科条件 "+division);
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/courses");
	
	CourseInfo course = new CourseInfo();
	if (gradeId != null)
		course.getGrade().setGradeId(gradeId);
	if (division != null)
		course.setDivision(division);
	List<CourseInfo> courses = courseInfoService.getCourses(course);
	model.addObject("courses", courses);
	
	return model;
}

/**
 * 根据科目编号获取学科信息
 * @param courseId 科目编号
 * @return
 */
@RequestMapping("/course/{courseId}")
public ModelAndView getCourseById(@PathVariable("courseId") Integer courseId) {
	logger.info("获取科目信息 科目编号 "+courseId);
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/courseedit");
	
	CourseInfo course = courseInfoService.getCourseById(courseId);
	model.addObject("course", course);
	/** 获取所有年级列表 */
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);
	
	return model;
}

/**
 * 添加/修改科目信息
 * @param courseId 科目编号
 * @param isUpdate 标识是否为修改操作
 * @param courseName 科目名称
 * @param division 分科情况
 * @param gradeId 年级编号
 * @return
 */
@RequestMapping(value="/course/course", method=RequestMethod.POST)
public String isUpdateOrAddCourse(@RequestParam(value="courseId", required=false) Integer courseId,
		@RequestParam(value="isupdate", required=false) Integer isUpdate,
		@RequestParam("courseName") String courseName,
		@RequestParam("division") Integer division,
		@RequestParam("gradeId") Integer gradeId) {
	
	CourseInfo course = new CourseInfo();
		course.setCourseId(courseId);
		course.setCourseName(courseName);
		course.setDivision(division);
		GradeInfo grade = new GradeInfo();
		grade.setGradeId(gradeId);
		course.setGrade(grade);
	
	//修改
	if (isUpdate != null) {
		logger.info("修改科目 "+course+" 的信息");
		int row = courseInfoService.isUpdateCourse(course);			
	}
	//添加
	else {
		logger.info("添加科目 "+course+" 的信息");
		int row = courseInfoService.isAddCourse(course);
	}
	
	return "redirect:/courses";
}

/**
 * 删除科目
 * @param courseId 待删除科目编号
 * @return
 */
@RequestMapping(value="/course/{courseId}", method=RequestMethod.DELETE)
public String isDelTeacher(@PathVariable("courseId") Integer courseId) {
	logger.info("删除科目 "+courseId);
	
	int row = courseInfoService.isDelCourse(courseId);
	
	return "redirect:/courses";
}

/**
 * 预添加科目信息
 * @return
 */
@RequestMapping("/preAddCourse")
public ModelAndView preAddCourse() {
	logger.info("预添加科目信息");
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/courseedit");
	/** 获取年级集合 */
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);
	
	return model;
}

} public class ExamChooseInfoHandler {

@Autowired
private ExamChooseInfoService examChooseInfoService;
@Autowired
private ExamChooseInfo examChoose;

private Logger logger = Logger.getLogger(ExamChooseInfoHandler.class);

/**
 * 记录考生考试选择答案
 * @param studentId 考生编号
 * @param examPaperId 考试试卷编号
 * @param subjectId 当前选择试题编号
 * @param index 前台控制索引
 * @param chooseAswer 选择答案
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/choose", method=RequestMethod.POST)
public void examChooseHandler(
		@RequestParam("studentId") Integer studentId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam("subjectId") Integer subjectId,
		@RequestParam(value="index", required=false) Integer index,
		@RequestParam("chooseAswer") String chooseAswer,
		HttpServletResponse response) throws IOException {
	logger.info("考生 "+studentId+" 在试卷 "+examPaperId+" 中试题 "+subjectId+" 选择了答案 "+chooseAswer+" 序号 "+index);
	
	//判断该考生是否已经选择过该试题
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("studentId", studentId);
	map.put("examPaperId", examPaperId);
	map.put("subjectId", subjectId);
	examChoose = examChooseInfoService.getChooseWithIds(map);
	logger.info("考生是否选择过试题 "+subjectId+" "+examChoose+" (NULL-否)");
	if (examChoose == null) {
		logger.info("考生 "+studentId+" 尚未选择试题 "+subjectId+" 添加选择记录 答案 "+chooseAswer);
		map.put("chooseResult", chooseAswer);
		/** 添加选择记录 */
		examChooseInfoService.addChoose(map);
	} else if (examChoose.getChooseId() != null && examChoose != null) {
		logger.info("考生 "+studentId+" 已经选择试题 "+subjectId+" 修改选择记录 答案 "+examChoose.getChooseResult()+" 更新为 "+chooseAswer);
		/*
		 * 如果选择了和上次相同的答案,则不做修改操作
		 * 优化 -- 前台判断选择了相同答案则不发出请求
		 */
		if(!chooseAswer.equals(examChoose.getChooseResult())) {
			examChoose.setChooseResult(chooseAswer);
			/** 当前选择答案和之前选择答案不同 修改答案记录 */
			examChooseInfoService.updateChooseWithIds(examChoose);
		} else {
			logger.info("考生选择了相同答案,不做修改操作");
		}
	} else {
		response.getWriter().print("f");
		return;
	}
	
	response.getWriter().print("t");
}

} public class ExamHistoryInfoHandler {

@Autowired
private ExamHistoryPaperService examHistoryPaperService;

private Logger logger = Logger.getLogger(ExamHistoryInfoHandler.class);


@RequestMapping("/historys")
public ModelAndView examHistorys() {
	List<ExamHistoryInfo> historys = examHistoryPaperService.getExamHistoryToTeacher();
	ModelAndView model = new ModelAndView("admin/examHistorys");
	logger.info("教师 查询历史考试信息 SIZE "+historys.size());
	
	model.addObject("historys", historys);
	
	return model;
}

} public class ExamPaperInfoHandler {

@Autowired
private ExamPaperInfoService examPaperInfoService;
@Autowired
private GradeInfoService gradeInfoService;
@Autowired
private GradeInfo grade;
@Autowired
private ExamPaperInfo examPaper;

private Logger logger = Logger.getLogger(ExamPaperInfoHandler.class);


/**
 * 获取试卷信息
 * @param gradeId 年级编号
 * @param startPage 起始页 默认第一页
 * @param pageShow 页容量 默认10
 * @return
 */
@RequestMapping("/examPapers")
public ModelAndView getCourses(@RequestParam(value = "gradeId", required = false) Integer gradeId,
		@RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,
		@RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow ) {
	logger.info("获取试卷集合  gradeId="+gradeId+", startPage="+startPage+", pageShow="+pageShow);
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/examPapers");

	if (gradeId != null) {
		grade.setGradeId(gradeId);
		examPaper.setGrade(grade);
	}
	
	Map<String, Object> map = new HashMap<String, Object>();
	//计算当前查询起始数据索引
	int startIndex = (startPage-1) * pageShow;
	map.put("examPaper", examPaper);
	map.put("startIndex", startIndex);
	map.put("pageShow", pageShow);
	List<ExamPaperInfo> examPapers = examPaperInfoService.getExamPapers(map);
	model.addObject("examPapers", examPapers);
	
	//获取试卷总量
	int examPaperTotal = examPaperInfoService.getExamPpaerTotal();
	//计算总页数
	int pageTotal = 1;
	if (examPaperTotal % pageShow == 0)
		pageTotal = examPaperTotal / pageShow;
	else
		pageTotal = examPaperTotal / pageShow + 1;			
	model.addObject("pageTotal", pageTotal);
	model.addObject("pageNow", startPage);

	return model;
}

/**
 * 根据编号获取试卷信息
 * @param examPaperId 试卷编号
 * @return
 */
@RequestMapping("/examPaper/{examPaperId}")
public ModelAndView getCourseById(@PathVariable("examPaperId") Integer examPaperId) {
	logger.info("获取试卷 " + examPaperId);
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/examPaperedit");

	ExamPaperInfo paper = examPaperInfoService.getExamPaper(examPaperId);
	model.addObject("examPaper", paper);
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);

	return model;
}

/**
 * 添加/修改试卷信息
 * @param examPaperId 待操作试卷编号
 * @param isUpdate 标识是否为修改操作
 * @param examPaperName 试卷名称
 * @param subjectNum 试卷试题数量
 * @param examPaperScore 试卷总分
 * @param examPaperTime 试卷规定考试时间
 * @param division 分科情况
 * @param examPaperEasy 难易程度
 * @param gradeId 年级编号
 * @return
 */
@RequestMapping(value = "/examPaper/examPaper", method = RequestMethod.POST)
public String isUpdateOrAddCourse(
		@RequestParam(value = "examPaperId", required = false) Integer examPaperId,
		@RequestParam(value = "isupdate", required = false) Integer isUpdate,
		@RequestParam(value = "examPaperName", required = false) String examPaperName,
		@RequestParam("subjectNum") Integer subjectNum,
		@RequestParam("examPaperScore") Integer examPaperScore,
		@RequestParam("examPaperTime") Integer examPaperTime,
		@RequestParam("division") Integer division,
		@RequestParam("examPaperEasy") Integer examPaperEasy,
		@RequestParam("gradeId") Integer gradeId) {

	examPaper.setExamPaperId(examPaperId);
	examPaper.setExamPaperName(examPaperName);
	examPaper.setSubjectNum(subjectNum);
	examPaper.setExamPaperScore(examPaperScore);
	examPaper.setExamPaperTime(examPaperTime);
	examPaper.setDivision(division);
	examPaper.setExamPaperEasy(examPaperEasy);
	grade.setGradeId(gradeId);
	examPaper.setGrade(grade);

	if (isUpdate != null) {
		logger.info("修改试卷 " + examPaper + " 的信息");
		int row = examPaperInfoService.isUpdateExamPaper(examPaper);
	} else {
		logger.info("添加试卷 " + examPaper + " 的信息");
		int row = examPaperInfoService.isAddExamPaper(examPaper);
	}

	return "redirect:/examPapers";
}

/**
 * 删除试卷
 * @param examPaperId 待删除试卷编号
 * @return
 */
@RequestMapping(value = "/examPaper/{examPaperId}", method = RequestMethod.DELETE)
public String isDelTeacher(@PathVariable("examPaperId") Integer examPaperId) {
	logger.info("删除试卷 " + examPaperId);

	int row = examPaperInfoService.isDelExamPaper(examPaperId);

	return "redirect:/examPapers";
}

/**
 * 预添加试卷
 * @return
 */
@RequestMapping("/preAddExamPaper")
public ModelAndView preAddStudent() {
	logger.info("预添加试卷信息");
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/examPaperedit");
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);

	return model;
}

} public class ExamPlanInfoHandler {

@Autowired
private ExamPlanInfoService examPlanInfoService;
@Autowired
private ClassInfoService classInfoService;
@Autowired
private CourseInfoService courseInfoService;
@Autowired
private ExamPaperInfoService examPaperInfoService;
@Autowired
private ExamPaperInfo examPaper;
@Autowired
private GradeInfo grade;

private Logger logger = Logger.getLogger(ExamPlanInfoHandler.class);


/**
 * 获取所有待考记录
 * @return
 */
@RequestMapping("/examPlans")
public ModelAndView getExamPlans() {
	ModelAndView model = new ModelAndView();
	model.setViewName("admin/examPlans");
	logger.info("获取待考考试信息");
	
	List<ExamPlanInfo> examPlans = examPlanInfoService.getExamPlans(null);
	model.addObject("examPlans", examPlans);
	
	return model;
}


/**
 * 预添加
 * @return
 */
@RequestMapping("/preAddep")
public ModelAndView preAddep() {
	ModelAndView model = new ModelAndView();
	model.setViewName("admin/examPlanedit");
	
	//获取所有班级信息
	List<ClassInfo> classes = classInfoService.getClasses(null);
	model.addObject("classes", classes);
	//获取所有科目信息
	List<CourseInfo> courses = courseInfoService.getCourses(null);
	model.addObject("courses", courses);
	//获取所有的试卷信息 -- 纯净的
	List<ExamPaperInfo> examPapers = examPaperInfoService.getExamPapersClear();
	model.addObject("examPapers", examPapers);
	
	return model;
}

/**
 * 添加待考信息
 * @param examPlan 考试安排记录信息
 * @return
 */
@RequestMapping(value="examPlan", method=RequestMethod.POST)
public String isAddExamPlan(ExamPlanInfo examPlan) {
	logger.info("添加待考记录:"+examPlan);
	examPlanInfoService.isAddExamPlan(examPlan);
	
	return "redirect:examPlans";
}


/**
 * 预修改
 * @param examPlanId 考试安排(待考)编号
 * @return
 */
@RequestMapping(value="/preUpdateep/{examPlanId}", method=RequestMethod.GET)
public ModelAndView preUpdateep(@PathVariable("examPlanId") Integer examPlanId) {
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/examPlanedit");
	
	//获取所有班级信息
	List<ClassInfo> classes = classInfoService.getClasses(null);
	model.addObject("classes", classes);
	//获取所有科目信息
	List<CourseInfo> courses = courseInfoService.getCourses(null);
	model.addObject("courses", courses);
	//获取所有的试卷信息 -- 纯净的(简单的)
	List<ExamPaperInfo> examPapers = examPaperInfoService.getExamPapersClear();
	model.addObject("examPapers", examPapers);
	//获取当前修改对象
	ExamPlanInfo examPlanWithUpdate = examPlanInfoService.getExamPlanById(examPlanId);
	logger.info("获取要修改的待考记录:"+examPlanWithUpdate);
	model.addObject("examPlan", examPlanWithUpdate);
	
	return model;
}


/**
 * 修改待考信息
 * @param examPlan 待考记录
 * @return
 */
@RequestMapping(value="preUpdateep/examPlan", method=RequestMethod.PUT)
public String isUpdateExamPlan(ExamPlanInfo examPlan) {
	logger.info("修改待考记录:"+examPlan);
	examPlanInfoService.isUpdateExamPlan(examPlan);
	
	return "redirect:../examPlans";
}


/**
 * 查询学生待考信息
 * @param classId 学生所在班级编号
 * @param gradeId 学生所在年级百年好
 * @param studentId 学生编号
 * @return
 */
@RequestMapping("/willexams")
public ModelAndView getStudentWillExam(
		@RequestParam("classId") Integer classId,
		@RequestParam("gradeId") Integer gradeId,
		@RequestParam(value="studentId", required=false) Integer studentId) {
	logger.info("查询学生 "+studentId+"(NULL-未指定)待考信息 班级:"+classId+", 年级:"+gradeId);
	ModelAndView model = new ModelAndView();
	model.setViewName("/reception/examCenter");
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("classId", classId);
	map.put("gradeId", gradeId);
	
	List<ExamPlanInfo> examPlans = examPlanInfoService.getStudentWillExam(map);
	model.addObject("examPlans", examPlans);
	model.addObject("gradeId", gradeId);
	
	return model;
}



/**
 * 定时刷新考试安排记录,将过期考试移除
 * 周一至周五 每隔15分钟刷新一次
 */
@Scheduled(cron="0 */15 * * * MON-FRI")
public void refreshExamPlan() {
	List<ExamPlanInfo> examPlans = examPlanInfoService.getExamPlans(null);
	logger.info("刷新待考记录, SIZE "+examPlans.size());
	if (examPlans.size() > 0) {
		for (ExamPlanInfo examPlanInfo : examPlans) {
			String beginTime = examPlanInfo.getBeginTime();
			int examPaperTime = examPlanInfo.getExamPaper().getExamPaperTime();
			/** 验证是否可移除 */
			if (validateExamPaerBeOverdue(beginTime, examPaperTime)) {
				logger.info("待考试卷 "+examPlanInfo.getExamPaper().getExamPaperId()+" 已经过期,即将移除");
				//移除过期考试安排
				int row = examPlanInfoService.isRemoveExamPlan(examPlanInfo.getExamPlanId());
			} else {
				logger.info("待考试卷 "+examPlanInfo.getExamPaper().getExamPaperId()+" 暂未过期,无法移除");
				continue;
			}
		} 
	}
}


/**
 * 验证试卷是否过期
 * @param beginTime 考试开始时间
 * @param examTime 考试时间
 * @return
 */
private boolean validateExamPaerBeOverdue(String beginTime, int examTime) {
	boolean flag = false;
	try {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date beginTimeDate = sdf.parse(beginTime);
		Long beginTimeTime = beginTimeDate.getTime();
		
		/** 转换考试时间为毫秒单位 */
		int examTimeSecond = examTime * 60 * 1000;
		
		Date nowDate = new Date();
		Long nowDateTime = nowDate.getTime();
		
		/** 当前时间超过了 考试结束时间,即为过期记录 */
		if(nowDateTime > (beginTimeTime+examTimeSecond)) {
			flag = true;
		}
	} catch (ParseException e) {
		e.printStackTrace();
	}
	
	return flag;
}


/**
 * 教师移除考试安排记录
 * @param examPlanId
 * @return
 */
@RequestMapping(value="/del/{examPlanId}")
public String isDelExamPlan(
		@PathVariable("examPlanId") Integer examPlanId) {
	logger.info("教师 移除考试安排 "+examPlanId);
	
	int row = examPlanInfoService.isRemoveExamPlan(examPlanId);
	
	return "redirect:../examPlans";
}

} public class ExamSubjectMiddleInfoHandler {

@Autowired
private ExamSubjectMiddleInfoService esmService;
@Autowired
private ExamPaperInfoService examPaperInfoService;
@Autowired
private SubjectInfoService subjectInfoService;
@Autowired
private ExamSubjectMiddleInfo esm;
@Autowired
private ExamPaperInfo examPaper;
@Autowired
private SubjectInfo subject;
@Autowired
private CourseInfo course;
@Autowired
private GradeInfo grade;
@Autowired
private Gson gson;

private Logger logger = Logger.getLogger(ExamSubjectMiddleInfoHandler.class);


/**
 * 查询试卷-试题信息
 * 根据多条件查询
 * @param examPaperId 试卷编号
 * @param courseName 科目名称
 * @param courseId 科目百年好
 * @param gradeId 年级编号
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/getESM", method={RequestMethod.GET, RequestMethod.POST})
public void getExamPaperWithSubject(
		@RequestParam(value="examPaperId", required=false) Integer examPaperId,
		@RequestParam(value="courseName", required=false) String courseName,
		@RequestParam(value="courseId", required=false) Integer courseId,
		@RequestParam(value="gradeId", required=false) Integer gradeId,
		HttpServletResponse response) throws IOException {
	ModelAndView model = new ModelAndView();
	
	/*条件处理*/
	if (examPaperId != null) examPaper.setExamPaperId(examPaperId);
	if (courseName != null) course.setCourseName(courseName);
	if (courseId != null) course.setCourseId(courseId);
	if (gradeId != null) grade.setGradeId(gradeId);
	subject.setCourse(course);
	subject.setGrade(grade);
	
	esm.setExamPaper(examPaper);
	esm.setSubject(subject);
	
	logger.info("查询试卷试题信息 With "+esm);
	List<ExamSubjectMiddleInfo> esms = esmService.getExamPaperWithSubject(esm);
	
	response.getWriter().print(gson.toJson(esms));
}

/**
 * 手动添加试题
 * 手动将选择的试题添加到指定试卷中  -- 正式添加处理
 * @param examPaperId 试卷编号
 * @param session
 * @param response
 * @throws Exception
 */
@RequestMapping(value="/handAdd", method={RequestMethod.GET, RequestMethod.POST})
public void isHandAddSubjectToExamPaper(
		@RequestParam(value="examPaperId") Integer examPaperId,
		HttpSession session,
		HttpServletResponse response) throws Exception {
	//添加试题总分统计
	int scoreSum = 0;
	//添加试题总量统计
	int subjectSum = 0;
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("examPaperId", examPaperId);
	ArrayList<Integer> subjectIds = new ArrayList<Integer>();
	
	//试题信息
	List<String> ids = (List<String>) session.getAttribute("ids");
	if (ids != null) {
		for (String is : ids) {
			//分割试题编号和分数
			String[] idAndScore = is.split(",");
			subjectIds.add(Integer.parseInt(idAndScore[0]));
			//累加试题分数
			scoreSum += Integer.parseInt(idAndScore[1]);
			//累加试题数量
			subjectSum += 1;
		}
		/** 需要添加试题集合 */
		map.put("subjectIds", subjectIds);
	} else {
		logger.error("试题集合为空,不能进行添加试题操作!");
		response.getWriter().print("需要添加的试题为空,操作失败!");
		return;
	}
	logger.info("添加试题集合到试卷 "+examPaperId);
	//总分和题目数量信息
	Map<String, Object> scoreWithNum = new HashMap<String, Object>();
	scoreWithNum.put("subjectNum", subjectSum);
	scoreWithNum.put("score", scoreSum);
	scoreWithNum.put("examPaperId", examPaperId);
	/** 修改试卷总分 */
	examPaperInfoService.isUpdateExamPaperScore(scoreWithNum);
	/** 修改试卷试题总量 */
	examPaperInfoService.isUpdateExamPaperSubjects(scoreWithNum);
	
	/** 添加试题到试卷中 */
	esmService.isAddESM(map);
	
	response.getWriter().print("试题已成功添加到试卷中!");
}


/**
 * 手动添加试题到试卷时 向 Session中存入试题信息
 * @param subjectId 试题编号
 * @param examPaperId 试卷编号
 * @param score 试题分数
 * @param handle 操作标识, 自动 OR 手动
 * @param session
 * @param response
 * @throws IOException
 */
@RequestMapping("/getChooseSubId")
public void getChooseSubjectId(
		@RequestParam("subjectId") Integer subjectId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam("score") Integer score,
		@RequestParam(value="handle", required=false) Integer handle,
		HttpSession session, HttpServletResponse response) throws IOException {
	List<String> ids = null;
	/*
	 * 添加到 Session 中需先判断该试题是否已经存在该试卷中
	 * 如果存在,则不进行添加;反之添加
	 */
	examPaper.setExamPaperId(examPaperId);
	subject.setSubjectId(subjectId);
	esm.setExamPaper(examPaper);
	esm.setSubject(subject);
	/** 验证添加记录 是否已经存在 */
	Integer esmId = esmService.getEsmByExamIdWithSubjectId(esm);
	if (esmId == null) {
		logger.error("需要添加的试题 "+subjectId+" 暂不存在试卷 "+examPaperId+" 中,可进行添加");
		ids = (List<String>) session.getAttribute("ids");
		
		/** Session 记录非空验证 */
		if (subjectId != null && score != null) {
			//第一次添加
			if (ids == null) {
				ids = new ArrayList<String>();
				ids.add((subjectId+","+score));
				logger.info("Session 添加试题:是否手动"+handle+", 试题编号:"+subjectId+", 试题分数"+score);
			} else {
				//存在就移除,反之添加
				if (ids.contains((subjectId+","+score))) {
					ids.remove((subjectId+","+score));
					logger.info("Session 移除试题:是否手动"+handle+", 试题编号:"+subjectId+", 试题分数"+score);
				} else {
					ids.add((subjectId+","+score));
					logger.info("Session 添加试题:是否手动"+handle+", 试题编号:"+subjectId+", 试题分数"+score);
				}
			}
		} else {
			logger.error("添加试题 "+subjectId+" 到 Session 失败");
			response.getWriter().print("添加失败,试题编号或试题分数异常!");
			return;
		}
	} else {
		logger.error("需要添加的试题 "+subjectId+" 已经存在试卷 "+examPaperId+" 中了, 无法进行添加");
		//同时返回添加失败的题号,用于前台方便移除选中
		response.getWriter().print("f-exists-"+subjectId);
		return;
	}
	
	session.setAttribute("ids", ids);
	
	response.getWriter().print("编号为 "+subjectId+" 的试题添加成功");
}

/**
 * 清空Session中保存的试题编号集合
 * @param session
 * @return
 */
@RequestMapping("/clearSubjectIdsWithSession")
public String isClearChooseSubjectIds(HttpSession session) {
	logger.info("清空 Session 中需要添加的试题编号集合");
	session.removeAttribute("ids");
	
	return "redirect:examPapers";
}


/**
 * 从试卷中移除试题
 * @param subjectId 试题编号
 * @param examPaperId 试卷百年好
 * @param score 试题分数
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/removeSubjectFromPaper", method={RequestMethod.GET, RequestMethod.POST})
public void removeSubjectWithExamPaper(
		@RequestParam("subjectId") Integer subjectId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam("score") Integer score,
		HttpServletResponse response) throws IOException {
	logger.info("从试卷 "+examPaperId+" 中移除试题 "+subjectId+",试题分值:"+score);
	
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("subjectNum", (-1));
	map.put("score", (-score));
	map.put("examPaperId", examPaperId);
	map.put("subjectId", subjectId);
	//修改试卷总分
	examPaperInfoService.isUpdateExamPaperScore(map);
	//修改试卷题目数量
	examPaperInfoService.isUpdateExamPaperSubjects(map);
	
	//从试卷中移除试题
	esmService.removeSubjectWithExamPaper(map);
	
	response.getWriter().print("t");
}


/**
 * 自动生成试题到试卷
 * @param examPaperId 试卷编号
 * @param subjectEasy 试题难易程度
 * @param courseId 科目编号
 * @param gradeId 年级编号
 * @param subjectSum 生成试题数量
 * @param response
 * @throws IOException
 */
@RequestMapping("/autoAddSubject")
public void isAutoAddSubjectToExamPaper(
		@RequestParam(value="examPaperId") Integer examPaperId,
		@RequestParam(value="subjectEasy", required=false) Integer subjectEasy,
		@RequestParam(value="courseId", required=false) Integer courseId,
		@RequestParam(value="gradeId", required=false) Integer gradeId,
		@RequestParam("subjectSum") Integer subjectSum,
		HttpServletResponse response) throws IOException {
	Random random = new Random();
	
	/*生成条件处理*/
	if (subjectEasy != null) {
		subject.setSubjectEasy(subjectEasy);
	}
	if (courseId != null) {
		course.setCourseId(courseId);
		subject.setCourse(course);
	}
	if (gradeId != null) {
		grade.setGradeId(gradeId);
		subject.setGrade(grade);
	}
	
	
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("subject", subject);
	map.put("startIndex", null);
	map.put("pageShow", null);
	
	List<SubjectInfo> subjects = subjectInfoService.getSubjects(map);
	int subjectTotal = subjects.size()-1;
	
	Map<String, Object> addMap = new HashMap<String, Object>();
	ArrayList<Integer> indexs = new ArrayList<Integer>();
	ArrayList<Integer> subjectIds = new ArrayList<Integer>();
	
	//添加试题总分
	int score = 0;
	for (int i=0; i<subjectSum; i++) {
		//产生随机索引
		int index = random.nextInt(subjectTotal);
		if (indexs.contains(index)) {  //随机索引已经存在
			i--;
			continue;
		} else {
			indexs.add(index);
			int subjectId = subjects.get(index).getSubjectId();
			subjectIds.add(subjectId);
			score += subjects.get(index).getSubjectScore();
			logger.info("索引 "+index+" 试题编号 "+subjectId+" 成立");
		}
	}
	
	//添加试题信息
	addMap.put("examPaperId", examPaperId);
	addMap.put("subjectIds", subjectIds);
	
	//总分和题目数量信息
	Map<String, Object> scoreWithNum = new HashMap<String, Object>();
	scoreWithNum.put("subjectNum", subjectSum);
	scoreWithNum.put("score", score);
	scoreWithNum.put("examPaperId", examPaperId);
	//修改试卷总分
	examPaperInfoService.isUpdateExamPaperScore(scoreWithNum);
	//修改试卷题目数量
	examPaperInfoService.isUpdateExamPaperSubjects(scoreWithNum);
	
	//添加
	logger.info("添加试题到试卷 "+examPaperId);
	esmService.isAddESM(addMap);
	
	response.getWriter().print("t");
}

} public class GradeInfoHandler {

@Autowired
@Qualifier("gson")
private Gson gson;
@Autowired
private GradeInfoService gradeInfoService;

private Logger logger = Logger.getLogger(GradeInfoHandler.class);

/**
 * 获取所有年级集合
 * @return
 */
@RequestMapping(value="/grades")
public ModelAndView getGrades() {
	logger.info("获取所有年级");
	
	ModelAndView model = new ModelAndView();
	model.setViewName("admin/grades");
	//获取所有年级
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);
	
	return model;
}


/**
 * 预添加年级处理
 * @param map
 * @return
 */
@RequestMapping("/preAddGrade")
public String preAddGrade(Map<String, Object> map) {
	logger.info("年级添加预处理");
	
	map.put("grade", new GradeInfo());
	
	return "admin/gradeedit";
}

/**
 * 添加年级
 * @param grade
 * @param request
 * @return
 */
@RequestMapping(value="/grade", method=RequestMethod.POST)
public String isAddGrade(GradeInfo grade, HttpServletRequest request) {
	logger.info("添加年级 "+grade);

	if (grade == null) {
		logger.error("年级 "+grade+" 为空");
		
		request.setAttribute("error", "年级添加失败,请稍后再试!");
		return "error";
	}
	int row = gradeInfoService.isAddGrade(grade);
	if (row < 1) {
		logger.error("年级添加失败");
		
		request.setAttribute("error", "年级添加失败,请稍后再试!");
		return "error";
	}
	
	return "redirect:grades";
}

/**
 * 预修改年级处理
 * @param gradeId 待修改年级编号
 * @param map
 * @return
 */
@RequestMapping(value="/grade/update/{gradeId}", method=RequestMethod.GET)
public String preUpdateGrade(@PathVariable("gradeId") Integer gradeId,
		Map<String, Object> map) {
	logger.info("年级修改预处理");
	
	map.put("grade", gradeInfoService.getGradeById(gradeId));
	
	return "/admin/gradeedit";
}

/**
 * 修改年级信息
 * @param grade
 * @param request
 * @return
 */
@RequestMapping(value="/grade/update/grade", method=RequestMethod.PUT)
public String isUpdateGrade(GradeInfo grade, HttpServletRequest request) {
	logger.info("修改年级 "+grade+" 的信息");
	
	int row = gradeInfoService.isUpdateGrade(grade);
	if (row < 1) {
		logger.error("年级修改失败");
		
		request.setAttribute("error", "年级修改失败,请稍后再试!");
		return "/error";
	}
	
	return "redirect:/grades";
}

/**
 * 删除年级
 * @param gradeId
 * @param request
 * @return
 */
@RequestMapping(value="grade/del/{gradeId}", method=RequestMethod.DELETE)
public String isDelGrade(@PathVariable("gradeId") Integer gradeId, HttpServletRequest request) {
	logger.info("删除年级 "+gradeId);
	
	int row = gradeInfoService.isDelGrade(gradeId);
	if (row < 1) {
		logger.error("年级删除失败");
		
		request.setAttribute("error", "年级删除失败,请稍后再试!");
		return "/error";
	}
	
	return "redirect:/grades";
}

} public class StudentExamInfoHandler {

@Autowired
private StudentExamInfoService studentExamInfoService;
@Autowired
private ClassInfoService classInfoService;
@Autowired
private StudentInfoService studentInfoService;
@Autowired
private Gson gson;

private Logger logger = Logger.getLogger(StudentExamInfoHandler.class);

/**
 * 所有学生考试信息 图表 Json 字符串生成
 * @param teacherId
 * @param response
 * @throws IOException
 */
@RequestMapping("/examCount")
public void getStudentExamCount(@RequestParam("tid") Integer teacherId, HttpServletResponse response) throws IOException {
	if (teacherId == null) {
		response.getWriter().print("TID-NULL");			
	} else {
		//获取当前班主任对应的班级
		ClassInfo classInfo = classInfoService.getClassByTeacherId(teacherId);
		//获取学生考试信息
		List<StudentExamInfo> stuExamInfos = studentExamInfoService.getStudentExamCountByClassId(classInfo.getClassId());
		
		response.getWriter().print(StudentExamInfoCharts.createExamCountBarJson(stuExamInfos));
	}
}


/**
 * 获取班级中的所有学生
 * @param teacherId
 * @param response
 * @throws IOException
 */
@RequestMapping("/stus")
public void getStudentsByClassId(@RequestParam("tid") Integer teacherId, HttpServletResponse response) throws IOException {
	if (teacherId == null) {
		response.getWriter().print("TID-NULL");			
	} else {
		//获取当前班主任对应的班级
		ClassInfo classInfo = classInfoService.getClassByTeacherId(teacherId);
		//获取所有学生信息
		List<StudentInfo> stus = studentInfoService.getStudentsByClassId(classInfo.getClassId());
		
		response.getWriter().print(gson.toJson(stus));
	}
}


/**
 * 班级下所有学生考试平均分等信息 图表 Json 生成
 * @param teacherId
 * @param response
 * @throws IOException
 */
@RequestMapping("/avgcounts")
public void getAllStudentAvgScoreCount(@RequestParam("tid") Integer teacherId, HttpServletResponse response) throws IOException {
	if (teacherId == null) {
		response.getWriter().print("TID-NULL");			
	} else {
		//获取当前班主任对应的班级
		ClassInfo classInfo = classInfoService.getClassByTeacherId(teacherId);
		//获取所有学生信息 平局分等信息
		List<StudentExamInfo> stuExamInfos = studentExamInfoService.getAllStudentAvgScoreCount(classInfo.getClassId());
		
		response.getWriter().print(StudentExamInfoCharts.createAvgCountLineJson(stuExamInfos));
	}
}


@RequestMapping("/stuexam")
public void getStudentExamInfoById(@RequestParam("stuId") Integer studentId, HttpServletResponse response) throws IOException {
	//获取学生考试信息
	List<StudentExamInfo> stuExamInfos = studentExamInfoService.getStudentExamInfo(studentId);
	
	response.getWriter().print(StudentExamInfoCharts.createStudentExamLineJson(stuExamInfos));
}

} public class StudentInfoHandler {

@Autowired
private StudentInfoService studentInfoService;
@Autowired
private ClassInfoService classInfoService;
@Autowired
private ExamSubjectMiddleInfoService examSubjectMiddleInfoService;
@Autowired
private ExamHistoryPaperService examHistoryPaperService;
@Autowired
private ExamChooseInfoService examChooseInfoService;
@Autowired
private ExamSubjectMiddleInfo esm;
@Autowired
private ClassInfo classInfo;
@Autowired
private ExamPaperInfo examPaper;
@Autowired
private GradeInfo grade;
@Autowired
private StudentInfo student;

@Autowired
private ExamPaperInfoService examPaperInfoService;

private Logger logger = Logger.getLogger(StudentInfoHandler.class);

/**
 * 获取学生集合
 * @param studentId 学生编号
 * @param classId 班级编号
 * @param gradeId 年级编号
 * @param startPage 起始页 default=1
 * @param pageShow 页容量 default=10
 * @return
 */
@RequestMapping("/students")
public ModelAndView getCourses(@RequestParam(value = "studentId", required = false) Integer studentId,
		@RequestParam(value = "classId", required = false) Integer classId,
		@RequestParam(value = "gradeId", required = false) Integer gradeId,
		@RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,
		@RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow ) {
	logger.info("获取学生集合  classId="+classId+", gradeId="+gradeId+", startPage="+startPage+", pageShow="+pageShow);
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/students");

	//查询条件处理
	StudentInfo student = new StudentInfo();
	if (studentId != null)
		student.setStudentId(studentId);
	if (classId != null) {
		classInfo.setClassId(classId);
		student.setClassInfo(classInfo);
	}
	if (gradeId != null) {
		grade.setGradeId(gradeId);
		student.setGrade(grade);
	}
	
	Map<String, Object> map = new HashMap<String, Object>();
	//计算当前查询起始数据索引
	int startIndex = (startPage-1) * pageShow;
	map.put("student", student);
	map.put("startIndex", startIndex);
	map.put("pageShow", pageShow);
	List<StudentInfo> students = studentInfoService.getStudents(map);
	model.addObject("students", students);
	
	//获取学生总量
	int studentTotal = studentInfoService.getStudentTotal();
	//计算总页数
	int pageTotal = 1;
	if (studentTotal % pageShow == 0)
		pageTotal = studentTotal / pageShow;
	else
		pageTotal = studentTotal / pageShow + 1;			
	model.addObject("pageTotal", pageTotal);
	model.addObject("pageNow", startPage);

	return model;
}

/**
 * 根据编号获取学生信息
 * @param studentId
 * @return
 */
@RequestMapping("/student/{studentId}")
public ModelAndView getCourseById(@PathVariable("studentId") Integer studentId) {
	logger.info("获取学生 " + studentId);
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/studentedit");

	StudentInfo student = studentInfoService.getStudentById(studentId);
	model.addObject("student", student);
	List<ClassInfo> classes = classInfoService.getClasses(null);
	model.addObject("classes", classes);

	return model;
}

/**
 * 添加/修改学生信息
 * @param studentId
 * @param isUpdate 操作标识
 * @param studentName
 * @param studentAccount
 * @param studentPwd
 * @param classId
 * @return
 */
@RequestMapping(value = "/student/student", method = RequestMethod.POST)
public String isUpdateOrAddCourse(
		@RequestParam(value = "studentId", required = false) Integer studentId,
		@RequestParam(value = "isupdate", required = false) Integer isUpdate,
		@RequestParam(value = "studentName", required = false) String studentName,
		@RequestParam("studentAccount") String studentAccount,
		@RequestParam("studentPwd") String studentPwd,
		@RequestParam("classId") Integer classId) {

	StudentInfo student = new StudentInfo();
		student.setStudentId(studentId);
		student.setStudentName(studentName);
		student.setStudentAccount(studentAccount);
		student.setStudentPwd(studentPwd);
		classInfo.setClassId(classId);
		student.setClassInfo(classInfo);

	if (isUpdate != null) {
		logger.info("修改学生 " + student + " 的信息");
		int row = studentInfoService.isUpdateStudent(student);
	} else {
		logger.info("添加学生 " + student + " 的信息");
		int row = studentInfoService.isAddStudent(student);
	}

	return "redirect:/students";
}

/**
 * 删除学生
 * @param studentId
 * @return
 */
@RequestMapping(value = "/student/{studentId}", method = RequestMethod.DELETE)
public String isDelTeacher(@PathVariable("studentId") Integer studentId) {
	logger.info("删除学生 " + studentId);

	int row = studentInfoService.isDelStudent(studentId);

	return "redirect:/students";
}

/**
 * 预添加学生
 * @return
 */
@RequestMapping("/preAddStudent")
public ModelAndView preAddStudent() {
	logger.info("预添加学生信息");
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/studentedit");
	List<ClassInfo> classes = classInfoService.getClasses(null);
	model.addObject("classes", classes);

	return model;
}

/**
 * 学生考试登录验证
 * 
 * 此处验证并不合理 登录验证实现如下:
 *   前台学生登录传入账户,后台根据账户获取学生密码
 *   返回学生密码,前台登录焦点离开密码框使用 JavaScript 判断
 * 
 * @param studentAccount 学生登录账户
 * @param response
 * @throws IOException
 */
@RequestMapping("/validateLoginStudent")
public void validateLoginStudent(@RequestParam("studentAccount") String studentAccount,
		HttpServletResponse response) throws IOException {
	logger.info("学生账户 "+studentAccount+",尝试登录考试");
	
	//获取需要登录的学生对象
	StudentInfo student = studentInfoService.getStudentByAccountAndPwd(studentAccount);
	
	if (student == null) {
		logger.error("登录学生账户 "+studentAccount+" 不存在");
		response.getWriter().print("n");
	} else {
		logger.error("登录学生账户 "+studentAccount+" 存在");
		response.getWriter().print(student.getStudentPwd());
	}
}

/**
 * 学生登录考试
 * @param student 登录学生
 * @param request
 * @return
 */
@RequestMapping(value="/studentLogin", method=RequestMethod.POST)
public ModelAndView studentLogin(StudentInfo student, HttpServletRequest request) {
	ModelAndView model = new ModelAndView();
	StudentInfo loginStudent = studentInfoService.getStudentByAccountAndPwd(student.getStudentAccount());
	logger.info("学生 "+loginStudent+" 有效登录");
	if(loginStudent == null || !student.getStudentPwd().equals(loginStudent.getStudentPwd())){
		model.setViewName("reception/suc");
		model.addObject("success", "密码错误");
		return model;
	}
	request.getSession().setAttribute("loginStudent", loginStudent);
	
	model.setViewName("reception/suc");
	model.addObject("success", "登录成功");
	
	return model;
}

/**
 * 退出登录
 * @param session
 * @return
 */
@RequestMapping("/exit")
public String studentClearLogin(HttpSession session) {
	StudentInfo studnet = (StudentInfo) session.getAttribute("loginStudent");
	logger.info("学生 "+studnet.getStudentName()+", 编号 "+studnet.getStudentId()+" 退出登录");
	session.removeAttribute("loginStudent");
	
	return "redirect:index.jsp";
}

/**
 * 学生注册 验证当前账户是否被占用
 * @param studentAccount 注册账户
 * @param response
 * @throws IOException
 */
@RequestMapping("/validateAccount")
public void validateRegisterAccount(@RequestParam("studentAccount") String studentAccount,
		HttpServletResponse response) throws IOException {
	logger.info("验证学生账户 "+studentAccount+",是否已被注册");
	
	StudentInfo student = studentInfoService.getStudentByAccountAndPwd(studentAccount);
	
	if (student == null) {
		logger.error("注册学生账户 "+studentAccount+" 可以注册");
		response.getWriter().print("t");
	} else {
		logger.error("注册学生账户 "+studentAccount+" 已被注册");
		response.getWriter().print("f");
	}
}

/**
 * 学生注册
 * @param studentName
 * @param studentAccount
 * @param studentPwd
 * @param classId
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/studentReg", method=RequestMethod.POST)
public void studentRegister(
		@RequestParam("name") String studentName,
		@RequestParam("account") String studentAccount,
		@RequestParam("pwd") String studentPwd,
		@RequestParam("classId") Integer classId,
		HttpServletResponse response) throws IOException {
	ModelAndView model = new ModelAndView();
	student.setStudentName(studentName);
	student.setStudentAccount(studentAccount);
	student.setStudentPwd(studentPwd);
	classInfo.setClassId(classId);
	student.setClassInfo(classInfo);
	logger.info("学生注册 "+student);
	int row = studentInfoService.isAddStudent(student);
	
	response.getWriter().print("t");
}

/**
 * 预注册
 * @return
 */
@RequestMapping("/preStudentReg")
public ModelAndView preStudentReg() {
	ModelAndView model = new ModelAndView();
	model.setViewName("reception/register");
	model.addObject("classs", classInfoService.getClasses(null));
	return model;
}

/**
 * 学生进入考试
 * @param classId 班级编号
 * @param examPaperId 试卷编号
 * @param studentId 考生编号
 * @param examTime 考试时间
 * @param beginTime 考试开始时间
 * @param gradeId 年级编号
 * @param session
 * @return
 */
@RequestMapping("/begin")
public ModelAndView beginExam(
		@RequestParam("classId") Integer classId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam(value="studentId", required=false) Integer studentId,
		@RequestParam("examTime") Integer examTime,
		@RequestParam("beginTime") String beginTime,
		@RequestParam("gradeId") Integer gradeId,
		HttpSession session) {
	ModelAndView model = new ModelAndView();
	
	/*
	 * 查询该考试当前进入的试卷是否已经在历史记录中存在
	 * 如果存在,则不能再次进入考试; 反之进入考试
	 */
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("studentId", studentId);
	map.put("examPaperId", examPaperId);
	int count = examHistoryPaperService.getHistoryInfoWithIds(map);
	if(session.getAttribute("loginStudent") == null) {
		model.addObject("error", "请先登录后再操作");
		model.setViewName("error");
		return model;
	} else if (count >= 1) {
		model.addObject("error", "你已经考试过了");
		model.setViewName("error");
		return model;
	} else {			
		logger.info("学生 "+studentId+" 进入考试 班级 "+classId+" 试卷 "+examPaperId);
		model.setViewName("/reception/exam");
		
		ExamPaperInfo examPaper = new ExamPaperInfo();
		examPaper.setExamPaperId(examPaperId);
		esm.setExamPaper(examPaper);
		//获取试卷 试题集合
		List<ExamSubjectMiddleInfo> esms = examSubjectMiddleInfoService.getExamPaperWithSubject(esm);
		logger.info("考试试题总量 "+esms.size());
		
		//获取当前考生在当前试卷中已选答案记录
		Map<String, Object> choosedMap = new HashMap<String, Object>();
		choosedMap.put("studentId", studentId);
		choosedMap.put("examPaperId", examPaperId);
		List<ExamChooseInfo> chooses = examChooseInfoService.getChooseInfoWithSumScore(choosedMap); 
		if (chooses == null || chooses.size() == 0) {
			model.addObject("chooses", null);
		} else {
			model.addObject("chooses", chooses);				
		}
		
		
		model.addObject("esms", esms);
		model.addObject("sumSubject", esms.size());
		model.addObject("examPaperId", examPaperId);
		model.addObject("examTime", examTime);
		model.addObject("beginTime", beginTime);
		model.addObject("classId", classId);
		model.addObject("gradeId", gradeId);
		
		return model;
	}
}


/**
 * 获取学生历史考试记录
 * @param studentId 学生编号
 * @return
 */
@RequestMapping("/history/{studentId}")
public ModelAndView getExamHistoryInfo(@PathVariable("studentId") Integer studentId) {
	ModelAndView model = new ModelAndView();
	
	if (studentId == null) {
		logger.error("学生编号 为空");
		model.setViewName("error");
		return model;
	}
	logger.info("学生 "+studentId+" 获取考试历史记录");
	//获取历史考试信息记录集合
	List<ExamHistoryPaper> ehps = examHistoryPaperService.getExamHistoryToStudent(studentId);
	model.addObject("ehps", ehps);
	model.setViewName("/reception/examHistory");
	
	return model;
}


/**
 * 考生提交考试
 * @param studentId
 * @param examPaperId
 * @param classId
 * @param gradeId
 * @return
 */
@RequestMapping(value="/submit", method={RequestMethod.POST, RequestMethod.GET})
public String examSubmit(
		@RequestParam("studentId") Integer studentId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam("classId") Integer classId,
		@RequestParam("gradeId") Integer gradeId) {
	logger.info("学生 "+studentId+" 提交了试卷 "+examPaperId);
	
	//获取当前学生当前试卷所选择的全部答案
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("studentId", studentId);
	map.put("examPaperId", examPaperId);
	List<ExamChooseInfo> chooses = examChooseInfoService.getChooseInfoWithSumScore(map);
	logger.info("学生 "+studentId+" 共选择了 "+chooses.size()+" 道题");
	
	//总分记录
	int sumScore = 0;
	for (ExamChooseInfo choose : chooses) {
		SubjectInfo subject = choose.getSubject();
		String chooseResult = choose.getChooseResult();
		String rightResult = subject.getRightResult();
		
		if (chooseResult.equals(rightResult)) {	//答案正确
			sumScore += subject.getSubjectScore();
			logger.info("学生 "+studentId+" 第 "+subject.getSubjectId()+" 选择正确答案 "+chooseResult+" 当前总分 "+sumScore);
		} else {
			logger.info("学生 "+studentId+" 第 "+subject.getSubjectId()+" 答案选择错误 "+chooseResult+" 正确答案为 "+rightResult+" 当前总分 "+sumScore);				
		}
	}
	
	/*
	 * 首先判断当前记录是否已经添加过
	 * 防止当前学生点击提交后,系统倒计时再次进行提交
	 */
	int count = examHistoryPaperService.getHistoryInfoWithIds(map);
	
	if (count == 0) {
		//添加到历史记录
		map.put("examScore", sumScore);
		int row = examHistoryPaperService.isAddExamHistory(map);
		logger.info("学生 "+studentId+" 提交的试卷 "+examPaperId+" 已成功处理,并添加到历史记录中");
	}
	
	return "redirect:willexams?gradeId="+gradeId+"&classId="+classId+"&studentId="+studentId;
}


/**
 * 学生回顾试卷  --  后台教师查看也调用此方法
 * @param studentId
 * @param examPaperId
 * @param score
 * @param examPaperName
 * @param studentName  后台教师查看需传入学生姓名
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping("/review")
public ModelAndView reViewExam(
		@RequestParam("studentId") Integer studentId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam("score") Integer score,
		@RequestParam("examPaperName") String examPaperName,
		@RequestParam(value="studentName", required=false) String studentName) throws UnsupportedEncodingException {
	ModelAndView model = new ModelAndView();
	if (studentId == null) {
		model.addObject("error", "请先登录后再操作");
		model.setViewName("error");
		return model;
	} else {
		//获取当前试卷的试题集合  -- 前台判断需要
		examPaper.setExamPaperId(examPaperId);
		esm.setExamPaper(examPaper);
		List<ExamSubjectMiddleInfo> esms = examSubjectMiddleInfoService.getExamPaperWithSubject(esm);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("studentId", studentId);
		map.put("examPaperId", examPaperId);
		
		//获取当前回顾试卷 试题、选择答案 信息
		List<ExamChooseInfo> reviews = examChooseInfoService.getChooseInfoWithExamSubject(map);
		logger.info("学生 "+studentId+" 回顾试卷 "+examPaperId+" 试题数量 "+reviews.size());
		//设置试卷名称、试卷总分
		model.addObject("examPaperName", examPaperName);
		model.addObject("score", score);
		
		model.setViewName("reception/review");
		model.addObject("views", reviews);
		
		model.addObject("esms", esms);
		if (studentName != null) model.addObject("studentName", studentName);
		
		model.addObject("ExamedPaper", examPaperInfoService.getExamPaper(examPaperId));
		
		return model;
	}
}

/**
 * 学生查看自己信息
 * @param studentId
 * @return
 */
@RequestMapping("/self/{studentId}")
public ModelAndView selfInfo(@PathVariable("studentId") Integer studentId) {
	StudentInfo stu = studentInfoService.getStudentById(studentId);
	
	ModelAndView model = new ModelAndView();
	model.setViewName("/reception/self");
	model.addObject("self", stu);
	
	
	return model;
}


/**
 * 学生修改密码
 * @param pwd
 * @param studentId
 * @param response
 * @throws IOException
 */
@RequestMapping("/reset/{pwd}/{studentId}")
public void isResetPwd(
		@PathVariable("pwd") String pwd,
		@PathVariable("studentId") Integer studentId,
		HttpServletResponse response) throws IOException {
	logger.info("学生 "+studentId+" 修改密码");
	student.setStudentId(studentId);
	student.setStudentPwd(pwd);
	
	int row = studentInfoService.isResetPwdWithStu(student);
	
	if (row > 0) {
		response.getWriter().print("t");
	} else {
		response.getWriter().print("f");			
	}
}

public class SubjectInfoHandler {

@Autowired
private SubjectInfoService subjectInfoService;
@Autowired
private CourseInfoService courseInfoService;
@Autowired
private GradeInfoService gradeInfoService;
@Autowired
private ExamPaperInfoService examPaperInfoService;
@Autowired
private ExamSubjectMiddleInfoService esmService;
@Autowired
private SubjectInfo subject;
@Autowired
private CourseInfo course;
@Autowired
private GradeInfo grade;
@Autowired
private ExamPaperInfo examPaper;

private Logger logger = Logger.getLogger(SubjectInfoHandler.class);


/**
 * 查询试题集合
 * @param subjectId    查询条件
 * @param courseId
 * @param gradeId
 * @param startPage
 * @param pageShow
 * @param handAdd  标识 是否为需要进行手动添加试题到试卷而发起的请求
 * @param examPaperId
 * @param session
 * @return
 */
@RequestMapping(value="/subjects", method=RequestMethod.GET)
public ModelAndView getTeachers(
		@RequestParam(value="subjectId", required=false) Integer subjectId,
		@RequestParam(value="courseId", required=false) Integer courseId,
		@RequestParam(value="gradeId", required=false) Integer gradeId,
		@RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,
		@RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow,
		@RequestParam(value="handAdd", required=false) Integer handAdd,
		@RequestParam(value="examPaperId", required=false) Integer examPaperId,
		HttpSession session) {
	logger.info("查询试题集合");
	
	ModelAndView model = new ModelAndView();
	model.setViewName("admin/subjects");
	
	//条件处理
	if (subjectId != null) subject.setSubjectId(subjectId);
	if (courseId != null) course.setCourseId(courseId);
	if (gradeId != null) grade.setGradeId(gradeId);
	
	Map<String, Object> map = new HashMap<String, Object>();
	//计算当前查询起始数据索引
	int startIndex = (startPage-1) * pageShow;
	//map.put("subject", subject);
	map.put("startIndex", startIndex);
	map.put("pageShow", pageShow);
	List<SubjectInfo> subjects = subjectInfoService.getSubjects(map);
	model.addObject("subjects", subjects);
	
	//获取试题总量
	int subjectTotal = subjectInfoService.getSubjectTotal();
	//计算总页数
	int pageTotal = 1;
	if (subjectTotal % pageShow == 0)
		pageTotal = subjectTotal / pageShow;
	else
		pageTotal = subjectTotal / pageShow + 1;			
	model.addObject("pageTotal", pageTotal);
	model.addObject("pageNow", startPage);
	
	//是否为需要进行手动添加试题到试卷而发起的请求
	if (handAdd != null && handAdd == 1) {
		model.addObject("handAdd", "1");
	}
	//如果是手动添加试题到试卷,则需要返回试卷编号, 且返回当前已经选择试题数量
	if (examPaperId != null) {
		model.addObject("examPaperId", examPaperId);
		List<String> ids = (List<String>) session.getAttribute("ids");
		if (ids == null) {
			model.addObject("choosed", 0);
		} else {				
			model.addObject("choosed", ids.size());
		}
	}
	
	return model;
}


/**
 * 添加试题
 * @param subject
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/addSubject", method=RequestMethod.POST)
public void addSubject(SubjectInfo subject, HttpServletResponse response) throws IOException {
	if(subject != null){
		subject.setSubjectName(trimChar(subject.getSubjectName()));
		subject.setRightResult(trimChar(subject.getRightResult()));
		subject.setOptionA(trimChar(subject.getOptionA()));
		subject.setOptionB(trimChar(subject.getOptionB()));
		subject.setOptionC(trimChar(subject.getOptionC()));
		subject.setOptionD(trimChar(subject.getOptionD()));
	}
	int row = subjectInfoService.isAddSubject(subject);
	
	response.getWriter().print("试题添加成功!");
}


/**
 * 删除试题
 * @param subjectId
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/delSubject", method=RequestMethod.POST)
public void delSubject(@RequestParam("subjectId") Integer subjectId,
		HttpServletResponse response) throws IOException {
	logger.info("删除试题 "+subjectId);
	
	int row = subjectInfoService.isDelSubject(subjectId);
	
	if (row > 0) {
		response.getWriter().print("t");
	} else {
		response.getWriter().print("f");			
	}
}


/**
 * 修改试题 -- 获取待修改试题信息
 * @param subjectId
 * @return
 */
@RequestMapping("/subject/{subjectId}")
public ModelAndView updateSubject(@PathVariable("subjectId") Integer subjectId) {
	logger.info("修改试题 "+subjectId+" 的信息(获取试题信息)");
	
	SubjectInfo subject = subjectInfoService.getSubjectWithId(subjectId);
	
	ModelAndView model = new ModelAndView("/admin/subject-test");
	model.addObject("subject", subject);
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);
	model.addObject("courses", courseInfoService.getCourses(null));
	return model;
}

/**
 * 修改试题
 * @param subject
 * @param response
 * @throws IOException
 */
@RequestMapping(value="/updateSubject", method=RequestMethod.POST)
public void updateSubject(SubjectInfo subject, HttpServletResponse response) throws IOException {
	logger.info("修改试题 "+subject.getSubjectId()+" 的信息(正式)");

	if(subject != null){
		subject.setSubjectName(trimChar(subject.getSubjectName()));
		subject.setRightResult(trimChar(subject.getRightResult()));
		subject.setOptionA(trimChar(subject.getOptionA()));
		subject.setOptionB(trimChar(subject.getOptionB()));
		subject.setOptionC(trimChar(subject.getOptionC()));
		subject.setOptionD(trimChar(subject.getOptionD()));
	}
	int row = subjectInfoService.isUpdateSubject(subject);
	if (row > 0) {
		response.getWriter().print("试题修改成功!");
	} else {
		response.getWriter().print("试题修改失败!");
	}
}


/**
 * 初始化 导入 excel 试题信息
 * @return
 */
@RequestMapping(value="/initImport")
public ModelAndView initImportExcel() {
	logger.info("初始化 导入 EXCEL 试题信息");
	ModelAndView model = new ModelAndView("admin/importSubject");
	//获取所有科目
	List<CourseInfo> courses = courseInfoService.getCourses(null);
	//获取所有年级
	List<GradeInfo> grades = gradeInfoService.getGrades();
	//获取所有试卷名称
	List<ExamPaperInfo> examPapers = examPaperInfoService.getExamPapersClear();
	
	model.addObject("courses", courses);
	model.addObject("grades", grades);
	model.addObject("examPapers", examPapers);
	
	return model;
}


/**
 * 试题导入 处理
 * @param request
 * @param importOption
 * @param excel
 */
@RequestMapping(value="/dispatcherUpload", method=RequestMethod.POST)
public ModelAndView dispatcherUpload(HttpServletRequest request,
		@RequestParam("division") Integer division,
		@RequestParam("courseId") Integer courseId,
		@RequestParam("gradeId") Integer gradeId,
		@RequestParam("examPaperId") Integer examPaperId,
		@RequestParam("importOption") String importOption,
		@RequestParam("examPaperEasy") Integer examPaperEasy,
		@RequestParam("examPaperName") String examPaperName,
		@RequestParam("examPaperTime") Integer examPaperTime,
		@RequestParam("inputfile") MultipartFile excel) {
	ModelAndView model = new ModelAndView("reception/suc");
	String savePath = "";
	
	try {
		/** 保存上传 excel 文件 */
		savePath = saveUploadFile(excel, request.getRealPath("/WEB-INF/upload"));
		
		/** 解析上传 excel 文件, 得到试题集合 */
		List<SubjectInfo> subjects = SubjectImportUtil.parseSubjectExcel(savePath, courseId, gradeId, division);
		
		/** 只添加试题 */
		if ("0".equals(importOption)) {
			Map<String, Object> subjectsMap = new HashMap<String, Object>();
			subjectsMap.put("subjects", subjects);
			
			importSubejctOnly(subjects, subjectsMap);
		}
		/** 添加试题到指定的已有试卷 */
		else if ("1".equals(importOption)) {
			dispatcherExamPaperAndSubject(subjects, examPaperId);
		}
		/** 添加试题到新建试卷 */
		else if ("2".equals(importOption)) {
			/** 创建新试卷 */
			examPaper.setExamPaperName(examPaperName);
			examPaper.setExamPaperEasy(examPaperEasy);
			examPaper.setExamPaperTime(examPaperTime);
			grade.setGradeId(gradeId);
			examPaper.setGrade(grade);
			examPaper.setDivision(division);
			int row = examPaperInfoService.isAddExamPaper(examPaper);
			logger.info("添加的新试卷 编号 "+examPaper.getExamPaperId());
			
			dispatcherExamPaperAndSubject(subjects, examPaper.getExamPaperId());
		}
		
		if (subjects.size() == 0) {
			model.addObject("success", "操作处理失败,共添加 <b style='color:red;'>"+subjects.size()+"</b> 道题, 请检查上传数据正确性!");
		} else {
			model.addObject("success", "操作处理成功,共添加 "+subjects.size()+" 道题");
		}
		
	} catch (Exception e) {
		e.printStackTrace();
		model.setViewName("error");
		model.addObject("error", "上传失败, 请检查上传数据合理性或联系管理员!");
	} finally {
		/** 删除上传文件 */
		deleteUploadFile(savePath);
	}
	return model;
}


/**
 * 保存上传 excel 文件
 * @param file 上传文件
 * @return 保存路径
 */
private String saveUploadFile(MultipartFile file, String rootPath) {
	String fileName = file.getOriginalFilename();
	logger.info("保存上传文件 "+fileName+" 到 "+rootPath);
	
	try {
		file.transferTo(new File(rootPath+"/"+fileName));
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	return rootPath+"/"+fileName;
}


/**
 * 只将试题上传到数据库
 * @param subjects
 * @param subjectsMap
 */
private void importSubejctOnly(List<SubjectInfo> subjects, Map<String, Object> subjectsMap) {
	try {
		if (subjects != null && subjects.size() > 0) {
			//添加试题
			int row = subjectInfoService.isAddSubjects(subjectsMap);
			logger.info("只将 excel 中的试题添加到数据库成功 SIZE "+subjects.size());
		} else {
			logger.info("上传试题文件中不存在试题,或解析失败");
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}


/**
 * 处理 试题 添加到 试卷
 * @param subjects 试题集合
 * @param examPaperId 对应试卷编号
 */
private void dispatcherExamPaperAndSubject(List<SubjectInfo> subjects, Integer examPaperId) {
	List<Integer> subjectIds = new ArrayList<Integer>();
	//试题总量统计
	int count = 0;
	//试题总分统计
	int score = 0;
	
	/** 添加试题 */
	for (SubjectInfo subjectInfo : subjects) {
		int row1 = subjectInfoService.isAddSubject(subjectInfo);
		score += subjectInfo.getSubjectScore();
		subjectIds.add(subjectInfo.getSubjectId());
		count++;
	}
	logger.info("添加试题 SIZE "+count);
	
	/** 添加试题到试卷 */
	Map<String, Object> esmMap = new HashMap<String, Object>();
	esmMap.put("examPaperId", examPaperId);
	esmMap.put("subjectIds", subjectIds);
	esmService.isAddESM(esmMap);
	logger.info("添加试题 SIZE "+count+" SCORE "+score+" 到试卷 "+examPaperId);
	
	//修改试卷信息
	Map<String, Object> scoreWithNum = new HashMap<String, Object>();
	scoreWithNum.put("subjectNum", count);
	scoreWithNum.put("score", score);
	scoreWithNum.put("examPaperId", examPaperId);
	/** 修改试卷总分 */
	examPaperInfoService.isUpdateExamPaperScore(scoreWithNum);
	/** 修改试卷试题总量 */
	examPaperInfoService.isUpdateExamPaperSubjects(scoreWithNum);
}


/**
 * 删除上传文件
 * @param filePath 文件路径
 */
private void deleteUploadFile(String filePath) {
	File file = new File(filePath);
	
	if (file.exists()) {
		file.delete();
		logger.info("上传文件已被删除 "+filePath);
	}
}

/**
 * 预添加试题
 * @return
 */
@RequestMapping("/preAddSubject")
public ModelAndView preAddStudent() {
	logger.info("预添加试卷信息");
	ModelAndView model = new ModelAndView();
	model.setViewName("/admin/subject-test");
	List<GradeInfo> grades = gradeInfoService.getGrades();
	model.addObject("grades", grades);
	model.addObject("courses", courseInfoService.getCourses(null));
	return model;
}

private String trimChar(String str){
	if(str != null){
		return str.replaceAll("^,*|,*$", "");
	}
	return str;
}

} public class TeacherInfoHandler {

@Autowired
private TeacherInfoService teacherInfoService;

private Logger logger = Logger.getLogger(TeacherInfoHandler.class);


/**
 * 获取  验证教师信息
 * @param teacherAccount
 * @param response
 * @throws Exception
 */
@RequestMapping(value="/validateTeacher", method=RequestMethod.POST)
public void queryTeacherExists(@RequestParam(value="account") String teacherAccount,
		HttpServletResponse response) throws Exception {
	logger.info("获取教师 "+teacherAccount+" 的信息");

	TeacherInfo teacherInfo = null;
	teacherInfo = teacherInfoService.getTeacherByAccount(teacherAccount);
	
	//教师账户不存在
	if (teacherInfo == null) {
		response.getWriter().print("1");
	} else {			
		response.getWriter().print(teacherInfo.getTeacherPwd());
	}
}


/**
 * 教师登录
 * @param teacherAccount
 * @param request
 * @return
 */
@RequestMapping(value="/teacherlogin", method=RequestMethod.POST)
public String teacherLogin(@RequestParam("teacherAccount") String teacherAccount,
		HttpServletRequest request) {
	if (teacherAccount == null || "".equals(teacherAccount)) {
		logger.error("教师账号为空");
		request.setAttribute("error", "登录信息有误");
		return "/error";
	}
	logger.info("教师  "+teacherAccount+" 登录");
	
	//获取当前登录教师
	TeacherInfo teacherInfo = teacherInfoService.getTeacherByAccount(teacherAccount);
	
	if(teacherInfo == null){
		logger.error("教师账号为空");
		request.setAttribute("error", "账号不存在!");
		return "/error";
	}
	String teacherPwd = request.getParameter("teacherPwd");
	if(!teacherInfo.getTeacherPwd().equals(teacherPwd)){
		logger.error("密码错误");
		request.setAttribute("error", "密码错误!");
		return "/error";
	}
	//将当前登录教师 后台权限存入 Session
	request.getSession().setAttribute("adminPower", teacherInfo.getAdminPower());
	request.getSession().setAttribute("loginTeacher", teacherInfo);
	
	return "redirect:admin/index.jsp";
}

/**
 * 教师查看自己的信息
 * @param teacherId
 * @return
 */
@RequestMapping("/selfinfo/{teacherId}")
public ModelAndView loginTeacherSelf(@PathVariable("teacherId") Integer teacherId) {
	ModelAndView model = new ModelAndView();
	logger.error("教师 "+teacherId+" 查看自己的信息");
	if (teacherId == null) {
		model.setViewName("../error");
		return model;
	} else {
		List<TeacherInfo> teachers = new ArrayList<TeacherInfo>();
		TeacherInfo teacher = teacherInfoService.getTeacherById(teacherId);
		teachers.add(teacher);
		model.addObject("teachers", teachers);
		model.setViewName("/admin/teachers");
		
		return model;
	}
}


/**
 * 教师退出登录
 * @throws IOException 
 */
@RequestMapping("/exitTeacher")
public void exitTeacher(HttpSession session, HttpServletResponse response) throws IOException {
	session.removeAttribute("loginTeacher");
	session.removeAttribute("adminPower");
	
	response.sendRedirect("admin/login.jsp");
}


/**
 * 查询教师集合
 * @param startPage
 * @param pageShow
 * @return
 */
@RequestMapping(value="/teachers", method=RequestMethod.GET)
public ModelAndView getTeachers(
		@RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,  //当前页码,默认第一页
		@RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow /*每页显示数据量默认10条*/) {
	logger.info("查询教师集合");
	
	ModelAndView model = new ModelAndView();
	model.setViewName("admin/teachers");
	
	List<TeacherInfo> teachers;
	
	Map<String, Object> map = new HashMap<String, Object>();
	//计算当前查询起始数据索引
	int startIndex = (startPage-1) * pageShow;
	map.put("startIndex", startIndex);
	map.put("pageShow", pageShow);
	map.put("teacher", null);
	teachers = teacherInfoService.getTeachers(map);
	model.addObject("teachers", teachers);
	
	//获取教师总量
	int teacherTotal = teacherInfoService.getTeacherTotal();
	//计算总页数
	int pageTotal = 1;
	if (teacherTotal % pageShow == 0)
		pageTotal = teacherTotal / pageShow;
	else
		pageTotal = teacherTotal / pageShow + 1;			
	model.addObject("pageTotal", pageTotal);
	model.addObject("pageNow", startPage);
	
	return model;
}

/**
 * 预修改教师
 * @param teacherId
 * @return
 */
@RequestMapping(value="/teacher/{teacherId}", method=RequestMethod.GET)
public ModelAndView preUpdateTeacher(@PathVariable("teacherId") Integer teacherId) {
	logger.info("预修改教师处理");
	
	ModelAndView model = new ModelAndView();
	//获取要修改教师
	TeacherInfo teacher = teacherInfoService.getTeacherById(teacherId);
	model.setViewName("/admin/teacheredit");
	model.addObject("teacher", teacher);
	
	return model;
}

/**
 * 修改/添加 教师
 * @param teacherId
 * @param isUpdate 操作标识
 * @param teacherName
 * @param teacherAccount
 * @param teacherPwd
 * @param adminPower
 * @return
 */
@RequestMapping(value="/teacher/teacher", method=RequestMethod.POST)
public String isUpdateOrAddTeacher(@RequestParam(value="teacherId", required=false) Integer teacherId,
		@RequestParam(value="isupdate", required=false) Integer isUpdate,
		@RequestParam("teacherName") String teacherName,
		@RequestParam("teacherAccount") String teacherAccount,
		@RequestParam("teacherPwd") String teacherPwd,
		@RequestParam("adminPower") Integer adminPower) {
	
	TeacherInfo teacher = new TeacherInfo();
		teacher.setTeacherId(teacherId);
		teacher.setTeacherName(teacherName);
		teacher.setTeacherAccount(teacherAccount);
		teacher.setTeacherPwd(teacherPwd);
		teacher.setAdminPower(adminPower);
	
	if (isUpdate != null) {  //修改
		logger.info("修改教师 "+teacher+" 的信息");
		int row = teacherInfoService.isUpdateTeacherInfo(teacher);			
	} else {  //添加
		logger.info("添加教师 "+teacher+" 的信息");
		int row = teacherInfoService.isAddTeacherInfo(teacher);
	}
	
	return "redirect:/teachers";
}


/**
 * 删除教师
 * @param teacherId
 * @return
 */
@RequestMapping(value="/teacher/{teacherId}", method=RequestMethod.DELETE)
public String isDelTeacher(@PathVariable("teacherId") Integer teacherId) {
	logger.info("删除教师 "+teacherId);
	
	int row = teacherInfoService.isDelTeacherInfo(teacherId);
	
	return "redirect:/teachers";
}

}

public class LoginInterceptor extends HandlerInterceptorAdapter {

private Logger logger = Logger.getLogger(LoginInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request,
		HttpServletResponse response, Object handler) throws Exception {
	
	HttpSession session = request.getSession();
	if (session.getAttribute("loginTeacher") != null) {
		return true;
	} else {
		logger.info("检测到未登录访问后台内容操作");
		//如果没有登录,跳转至登录页面
		response.sendRedirect("admin/login.jsp");
		
		return false;
	}
}

} public class ExamSubjectMiddleInfoTest {

private SqlSessionFactory sqlSessionFactory;

public void init() throws Exception {
	InputStream is = Resources.getResourceAsStream("test/SqlMapConfig-test.xml");
	sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}

@Test
public void addTest() throws Exception {
	init();
	
	SqlSession session = sqlSessionFactory.openSession();
	
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("examPaperId", 2);
	ArrayList<Integer> subjectIds = new ArrayList<Integer>();
	subjectIds.add(100);
	subjectIds.add(200);
	subjectIds.add(300);
	subjectIds.add(400);
	map.put("subjectIds", subjectIds);
	
	session.insert("isAddESM", map);
	session.commit();
}

} public class StudentInfoTest {

private SqlSessionFactory sqlSessionFactory;

public void init() throws Exception {
	InputStream is = Resources.getResourceAsStream("test/SqlMapConfig-test.xml");
	sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}

@Test
public void test2() throws Exception {
	init();
	
	StudentInfo student = new StudentInfo();
	ClassInfo classInfo = new ClassInfo();
	classInfo.setClassId(1);
	student.setClassInfo(classInfo);
	
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("student", student);
	map.put("startIndex", 0);
	map.put("pageShow", 3);
	
	SqlSession session = sqlSessionFactory.openSession();
	List<StudentInfo> students = session.selectList("getStudents", map);
	System.out.println(students);

	session.close();
}

} public class TeacherInfoTest {

private SqlSessionFactory sqlSessionFactory;

public void init() throws Exception {
	InputStream is = Resources.getResourceAsStream("test/SqlMapConfig-test.xml");
	sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}

//分页测试
@Test
public void paginationTest() throws Exception {
	init();
	
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("startPage", 0);
	map.put("pageShow", 2);
	
	SqlSession session = sqlSessionFactory.openSession();
	List<TeacherInfo> teachers = session.selectList("getTest", map);
	System.out.println(teachers);

	session.close();
}

@Test
public void test2() throws Exception {
	init();
	
	TeacherInfo teacherInfo = new TeacherInfo();
	teacherInfo.setIsWork(1);

	Map<String, Object> map = new HashMap<String, Object>();
	map.put("teacher", teacherInfo);
	map.put("startIndex", 1);
	map.put("pageShow", 3);
	
	SqlSession session = sqlSessionFactory.openSession();
	List<TeacherInfo> teachers = session.selectList("getTeachers", map);
	System.out.println(teachers);

	session.close();
}

} public class SubjectImportUtil { private static int subjectNameIndex; private static int optionAIndex; private static int optionBIndex; private static int optionCIndex; private static int optionDIndex; private static int rightResultIndex; private static int subjectScoreIndex; private static int subjectTypeIndex; private static int subjectEasyIndex;

/**
 * 解析导入 excel 生成试题对象
 * @param filePath
 * @param indexs
 * @param courseId
 * @param gradeId
 * @param division
 * @return
 */
public static List<SubjectInfo> parseSubjectExcel(String filePath, Integer courseId, Integer gradeId, Integer division) {
	List<SubjectInfo> subjects = new LinkedList<SubjectInfo>();
	try {
		//读取工作本
		XSSFWorkbook workBook = new XSSFWorkbook(filePath);
		//读取工作簿
		XSSFSheet sheet = workBook.getSheet("Sheet1");
		//总行数
		int sumRow = sheet.getLastRowNum()-sheet.getFirstRowNum();
		
		//第一行
		XSSFRow firstRow = sheet.getRow(0);
		getCellIndexs(firstRow);
		
		for (int i = 1; i <= sumRow; i++) {
			XSSFRow row = (XSSFRow) sheet.getRow(i);
			XSSFCell subjectName = row.getCell(subjectNameIndex);
			XSSFCell optionA = row.getCell(optionAIndex);
			XSSFCell optionB = row.getCell(optionBIndex);
			XSSFCell optionC = row.getCell(optionCIndex);
			XSSFCell optionD = row.getCell(optionDIndex);
			XSSFCell rightResult = row.getCell(rightResultIndex);
			XSSFCell subjectScore = row.getCell(subjectScoreIndex);
			if(subjectScore.getCellType()==0) { subjectScore.setCellType(1); }
			XSSFCell subjectType = row.getCell(subjectTypeIndex);
			XSSFCell subjectEasy = row.getCell(subjectEasyIndex);
			
			SubjectInfo subject = new SubjectInfo();
			subject.setSubjectName(subjectName.toString());
			
			subject.setOptionA(optionA == null ? "" : optionA.toString());
			subject.setOptionB(optionB == null ? "" : optionB.toString());
			subject.setOptionC(optionC == null ? "" : optionC.toString());
			subject.setOptionD(optionD == null ? "" : optionD.toString());
			
			subject.setRightResult(rightResult.toString());
			subject.setSubjectScore(Integer.parseInt(subjectScore.toString()));
			//试题类型
			if("单选".equals(row.getCell(subjectTypeIndex).toString())){
				subject.setSubjectType(0);
			}else if("多选".equals(row.getCell(subjectTypeIndex).toString())){
				subject.setSubjectType(1);
			}else{
				subject.setSubjectType(2);
			}
			
			if ("简单".equals(subjectEasy.toString())) {
				subject.setSubjectEasy(0);					
			} else if ("普通".equals(subjectEasy.toString())) {
				subject.setSubjectEasy(1);					
			} else {
				subject.setSubjectEasy(2);						
			}
			subject.setCourse(new CourseInfo(courseId));
			subject.setGrade(new GradeInfo(gradeId));
			subject.setDivision(division);
			
			subjects.add(subject);
		}
		
		workBook.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return subjects;
}


/**
 * 解析第一行标题名得到列索引
 * @param firstRow
 */
private static void getCellIndexs(XSSFRow firstRow) {
	int cellNum = firstRow.getLastCellNum()-firstRow.getFirstCellNum();
	for (int i=0; i<cellNum; i++) {
		String cell = firstRow.getCell(i).toString();
		if ("题目".equals(cell)) {
			subjectNameIndex = i;
			continue;
		}
		if ("答案A".equals(cell)) {
			optionAIndex = i;
			continue;
		}
		if ("答案B".equals(cell)) {
			optionBIndex = i;
			continue;
		}
		if ("答案C".equals(cell)) {
			optionCIndex = i;
			continue;
		}
		if ("答案D".equals(cell)) {
			optionDIndex = i;
			continue;
		}
		if ("正确答案".equals(cell)) {
			rightResultIndex = i;
			continue;
		}
		if ("分值".equals(cell)) {
			subjectScoreIndex = i;
			continue;
		}
		if ("试题类型".equals(cell)) {
			subjectTypeIndex = i;
			continue;
		}
		if ("难易程度".equals(cell)) {
			subjectEasyIndex = i;
			continue;
		}
	}
}

}