package cn.hmsoft.ltc.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.hmsoft.ltc.common.constants.LtContext;
import cn.hmsoft.ltc.common.constants.SysConst.PaperStageEnum;
import cn.hmsoft.ltc.common.util.DialogUtil;
import cn.hmsoft.ltc.common.util.POIUtil;
import cn.hmsoft.ltc.common.util.StageManager;
import cn.hmsoft.ltc.model.Course;
import cn.hmsoft.ltc.model.QuestionType;
import cn.hmsoft.ltc.model.Subject;
import cn.hmsoft.ltc.model.SubjectOption;
import cn.hmsoft.ltc.service.iface.CourseQuestionService;
import cn.hmsoft.ltc.service.iface.CourseService;
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.TestPaperService;
import cn.hmsoft.ltc.service.impl.CourseQuestionServiceImpl;
import cn.hmsoft.ltc.service.impl.CourseServiceImpl;
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.TestPaperServiceImpl;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.GUIState;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * 题目管理-选择题类
 * 
 * @author zq
 */
@FXMLController
public class ChoiceSubjectController implements Initializable {

	private static final Logger LOG = Logger.getLogger(SubjectMainController.class);
	
	@FXML 
	AnchorPane multiAnchorPane;
	@FXML
	public TextArea quesRemarkTextArea;
	@FXML 
	Button wordEditBtn;//题目编辑(打开word)
	@FXML
	public TextField subjectIdTextField;
	@FXML
	public ComboBox<String> singleAnswerCombo;//选择题答案下拉框
	@FXML
	public ComboBox<Course> courseCombo;
	public final ObservableList<Course> COURSE_COMBO_DATA_LIST = FXCollections.observableArrayList();
	@FXML
	public ComboBox<QuestionType> questionTypeCombo;
	public final ObservableList<QuestionType> QUESTION_TYPE_COMBO_DATA_LIST = FXCollections.observableArrayList();
	@FXML
	public ComboBox<String> difficultCombo;
	@FXML
	public ComboBox<String> assessmentCombo;
	@FXML
	public TextField chapterTextField;
	@FXML
	public TextField jointTextField;
	@FXML
	public TextField directoryTextField;
	@FXML
	public TextField pagesTextField;
	@FXML
	public TextArea dryTextArea;
	@FXML
	public TextArea guideTextArea;
	@FXML
	public Button saveBtn;//保存 按钮
	@FXML
	public Button cancelBtn;
	@FXML
	public Text subjectOptionTextLabel;
	@FXML
	public SplitPane subjectOptionSplitPane;
	public SubjectService subjectService = new SubjectServiceImpl();
	public QuestionTypeService questionTypeService = new QuestionTypeServiceImpl();
	public SubjectOptionServie subjectOptionService = new SubjectOptionServieImpl();
	public CourseService courseService = new CourseServiceImpl();
	public TestPaperService testPaperService = new TestPaperServiceImpl();  //试卷管理
	public CourseQuestionService cqService = new CourseQuestionServiceImpl();//课程题型关联表
	private static final Logger LOGGER = Logger.getLogger(SubjectMainController.class);
	public static Subject SUBJECT = new Subject();

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		try {
			initEditData();
		} catch (Exception e) {
			e.printStackTrace();
		}
		StageManager.CONTROLLER.put("choiceSubjectController", this);
	}

	/**
	 * 初始化编辑数据
	 * 
	 * @throws SQLException
	 */
	private void initEditData() throws SQLException {
		Subject editSubject = (Subject) StageManager.VARIABLE.get("edit_subject");
		// 是否为编辑
		if (editSubject != null) {
			Subject sub = new Subject();
			sub.setSubjectId(editSubject.getSubjectId());
			ObservableList<Subject> subjects = this.subjectService.selectSubject(sub);
			sub = subjects.get(0);
			//难度选择
			difficultCombo.setPromptText("选择难度");
			difficultCombo.setEditable(false);
			difficultCombo.setItems(FXCollections.observableArrayList("易", "中等偏易", "中等偏难", "难"));
			//考核要求选择
			assessmentCombo.setPromptText("选择考核要求");
			assessmentCombo.setEditable(false);
			assessmentCombo.setItems(FXCollections.observableArrayList("重点", "次重要", "一般"));
			//考核要求
			assessmentCombo.setValue(sub.getAssessment());
			if (LtContext.CURR_PAPER.getKeyChapters().indexOf(sub.getChapter()) != -1) {
				assessmentCombo.setValue("重点");
			} 
			//难度
			difficultCombo.setValue(sub.getDifficult());
			//章
			chapterTextField.setText(sub.getChapter());
			//节
			jointTextField.setText(sub.getJoint() + "");
			//目
			directoryTextField.setText(sub.getDirectory() + "");
			//页
			pagesTextField.setText(sub.getPages() + "");
			
			subjectIdTextField.setText(sub.getSubjectId() + "");
			//备注
			quesRemarkTextArea.setText(sub.getRemark());
			
		}
	}

	/**
	 * 保存题目
	 */
	public void doSaveSubjectFunc(ActionEvent event) {
		// 验证表单
		if (!checkSubject()) {
			return;
		}
		if (!validateSubject(SUBJECT)) {
			return;
		}
		//校验下拉选项不能相同
		try {
			Subject editSubject = (Subject) StageManager.VARIABLE.get("edit_subject");
			if (editSubject != null) {
				// 修改
				SUBJECT.setIndex(editSubject.getIndex());
				SUBJECT.setTestPaperId(editSubject.getTestPaperId());
				SUBJECT.setScore(editSubject.getScore());
				subjectService.updateSubject(SUBJECT);
				SubjectOption subjectOption = new SubjectOption();
				subjectOption.setSubjectId(SUBJECT.getSubjectId());
				subjectOptionService.deleteSubjectOption(subjectOption);
				//更新题目列表显示
				((SubjectMainController)StageManager.CONTROLLER.get("subjectMainController")).doQuerySubjectFun(event);
			}
		} catch (Exception e) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "系统错误，请联系管理员!");
			LOGGER.error(e);
			return;
		}
		//查询窗口 是否所有的题目的题干都保存了--更改试卷状态为 完成
		boolean isAllEdite = true;
		List<Subject> subjectList = ((SubjectMainController)StageManager.CONTROLLER.get("subjectMainController")).SUBJECT_DATALIST;
		for (Subject sub : subjectList) {
			if (StringUtils.isEmpty(sub.getDry())) {
				isAllEdite = false;
				break;
			}
		}
		if (isAllEdite) {
			try {
				this.testPaperService.updateTestPaper(LtContext.CURR_PAPER.getPaperNo(), PaperStageEnum.QUES_DONE.ordinal());
				MainPaneController mainController = (MainPaneController)StageManager.CONTROLLER.get("mainPaneController");
				mainController.selectPaperTable();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		//调用到这个方法---可以是 保存按钮、题目编辑 按钮
		if ("saveBtn".equals(((Button)event.getSource()).getId())) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "提示", "保存成功！");
		}
		closeCurrentWindow(event);
	}

	/**
	 * 题干不能相同.
	 * @param sub
	 * @return
	 */
	private boolean validateSubject(Subject sub) {
		//AB卷中题干都不能相同
		String currPaperNo = LtContext.CURR_PAPER.getPaperNo();
		String otherPaperNo = currPaperNo.substring(0, currPaperNo.length() - 1) + (currPaperNo.endsWith("A") ? "B" : "A");
		/*try {
			List<Subject> subjectList = this.subjectService.findSubjectList(otherPaperNo, null);
			for (Subject subX : subjectList) {
				if (subX.getDry() != null && !subX.getDry().equals("") && subX.getDry().equals(sub.getDry())) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "与试卷" + otherPaperNo + "中题干重复：" + sub.getDry());
					return false;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}*/
		return true;
	}
	
	/**
	 * 取消
	 */
	public void doCancelSubjectFunc(ActionEvent event) {
		closeCurrentWindow(event);
		resetForm();
		StageManager.VARIABLE.remove("edit_subject");
	}

	public static void main(String[] args) {
		Pattern pattern = Pattern.compile("^[1-9]\\d*\\.{0,1}\\d*|0\\.{0,1}\\d*[1-9]\\d*$");//^[1-9]\\d*$
		Boolean result = pattern.matcher("5..63").matches();
		System.err.println(result);
	}
	
	/**
	 * 校验输入的相关信息 // *
	 * 
	 * @return
	 */
	private boolean checkSubject() {
		String difficult = difficultCombo.getValue();
		String assessment = assessmentCombo.getValue();
		String chapter = chapterTextField.getText().trim();
		String quesRemark = quesRemarkTextArea.getText().trim();
		chapterTextField.setText(chapter);
		String joint = jointTextField.getText().trim();
		jointTextField.setText(joint);
		String directory = directoryTextField.getText().trim();
		directoryTextField.setText(directory);
		String pages = pagesTextField.getText().trim();
		pagesTextField.setText(pages);
		
		if (StringUtils.isBlank(difficult)) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "难度不能为空!");
			return false;
		}
		if (StringUtils.isBlank(assessment)) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "考核要求不能为空!");
			return false;
		}
		if (StringUtils.isBlank(chapter)) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "章节目页不能为空!");
			return false;
		}
		/*if (StringUtils.isBlank(dry)) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "题干不能为空!");
			return false;
		}*/
		if (StringUtils.isNotBlank(subjectIdTextField.getText())) {
			SUBJECT.setSubjectId(Integer.parseInt(subjectIdTextField.getText()));
		}
		Subject editSubject = (Subject) StageManager.VARIABLE.get("edit_subject");
		
		SUBJECT.setCourseId(editSubject.getCourseId());
		SUBJECT.setQuestionTypeId(editSubject.getQuestionTypeId());
		SUBJECT.setChapter(chapter);
		SUBJECT.setJoint(Integer.parseInt(joint));
		SUBJECT.setDirectory(Integer.parseInt(directory));
		SUBJECT.setPages(Integer.parseInt(pages));
		SUBJECT.setDifficult(difficult);
		SUBJECT.setAssessment(assessment);
		SUBJECT.setRemark(quesRemark);
		//SUBJECT.setDry(dry);
		
		//判定每一个选项
		return true;
	}

	/**
	 * 新增题目选项 弹出框
	 */
	public void addSubjectOptionFunc(ActionEvent event) {
		try {
			// 把当前controller保存到map中，待其他页面使用
			StageManager.CONTROLLER.put("subjectController", this);
			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/AddSubjectOptionView.fxml"));
			Parent root = fxmlLoader.load();
			Stage stage = new Stage();
			stage.setTitle("新增题目选项");
			stage.setScene(new Scene(root));
			stage.show();
		} catch (IOException e) {
			LOGGER.error(e);
		}
	}

	/**
	 * 编辑题目(word).
	 */
	public void wordEditFunc(ActionEvent event) {
		Subject editSubject = (Subject) StageManager.VARIABLE.get("edit_subject");
		if (StringUtils.isBlank(this.assessmentCombo.getValue())) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "考核要求不能为空!");
			return;
		}
		if (StringUtils.isBlank(this.difficultCombo.getValue())) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "难度不能为空!");
			return;
		}
		wordEditeLogic(editSubject, event);
	}

	private void wordEditeLogic(Subject selectSubject, ActionEvent event) {
		try{
			String docName = selectSubject.getOrd() + ".docx";//保证题型都是从小到到排序(包括题型描述)
			String paprePrifix = selectSubject.getTestPaperId().substring(0, selectSubject.getTestPaperId().length() - 1);
			String docPath = System.getProperty("user.dir") + File.separator + "papers" + File.separator + paprePrifix + File.separator + selectSubject.getTestPaperId() + File.separator + "ques" + File.separator + docName;
			if (!new File(docPath).exists()) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "找不到试卷!");
				return;
			}
			Process proc = Runtime.getRuntime().exec("cmd /c \"" + docPath + "\"");
		    InputStream stderr = proc.getErrorStream();
		    InputStreamReader isr = new InputStreamReader(stderr);
		    BufferedReader br = new BufferedReader(isr);
		    String line = null;
		    while ( (line = br.readLine()) != null) {
			    System.err.println(line);
		    }
		    int exitVal = proc.waitFor();
		    if (exitVal == 0) {
		    	doSaveSubjectFunc(event);//来自 题目 编辑按钮调用
		    	//验证题目录入情况
		    	//validateWordQs(docPath, selectSubject);
		    }
		    LOG.info("-------word-------" + exitVal);
		} catch (Exception e) {
			LOG.error(e);
		}
	}
	
	//验证word题目
	public void validateWordQs(String docPath, Subject selectSubject) {
		if (selectSubject.getQuestionTypeId().intValue() == LtContext.TYPE_SINGLE_SELECT_ID
				|| selectSubject.getQuestionTypeName().equals("单项选择题")) {
			try {
				String[] caps = POIUtil.readWordParaCaption(docPath);
				if (!caps[1].startsWith("A") || !caps[2].startsWith("B") || !caps[3].startsWith("C") || !caps[4].startsWith("D")) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "单选题题必须存在 A、B、C、D选项。!");
				}
				if (caps[1].equals("A.") || caps[2].equals("B.") || caps[3].equals("C.") || caps[4].equals("D.")) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项不能为空，请修改!");
				}
				if (caps[1].equals(caps[2]) || caps[1].equals(caps[3]) || caps[1].equals(caps[4])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项1题干重复!");
				}
				if (caps[2].equals(caps[3]) || caps[2].equals(caps[4])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项2题干重复!");
				}
				if (caps[3].equals(caps[4])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项3题干重复!");
				}
			} catch (Exception e) {
				LOGGER.error(e);
			}
		} else if (selectSubject.getQuestionTypeId().intValue() == LtContext.TYPE_MULTI_SELECT_ID
				|| selectSubject.getQuestionTypeName().equals("多项选择题")) {
			try {
				String[] caps = POIUtil.readWordParaCaption(docPath);
				if (!caps[1].startsWith("A") || !caps[2].startsWith("B") || !caps[3].startsWith("C") || !caps[4].startsWith("D") || !caps[5].startsWith("E")) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "多选题题必须存在 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.")) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项不能为空，请修改!");
				}
				if (caps[1].equals(caps[2]) || caps[1].equals(caps[3]) || caps[1].equals(caps[4]) || caps[1].equals(caps[5])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项1题干重复!");
				}
				if (caps[2].equals(caps[3]) || caps[2].equals(caps[4]) || caps[2].equals(caps[5])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项2题干重复!");
				}
				if (caps[3].equals(caps[4]) || caps[3].equals(caps[5])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项3题干重复!");
				}
				if (caps[4].equals(caps[5])) {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "选项4题干重复!");
				}
			} catch (Exception e) {
				LOGGER.error(e);
			}
		}
		//检查是否又答案
		/*try {
			XWPFDocument word = new XWPFDocument(new FileInputStream(docPath));
			int pos = POIUtil.getAnswerParaPos(word);
			if (pos == -1) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "提示", "标准文档必须包含'答案及评分参考：'!");
			}
		} catch(Exception e) {
			e.printStackTrace();
		}*/
	}
	
	/**
	 * 关闭窗体
	 * 
	 * @param event
	 */
	private void closeCurrentWindow(ActionEvent event) {
		((Node) (event.getSource())).getScene().getWindow().hide();
	}

	/**
	 * 重置表单
	 */
	private void resetForm() {
		subjectIdTextField.setText("");
		difficultCombo.setValue("");
		assessmentCombo.setValue("");
		chapterTextField.setText("");
		jointTextField.setText("");
		directoryTextField.setText("");
		pagesTextField.setText("");
		subjectIdTextField.setText("");
		/*dryTextArea.setText("");
		singleAnswerCombo.setValue("");*/
	}

}
