package cn.hmsoft.ltc.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import cn.hmsoft.ltc.common.constants.LtContext;
import cn.hmsoft.ltc.common.util.DialogUtil;
import cn.hmsoft.ltc.common.util.DocUtil;
import cn.hmsoft.ltc.common.util.POIUtil;
import cn.hmsoft.ltc.common.util.StageManager;
import cn.hmsoft.ltc.model.CourseQuestion;
import cn.hmsoft.ltc.model.DetailTable;
import cn.hmsoft.ltc.model.QuestionType;
import cn.hmsoft.ltc.model.Subject;
import cn.hmsoft.ltc.model.TestPaper;
import cn.hmsoft.ltc.model.Users;
import cn.hmsoft.ltc.service.iface.CourseQuestionService;
import cn.hmsoft.ltc.service.iface.DetailTableService;
import cn.hmsoft.ltc.service.iface.QuestionTypeService;
import cn.hmsoft.ltc.service.iface.SubjectOptionServie;
import cn.hmsoft.ltc.service.iface.SubjectService;
import cn.hmsoft.ltc.service.iface.UserService;
import cn.hmsoft.ltc.service.impl.CourseQuestionServiceImpl;
import cn.hmsoft.ltc.service.impl.DetailTableServiceImpl;
import cn.hmsoft.ltc.service.impl.QuestionTypeServiceImpl;
import cn.hmsoft.ltc.service.impl.SubjectOptionServieImpl;
import cn.hmsoft.ltc.service.impl.SubjectServiceImpl;
import cn.hmsoft.ltc.service.impl.UserServiceImpl;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.GUIState;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * 题目编辑控制器
 * @author zq
 *
 */
@FXMLController
public class SubjectMainController implements Initializable {
	@FXML
	public Button wordBtn;
  	//关键字
  	@FXML
  	public TextField subjectKeywordTextField;
  	//预计难度
  	@FXML
  	public ComboBox<String> subjectDifficultSelectBox;
  	//考核要求
  	@FXML
  	public ComboBox<String> subjectAssessmentSelectBox;
  	@FXML
  	public Button subjectQueryBtn;
	@FXML 
	public TableView<Subject> subjectTableView;//题目列表对象
	@FXML 
	public TableColumn<Subject, Integer> index;
	@FXML 
	public TableColumn<Subject, Integer> subjectColId;
	@FXML 
	public TableColumn<Subject, Integer> subjectColCourse;
	@FXML 
	public TableColumn<Subject, String> subjectColQuestionTypeName;
	@FXML 
	public TableColumn<Subject, String> subDifficultCol;//预计难度
	@FXML 
	public TableColumn<Subject, String> subAssessmentCol;//考核要求
	@FXML 
	public TableColumn<Subject, String> subjectColAnswer;
	@FXML 
	public TableColumn<Subject, String> subjectColScore;
	@FXML 
	public TableColumn<Subject, String> subChapterCol;//章节
	@FXML 
	public TableColumn<Subject, String> subJointCol;//节
	@FXML 
	public TableColumn<Subject, String> subDirectoryCol;//目
	@FXML 
	public TableColumn<Subject, String> subPagesCol;//页
	@FXML 
	public TableColumn<Subject, String> quesRemarkCol;//备注
	@FXML 
	public TableColumn<Subject, Button> subEditBtnCol;//编辑
	
	public final ObservableList<Subject> SUBJECT_DATALIST = FXCollections.observableArrayList(); //题目列表--数据源对象
	@FXML
	public ScrollPane subjectScorllPane;
  	//题型
  	@FXML
  	public ComboBox<QuestionType> subjectQuestionTypeSelectBox;
  	public final ObservableList<QuestionType> SUBJECT_DATALIST_QUESTION_TYPE = FXCollections.observableArrayList();
  	
	public SubjectService subjectService = new SubjectServiceImpl();
	public DetailTableService detailTableService = new DetailTableServiceImpl(); //细目表
	public SubjectOptionServie subjectOptionServie = new SubjectOptionServieImpl();
	public QuestionTypeService questionTypeService = new QuestionTypeServiceImpl();  //题型
	public CourseQuestionService cqService = new CourseQuestionServiceImpl();//课程题型关联表
	private UserService userService = new UserServiceImpl();
	
	private static final Logger LOGGER = Logger.getLogger(SubjectMainController.class);
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		try {
			initSubjectData();
			ActionEvent event = new ActionEvent();
			doQuerySubjectFun(event);
			//双击题目 修改!
			subjectTableView.setRowFactory(new Callback<TableView<Subject>, TableRow<Subject>>() {
				
				@Override
				public TableRow<Subject> call(TableView<Subject> param) {
					TableRow<Subject> row = new TableRow<Subject>();
					row.setOnMouseClicked(new EventHandler<MouseEvent>() {

						@Override
						public void handle(MouseEvent event) {
							if (event.getClickCount() == 2 && !row.isEmpty()) {
								doEditSubjectFun(null);
							}
						}
						
					});
					return row;
				}
			});
		} catch (SQLException e) {
			LOGGER.error(e);
		}
		StageManager.CONTROLLER.put("subjectMainController", this);
	}

	/**
	 * 初始化 试题编辑数据
	 */
	private void initSubjectData() throws SQLException {
		//初始化 题型下拉数据
		subjectQuestionTypeSelectBox.getItems().clear();
		SUBJECT_DATALIST_QUESTION_TYPE.addAll(this.questionTypeService.selectQuestionTypeObs());
		subjectQuestionTypeSelectBox.setItems(SUBJECT_DATALIST_QUESTION_TYPE);
		subjectQuestionTypeSelectBox.setPromptText("请选择");
		
		subjectDifficultSelectBox.setItems(FXCollections.observableArrayList("易", "中等偏易", "中等偏难", "难"));
		subjectDifficultSelectBox.setPromptText("请选择");

		subjectAssessmentSelectBox.setItems(FXCollections.observableArrayList("重点", "次重要", "一般"));
		subjectAssessmentSelectBox.setPromptText("请选择");
		
	}
	
	/**
	 * 题目查询
	 */
	@FXML
	public void doQuerySubjectFun(ActionEvent event){
		TestPaper paper = LtContext.CURR_PAPER;
		QuestionType questionType = subjectQuestionTypeSelectBox.getValue();
		String difficult = subjectDifficultSelectBox.getValue();
		String assessment = subjectAssessmentSelectBox.getValue();
		Subject subject = new Subject();
		if (paper != null && paper.getId() != -1) {
			subject.setTestPaperId(paper.getPaperNo());
		} 
		if (questionType != null && questionType.getId() != -1) {
			subject.setQuestionTypeId(questionType.getId());
		}
		if(StringUtils.isNotBlank(difficult) && !difficult.equals("请选择")) {
			subject.setDifficult(difficult);
		}
		if(StringUtils.isNotBlank(assessment)  && !assessment.equals("请选择")) {
			subject.setAssessment(assessment);
		}
		subjectKeywordTextField.setText(subjectKeywordTextField.getText().trim());
		subject.setRemark(subjectKeywordTextField.getText());
		try {
			subjectTableView.getItems().clear();
			subjectColId.setCellValueFactory(new PropertyValueFactory<Subject, Integer>("id"));
			subjectColCourse.setCellValueFactory(new PropertyValueFactory<Subject, Integer>("courseId"));
			index.setCellValueFactory(new PropertyValueFactory<Subject, Integer>("index"));
			subjectColQuestionTypeName.setCellValueFactory(new PropertyValueFactory<Subject, String>("questionTypeName"));
			subAssessmentCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("assessment"));
			subDifficultCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("difficult"));
			subjectColScore.setCellValueFactory(new PropertyValueFactory<Subject, String>("scoreStr"));
			subChapterCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("chapter"));
			subJointCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("joint"));
			subDirectoryCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("directory"));
			subPagesCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("pages"));
			quesRemarkCol.setCellValueFactory(new PropertyValueFactory<Subject, String>("remark"));
			subEditBtnCol.setCellValueFactory(new PropertyValueFactory<Subject, Button>("subjectEditBtn"));
			SUBJECT_DATALIST.addAll(this.subjectService.selectSubject(subject));
			subjectTableView.setItems(SUBJECT_DATALIST);
			//循环设置按钮
			for (Subject sub : SUBJECT_DATALIST) {
				sub.getSubjectEditBtn().setText("编辑");
				sub.getSubjectEditBtn().setOnAction(new EventHandler<ActionEvent>() {

					@Override
					public void handle(ActionEvent event) {
						editeSubjectLogic(sub);
					}
					
				});
			}
		} catch (SQLException e) {
			LOGGER.error(e);
		}
	}
	
	/**
	 * 编辑题目窗口
	 * @param event
	 */
	public void doEditSubjectFun(ActionEvent event) {
		Subject selectSubject = subjectTableView.getSelectionModel().getSelectedItem();
		if(selectSubject == null) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "提示", "请选择一个题目!");
			return;
		}
		editeSubjectLogic(selectSubject);
	}

	private void editeSubjectLogic(Subject selectSubject) {
		this.subjectTableView.getSelectionModel().select(selectSubject.getIndex() - 1);
		if((selectSubject.getQuestionTypeId() == LtContext.TYPE_SINGLE_SELECT_ID 
				|| selectSubject.getQuestionTypeName().contains("单项选择题")) || 
				(selectSubject.getQuestionTypeId() == LtContext.TYPE_MULTI_SELECT_ID 
						|| selectSubject.getQuestionTypeName().contains("多项选择题"))) {
			try {
				StageManager.VARIABLE.put("edit_subject", selectSubject);
				FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/ChoiceSubjectView.fxml"));
				Parent root = fxmlLoader.load();
				Stage stage = new Stage();
				stage.setTitle("题目编辑");
				stage.setResizable(false);
				stage.setScene(new Scene(root,900, 300));
				stage.show();
			} catch (Exception e) {
				LOGGER.error(e);
			}
		} else {
			try {
				StageManager.VARIABLE.put("edit_subject", selectSubject);
				FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/OtherSubjectView.fxml"));
				Parent root = fxmlLoader.load();
				Stage stage = new Stage();
				stage.setTitle("题目编辑");
				stage.setResizable(false);
				stage.setScene(new Scene(root,900, 300));
				stage.show();
			} catch (Exception e) {
				LOGGER.error(e);
			}
		}
	}
	
	/**
	 * word合并.（试卷阅览导出）
	 * @param event
	 */
	@FXML
	public void wordMergeFun(ActionEvent event) {
		this.wordBtn.setDisable(true);
		List<CourseQuestion> cqList = null;
		String paprePrifix = LtContext.CURR_PAPER.getPaperNo().substring(0, LtContext.CURR_PAPER.getPaperNo().length() - 1);
		String basePath = System.getProperty("user.dir") + File.separator + "papers" + File.separator + paprePrifix + File.separator + LtContext.CURR_PAPER.getPaperNo() + File.separator;
//		List<String> errList = new ArrayList<String>();
		try {
			cqList = cqService.findCourseQuestion(LtContext.CURR_PAPER.getCourseId());
//			//验证
//			int qsNo = 1;
//			for (CourseQuestion cq : cqList) {
//				for (int m=0; m<cq.getQuesNums(); m++) {
//					if (cq.getQuesTypeId() == LtContext.TYPE_SINGLE_SELECT_ID || "单项选择题".equals(cq.getQuesTypeName())) {
//						errList.addAll(this.validateSingleSelectQs(basePath + "ques" + File.separator + qsNo + ".docx", qsNo));
//					} else if (cq.getQuesTypeId() == LtContext.TYPE_MULTI_SELECT_ID || "多项选择题".equals(cq.getQuesTypeName())) {
//						errList.addAll(this.validateMultySelectQs(basePath + "ques" + File.separator + qsNo + ".docx", qsNo));
//					}
//					qsNo++;
//				}
//			}
		} catch(Exception e) {
			LOGGER.error(e);
		}
//		if (errList.size() > 0) {
//			StringBuilder errSb = new StringBuilder();
//			for (String errMsg : errList) {
//				errSb.append(errMsg).append("\n");
//			}
//			//DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", errSb.toString());
//			if (DialogUtil.confirm(errSb.toString(), "验证不通过，是否强制导出?", GUIState.getStage())) {
//				this.exportPaperLogic(cqList, basePath);
//			}
//		} else {
			this.exportReadPaperLogic(cqList, basePath);
//		}
		this.wordBtn.setDisable(false);
	}
	
	private void exportReadPaperLogic(List<CourseQuestion> cqList, String basePath) {
//		if (DialogUtil.confirm("导出试卷和答案时，请仔细在系统中核对试卷和答案，确保导出试卷和答案一致！", GUIState.getStage())) {
//			Alert confirm = new Alert(Alert.AlertType.CONFIRMATION,
//					"", 
//					new ButtonType("通用卡", ButtonData.YES),
//	                new ButtonType("专用卡", ButtonData.NO),
//	                new ButtonType("取消", ButtonData.CANCEL_CLOSE));
//			confirm.setTitle("请选择");
//			confirm.setHeaderText("答题卡制作说明");
//			confirm.initOwner(GUIState.getStage());
//			Optional<ButtonType> btnType = confirm.showAndWait();
//			try {
//				Users user = userService.selectUserByCourseCode(LtContext.CURR_PAPER.getCourseCode());
//				List<DetailTable> tableList = detailTableService.selectDetailTable(LtContext.CURR_PAPER.getPaperNo());//细目表信息
//				if (btnType.get().getButtonData().equals(ButtonData.YES)) {//通用卡
//					DocUtil.expPrintCard(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), "通用答题卡");
//				} else if (btnType.get().getButtonData().equals(ButtonData.NO)) {//专用卡
//					DocUtil.expPrintCard(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), "专用答题卡");
//				}
//				DocUtil.expQuestionGenWordCover(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(),user); //命题纸封面
//				DocUtil.expAnswerGenCover(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), user); //答题纸封面
//				DocUtil.expSelfAuditItemList(basePath,LtContext.CURR_PAPER.getPaperNo(), user); //自考省级命题自审项目表 导出
//				DocUtil.expPaperDetailTable(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), user, tableList); //导出细目表
//			} catch(Exception e) {
//				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", e.getMessage());
//				LOGGER.error(e);
//			}
	
			try {
				//分离 试题和 答案到 qs,as目录
				this.splitAndMoveDocs(cqList, basePath);
				//最终合并
				this.finalMergeDoc(cqList, basePath);
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "提示", "成功合成试卷,试卷阅览导出成功!");
			} catch (Exception e) {
				e.printStackTrace();
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", e.getMessage());
				LOGGER.error(e);
			} finally {
				this.wordBtn.setDisable(false);
			}
//		}
	}
	
	/**
	 * word合并.
	 * @param event
	 */
	@FXML
	public void wordMergeFun1(ActionEvent event) {
		this.wordBtn.setDisable(true);
		List<CourseQuestion> cqList = null;
		String paprePrifix = LtContext.CURR_PAPER.getPaperNo().substring(0, LtContext.CURR_PAPER.getPaperNo().length() - 1);
		String basePath = System.getProperty("user.dir") + File.separator + "papers" + File.separator + paprePrifix + File.separator + LtContext.CURR_PAPER.getPaperNo() + File.separator;
		List<String> errList = new ArrayList<String>();
		try {
			cqList = cqService.findCourseQuestion(LtContext.CURR_PAPER.getCourseId());
			//验证
			int qsNo = 1;
			for (CourseQuestion cq : cqList) {
				for (int m=0; m<cq.getQuesNums(); m++) {
					if (cq.getQuesTypeId() == LtContext.TYPE_SINGLE_SELECT_ID || "单项选择题".equals(cq.getQuesTypeName())) {
						errList.addAll(this.validateSingleSelectQs(basePath + "ques" + File.separator + qsNo + ".docx", qsNo));
					} else if (cq.getQuesTypeId() == LtContext.TYPE_MULTI_SELECT_ID || "多项选择题".equals(cq.getQuesTypeName())) {
						errList.addAll(this.validateMultySelectQs(basePath + "ques" + File.separator + qsNo + ".docx", qsNo));
					}
					qsNo++;
				}
			}
		} catch(Exception e) {
			LOGGER.error(e);
		}
		if (errList.size() > 0) {
			StringBuilder errSb = new StringBuilder();
			for (String errMsg : errList) {
				errSb.append(errMsg).append("\n");
			}
			//DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", errSb.toString());
			if (DialogUtil.confirm(errSb.toString(), "验证不通过，是否强制导出?", GUIState.getStage())) {
				this.exportPaperLogic(cqList, basePath);
			}
		} else {
			this.exportPaperLogic(cqList, basePath);
		}
		this.wordBtn.setDisable(false);
	}

	private void exportPaperLogic(List<CourseQuestion> cqList, String basePath) {
		List<Subject> allSubList = null;
		
//		if (DialogUtil.confirm("导出试卷和答案时，请仔细在系统中核对试卷和答案，确保导出试卷和答案一致！", GUIState.getStage())) {
			Alert confirm = new Alert(Alert.AlertType.CONFIRMATION,
					"", 
					new ButtonType("通用卡", ButtonData.YES),
	                new ButtonType("专用卡", ButtonData.NO),
	                new ButtonType("取消", ButtonData.CANCEL_CLOSE));
			confirm.setTitle("请选择");
			confirm.setHeaderText("答题卡制作说明");
			confirm.initOwner(GUIState.getStage());
			Optional<ButtonType> btnType = confirm.showAndWait();
			try {
				Users user = userService.selectUserByCourseCode(LtContext.CURR_PAPER.getCourseCode());
				List<DetailTable> tableList = detailTableService.selectDetailTable(LtContext.CURR_PAPER.getPaperNo());//细目表信息
				
				allSubList =this.subjectService.findSubjectList(LtContext.CURR_PAPER.getPaperNo(),null);
				
				if (btnType.get().getButtonData().equals(ButtonData.YES)) {//通用卡
					DocUtil.expPrintCard(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), "通用答题卡");
				} else if (btnType.get().getButtonData().equals(ButtonData.NO)) {//专用卡
					DocUtil.expPrintCard(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), "专用答题卡");
				}
				DocUtil.expQuestionGenWordCover(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(),user); //命题纸封面
				DocUtil.expAnswerGenCover(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), user); //答题纸封面
				DocUtil.expSelfAuditItemList(basePath,LtContext.CURR_PAPER.getPaperNo(), user); //自考省级命题自审项目表 导出
				DocUtil.expPaperDetailTable(basePath, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo(), user, tableList); //导出细目表
				DocUtil.expPaperPage(basePath, allSubList, LtContext.CURR_PAPER.getCourseCode(), LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo());//答案
			} catch(Exception e) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", e.getMessage());
				LOGGER.error(e);
			}
	
			try {
				//分离 试题和 答案到 qs,as目录
				this.splitAndMoveDocs(cqList, basePath);
				//最终合并
				this.finalMergeDoc(cqList, basePath);
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "提示", "成功合成试卷!");
			} catch (Exception e) {
				e.printStackTrace();
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", e.getMessage());
				LOGGER.error(e);
			} finally {
				this.wordBtn.setDisable(false);
			}
//		}
	}

	public void splitAndMoveDocs(List<CourseQuestion> cqList, String basePath) throws Exception {
		String fromQuesPath = basePath + "ques" + File.separator;
		String qsPath = basePath + "qs" + File.separator;
		String asPath = basePath + "as" + File.separator;
		Integer qsNo = 1;//小题序号 连续 1-N
		for (CourseQuestion cq : cqList) {
			//复制 大题
			String fromBig = fromQuesPath + (cq.getOrd() * 100) + ".docx";//ques原始的大题
			String toQsBig = qsPath + (cq.getOrd() * 100) + ".docx";//拷贝到qs  正式 题目目录
			String toAsBig = asPath + (cq.getOrd() * 100) + ".docx";//拷贝到as 正式答案目录
			FileUtils.copyFile(new File(fromBig), new File(toQsBig));
			FileUtils.copyFile(new File(fromBig), new File(toAsBig));
			
			for (int i=0; i< cq.getQuesNums(); i++) {
				String fromQuesSm = fromQuesPath + qsNo + ".docx";
				String toNewQs = qsPath + qsNo + ".docx";
				String toNewAs = asPath + qsNo + ".docx";
				
				//分拆生成新的试题word到qs/
				POIUtil.createAndWriteQsWord(fromQuesSm, toNewQs);
				//分拆生成新的答案word到as/
				POIUtil.splitAndWriteAsWord(fromQuesSm, toNewAs, qsNo);//分拆迁移答案到新word
				
	
				qsNo++;
			}
		}
	}
	
	private List<String> validateSingleSelectQs(String docPath, int qsNo) {
		List<String> errList = new ArrayList<String>();
		try {
			String[] caps = POIUtil.readWordParaCaption(docPath);
			if (caps == null || caps.length != 6) {
				errList.add("第" + qsNo + "题结构错误，请修改!");
				return errList;
			}
			if (!caps[1].startsWith("A") || !caps[2].startsWith("B") || !caps[3].startsWith("C") || !caps[4].startsWith("D")) {
				errList.add("第" + qsNo + "题，单选题题必须存在 A、B、C、D四个选项!");
			}
			if (caps[1].equals("A.") || caps[2].equals("B.") || caps[3].equals("C.") || caps[4].equals("D.")) {
				errList.add("第" + qsNo + "题，选项不能为空，请修改!");
			}
			String choise1Str = caps[1].substring(2);
			String choise2Str = caps[2].substring(2);
			String choise3Str = caps[3].substring(2);
			String choise4Str = caps[4].substring(2);
			if (choise1Str.equals(choise2Str) || choise1Str.equals(choise3Str) || choise1Str.equals(choise4Str)) {
				errList.add("第" + qsNo + "题，选项1题干重复!");
			}
			if (choise2Str.equals(choise3Str) || choise2Str.equals(choise4Str)) {
				errList.add("第" + qsNo + "题，选项2题干重复!");
			}
			if (choise3Str.equals(choise4Str)) {
				errList.add("第" + qsNo + "题，选项3题干重复!");
			}
			if (caps[5].equals("答案及评分参考：")) {
				errList.add("第" + qsNo + "题，选项4题干重复!");
			} else {
				int pos = caps[5].indexOf("：");
				String key = caps[5].substring(pos + 1);
				if (key.equals("") || !"ABCD".contains(key)) {
					errList.add("第" + qsNo + "题，答案不能为空，且必须是[ABCD]其中一个!");
				}
			}
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return errList;
	}
	
	private List<String> validateMultySelectQs(String docPath, int qsNo) {
		List<String> errList = new ArrayList<String>();
		try {
			String[] caps = POIUtil.readWordParaCaption(docPath);
			if (caps == null || caps.length != 7) {
				errList.add("第" + qsNo + "题结构错误，请修改!");
				return errList;
			}
			if (!caps[1].startsWith("A") || !caps[2].startsWith("B") || !caps[3].startsWith("C") || !caps[4].startsWith("D") || !caps[5].startsWith("E")) {
				errList.add("第" + qsNo + "题，多选题必须存在 A、B、C、D、E五个选项!");
			}
			if (caps[1].equals("A.") || caps[2].equals("B.") || caps[3].equals("C.") || caps[4].equals("D.") || caps[5].equals("E.")) {
				errList.add("第" + qsNo + "题，选项不能为空，请修改!");
			}
			String choise1Str = caps[1].substring(2);
			String choise2Str = caps[2].substring(2);
			String choise3Str = caps[3].substring(2);
			String choise4Str = caps[4].substring(2);
			String choise5Str = caps[5].substring(2);
			if (choise1Str.equals(choise2Str) || choise1Str.equals(choise3Str) || choise1Str.equals(choise4Str) || choise1Str.equals(choise5Str)) {
				errList.add("第" + qsNo + "题，选项1题干重复!");
			}
			if (choise2Str.equals(choise3Str) || choise2Str.equals(choise4Str) || choise2Str.equals(choise5Str)) {
				errList.add("第" + qsNo + "题，选项2题干重复!");
			}
			if (choise3Str.equals(choise4Str) || choise3Str.equals(choise5Str)) {
				errList.add("第" + qsNo + "题，选项3题干重复!");
			}
			if (choise4Str.equals(choise5Str)) {
				errList.add("第" + qsNo + "题，选项4题干重复!");
			}
			if (caps[6].equals("答案及评分参考：")) {
				errList.add("第" + qsNo + "题，选择题参考答案不能为空!");
			} else {
				int pos = caps[6].indexOf("：");
				String key = caps[6].substring(pos + 1);
				if(key.equals("")) {
					errList.add("第" + qsNo + "题，答案不能为空，且必须是[ABCDE]其中任意多个!");
				}else {
					int count = key.length();
					if(count<2 || count>4) {
						errList.add("第" + qsNo + "题，答案不能为空，且必须是[ABCDE]中大于等于2个，小于等于4个，请重新审核题目!");
					}else {
						char[] strArr1 = key.toCharArray();
						 for (int i = 0; i < strArr1.length; i++) {
						        if(!"ABCDE".contains(String.valueOf(strArr1[i]))) {
						        	errList.add("第" + qsNo + "题，答案不能答案不能为空，且必须是[ABCDE]中大于等于2个，小于等于4个，请重新审核题目!");
						        }
						    }
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return errList;
	}
	
	public void finalMergeDoc(List<CourseQuestion> cqList, String basePath) throws IOException {
		int bigQs = 0;
		int smQs = 0;
		bigQs = cqList.size();
		for (CourseQuestion cq : cqList) {
			smQs += cq.getQuesNums();
		}
		//生成试卷头docx
		String headDocx = basePath + "qs" + File.separator + "0.docx";
		DocUtil.genPaperHeaderWord("header.ftl", headDocx, bigQs, smQs, LtContext.CURR_PAPER.getCourseCode(), 
				LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo());
		//生成答案头docx
		String asHeaderDocx = basePath + "as" + File.separator + "0.docx";
		DocUtil.genAsHeaderWord("asHeader.ftl", asHeaderDocx, bigQs, smQs, LtContext.CURR_PAPER.getCourseCode(), 
				LtContext.CURR_PAPER.getCourseName(), LtContext.CURR_PAPER.getPaperNo());
		//合并生成试卷文档
		Map<Integer, QuestionType> quesMap = this.subjectService.getQuestionTypeMap();
		
		String paperAB = LtContext.CURR_PAPER.getPaperNo().substring(LtContext.CURR_PAPER.getPaperNo().length()-1, LtContext.CURR_PAPER.getPaperNo().length());
		
		String strCopyFolderArg = basePath + "qs";//试题目录
		String outDocArg = basePath + LtContext.CURR_PAPER.getPaperNo() + ".docx";
		
		try {
			POIUtil.mergeDoc(POIUtil.getSrcDocxArr(quesMap, strCopyFolderArg, cqList), outDocArg, LtContext.CURR_PAPER.getCourseCode(), 
					LtContext.CURR_PAPER.getCourseName(), paperAB);
		} catch (Exception e) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", e.getMessage());
		}
		//合并生成答案文档
		String asCopyFolderArg = basePath + "as";//答案目录
		String asOutDocArg = basePath + LtContext.CURR_PAPER.getPaperNo() + "N.docx";
		try {
			POIUtil.mergeAnswerDoc(POIUtil.getSrcDocxArr(quesMap, asCopyFolderArg, cqList), asOutDocArg, LtContext.CURR_PAPER.getCourseCode(), 
					LtContext.CURR_PAPER.getCourseName(), paperAB);
		} catch (Exception e) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "错误", e.getMessage());
		}
	}
	
	public static void main(String[] args) {
		String strCopyFolderArg = "G:\\javaFx\\LT-client\\papers\\02363190601\\02363190601A\\ques";//试题目录
		String outDocArg = "G:\\javaFx\\LT-client\\papers\\02363190601\\02363190601A\\02363190601A.docx";
		
		//POIUtil.insertMerge(strCopyFolderArg, outDocArg);
	}
	
	public static void main3(String[] args) {
		/*String strCopyFolderArg = "D:\\word\\2001011207\\ques";//试题目录
		String outDocArg = "D:\\word\\2001011207\\2001011207.docx";
		POIUtil.insertMerge(strCopyFolderArg, outDocArg);*/
		Set<String> treeSet = new TreeSet<String>(new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
			}
			
		});
		treeSet.add("0");
		treeSet.add("100");
		treeSet.add("99");
		
		System.err.println(treeSet);
	}
	
}
