package cn.hmsoft.ltc.controller;

import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;

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.RegexUtil;
import cn.hmsoft.ltc.common.util.StageManager;
import cn.hmsoft.ltc.model.Course;
import cn.hmsoft.ltc.model.CourseQuestion;
import cn.hmsoft.ltc.model.QuestionType;
import cn.hmsoft.ltc.model.TestPaper;
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.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.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.event.Event;
import javafx.event.EventHandler;
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.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
 * 
 * @author zq
 *
 */
@FXMLController
public class SetQuestionTypeController implements Initializable {

	@FXML
	private TableView<QuestionType> sourceQuesTableView;
	//题型-源数据源
	public final ObservableList<QuestionType> SOURCE_QUESTION_TYPE_LIST = FXCollections.observableArrayList();
	@FXML 
	public TableColumn<QuestionType, Integer> sQuesTypeIdCol;
	@FXML 
	public TableColumn<QuestionType, String> sQuesTypeCodeCol;
	@FXML 
	public TableColumn<QuestionType, String> sQuesTypeNameCol;
	@FXML 
	public TableColumn<QuestionType, String> sQuesTypScoreCol;
	@FXML 
	public TableColumn<QuestionType, Button> moveRightBtnCol;
	
	@FXML
	private TableView<QuestionType> targetQuesTableView;
	//题型-源数据源
	public final ObservableList<QuestionType> TARGET_QUESTION_TYPE_LIST = FXCollections.observableArrayList();
	@FXML 
	public TableColumn<QuestionType, Integer> tQuesTypeIdCol;
	@FXML 
	public TableColumn<QuestionType, String> tQuesTypeCodeCol;
	@FXML 
	public TableColumn<QuestionType, String> tQuesTypeNameCol;
	@FXML
	public TableColumn<QuestionType, TextField> tQuesTypScoreCol;//小题分
	@FXML
	public TableColumn<QuestionType, TextField> tQuesNumsCol;//小题量
	@FXML
	public TableColumn<QuestionType, Integer> tSubScoreCol;//小题合计
	@FXML 
	public TableColumn<QuestionType, Button> deleteBtnCol;
	
	@FXML
	public Label totalLb;//显示总题分
	
	@FXML
	public Button moveUpBtn;
	@FXML
	public Button moveDownBtn;
	@FXML
	public Button saveBtn;
	@FXML
	public Button closeBtn;
	
	private QuestionTypeService questionTypeService = new QuestionTypeServiceImpl();  //题型
	private CourseQuestionService courseQuestionService = new CourseQuestionServiceImpl();//
	public TestPaperService testPaperService = new TestPaperServiceImpl();  //试卷管理
	public CourseService courseService = new CourseServiceImpl();  //课程
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		sQuesTypeIdCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Integer>("id"));
		sQuesTypeCodeCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("code"));
		sQuesTypeNameCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("name"));
		sQuesTypScoreCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("scoreStr"));
		moveRightBtnCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Button>("moveRightBtn"));
		
		tQuesTypeIdCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Integer>("id"));
		tQuesTypeCodeCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("code"));
		tQuesTypeNameCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("name"));
		tQuesTypScoreCol.setCellValueFactory(new PropertyValueFactory<QuestionType, TextField>("typeScoreTx"));
		tQuesNumsCol.setCellValueFactory(new PropertyValueFactory<QuestionType, TextField>("quesNumsTx"));
		tSubScoreCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Integer>("subTotalStr"));
		deleteBtnCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Button>("deleteBtn"));
		
		//查询试卷状态--是否细目表已保存
		MainPaneController mainController = (MainPaneController)StageManager.CONTROLLER.get("mainPaneController");
		for (TestPaper paper : mainController.PAPER_TABLE_DATALIST) {
			if (paper.getStatus() == 1) {//细目表编辑完成保存后
				saveBtn.setDisable(true);
				break;
			}
		}
		
		
		SOURCE_QUESTION_TYPE_LIST.clear();
		TARGET_QUESTION_TYPE_LIST.clear();
		try {
			SOURCE_QUESTION_TYPE_LIST.addAll(this.questionTypeService.selectQuestionTypeObs());
			for (QuestionType question : SOURCE_QUESTION_TYPE_LIST) {
				question.getMoveRightBtn().setText("→");
				question.getMoveRightBtn().setOnAction(new EventHandler<ActionEvent>() {
					@Override
					public void handle(ActionEvent event) {
						if (!TARGET_QUESTION_TYPE_LIST.contains(question)) {
							TARGET_QUESTION_TYPE_LIST.add(question);
							question.getTypeScoreTx().setText(String.valueOf(question.getDefaultScore()));
							question.getDeleteBtn().setText("删除");
							question.getDeleteBtn().setOnAction(new EventHandler<ActionEvent>() {
								@Override
								public void handle(ActionEvent event) {
									TARGET_QUESTION_TYPE_LIST.remove(question);
									targetQuesTableView.refresh();

								}
							});
							targetQuesTableView.refresh();
						}
					}
				});
				//小题量修改后
				question.getQuesNumsTx().setOnKeyReleased(new EventHandler<Event>() {
					@Override
					public void handle(Event event) {
						String input = ((TextField)event.getSource()).getText().trim();
						//((TextField)event.getSource()).setText(input);
						if (StringUtils.isNotEmpty(input)) {
							bindKeyReleaseChangeNum(question, event, input);
						} else {
							setAndShowTotalScore(0);
						}
					}
				});
				//小题分修改后
				question.getTypeScoreTx().setOnKeyReleased(new EventHandler<Event>() {
					@Override
					public void handle(Event event) {
						String input = ((TextField)event.getSource()).getText().trim();
						//((TextField)event.getSource()).setText(input);
						if (StringUtils.isNotEmpty(input)) {
							bindKeyReleaseChangeScore(question, event, input);
						} else {
							setAndShowTotalScore(0);
						}
					}
				});
			}
			double total = 0;
			TARGET_QUESTION_TYPE_LIST.clear();
			TARGET_QUESTION_TYPE_LIST.addAll(this.courseQuestionService.findQuestionTypeList(LtContext.CURR_COURSE.getId()));
			for (QuestionType question : TARGET_QUESTION_TYPE_LIST) {
				question.getDeleteBtn().setText("删除");
				question.getDeleteBtn().setOnAction(new EventHandler<ActionEvent>() {
					@Override
					public void handle(ActionEvent event) {
						//QuestionType selected = targetQuesTableView.getSelectionModel().getSelectedItem();
						TARGET_QUESTION_TYPE_LIST.remove(question);
						targetQuesTableView.refresh();
						//删除后总分变为0
						setAndShowTotalScore(0);
					}
				});
				//修改小题量
				question.getQuesNumsTx().setOnKeyReleased(new EventHandler<Event>() {
					@Override
					public void handle(Event event) {
						String input = ((TextField)event.getSource()).getText().trim();
						//((TextField)event.getSource()).setText(input);
						if (StringUtils.isNotEmpty(input)) {
							bindKeyReleaseChangeNum(question, event, input);
						} else {
							setAndShowTotalScore(0);
						}
					} 
				});
				//小题分修改后
				question.getTypeScoreTx().setOnKeyReleased(new EventHandler<Event>() {
					@Override
					public void handle(Event event) {
						String input = ((TextField)event.getSource()).getText().trim();
						//((TextField)event.getSource()).setText(input);
						if (StringUtils.isNotEmpty(input)) {
							bindKeyReleaseChangeScore(question, event, input);
						} else {
							setAndShowTotalScore(0);
						}
					}
				});
				//加载之前保存的总分
				total += question.getSubTotal();
				question.setSubTotalStr(question.getSubTotal());
			}
			NumberFormat format = NumberFormat.getInstance();
			setAndShowTotalScore(total);
			totalLb.setText(format.format(total));
			sourceQuesTableView.setItems(SOURCE_QUESTION_TYPE_LIST);
			targetQuesTableView.setItems(TARGET_QUESTION_TYPE_LIST);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void setAndShowTotalScore(double total) {
		if (total > 100) {
			totalLb.setTextFill(Color.RED);
		} else {
			totalLb.setTextFill(Color.BLACK);
		}
		NumberFormat format = NumberFormat.getInstance();
		totalLb.setText(format.format(total));
	}

	/**
	 * 小题量修改后触发.
	 * @param question
	 * @param event
	 * @param input
	 */
	private void bindKeyReleaseChangeNum(QuestionType question, Event event, String input) {
		if (RegexUtil.isPositiveNumber(input)) {
			int total = 0;
			for (QuestionType ques : TARGET_QUESTION_TYPE_LIST) {
				if (ques.equals(question) && StringUtils.isNotEmpty(question.getTypeScoreTx().getText())) {
					question.setSubTotal(Integer.valueOf(input) * Integer.valueOf(question.getTypeScoreTx().getText()));//
					question.setSubTotalStr(question.getSubTotal());
				}
				total += ques.getSubTotal();
			}
			setAndShowTotalScore(total);
			targetQuesTableView.refresh();
		} else {
			((TextField)event.getSource()).setText("");
			totalLb.setText("");//清空总分显示
		}
	}
	
	/**
	 * 小题分修改后触发.
	 * @param question
	 * @param event
	 * @param input
	 */
	private void bindKeyReleaseChangeScore(QuestionType question, Event event, String input) {
		if (RegexUtil.isPositiveNumber(input)) {
			int total = 0;
			for (QuestionType ques : TARGET_QUESTION_TYPE_LIST) {
				if (ques.equals(question) && StringUtils.isNotEmpty(question.getQuesNumsTx().getText())) {
					question.setSubTotal(Integer.valueOf(input) * Integer.valueOf(question.getQuesNumsTx().getText()));//
					question.setSubTotalStr(question.getSubTotal());
				}
				total += ques.getSubTotal();
			}
			setAndShowTotalScore(total);
			targetQuesTableView.refresh();
		} else {
			((TextField)event.getSource()).setText("");
			totalLb.setText("");//清空总分显示
		}
	}
	
	@FXML
	public void moveUpFunc(ActionEvent event) {
		if (targetQuesTableView.getSelectionModel().getSelectedIndex() == -1) {
			return;
		}
		int index = targetQuesTableView.getSelectionModel().getSelectedIndex();
		if (index > 0) {
			ObservableList<QuestionType> tempList = FXCollections.observableArrayList();
			tempList.addAll(TARGET_QUESTION_TYPE_LIST.subList(0, index + 1));
			QuestionType currObj = targetQuesTableView.getSelectionModel().getSelectedItem();
			QuestionType upObj = TARGET_QUESTION_TYPE_LIST.get(index - 1);//上面待交换对象
			tempList.remove(currObj);
			tempList.remove(upObj);
			tempList.add(currObj);
			tempList.add(upObj);
			if (TARGET_QUESTION_TYPE_LIST.size() - 1 > index) {
				tempList.addAll(TARGET_QUESTION_TYPE_LIST.subList(index + 1, TARGET_QUESTION_TYPE_LIST.size()));
			}
			TARGET_QUESTION_TYPE_LIST.clear();
			TARGET_QUESTION_TYPE_LIST.addAll(tempList);
			targetQuesTableView.refresh();
			targetQuesTableView.getSelectionModel().select(index - 1);//选中上一行
		}
	}
	
	@FXML
	public void moveDownFunc(ActionEvent event) {
		if (targetQuesTableView.getSelectionModel().getSelectedIndex() == -1) {
			return;
		}
		int index = targetQuesTableView.getSelectionModel().getSelectedIndex();
		if (index < TARGET_QUESTION_TYPE_LIST.size() - 1) {
			ObservableList<QuestionType> tempList = FXCollections.observableArrayList();
			tempList.addAll(TARGET_QUESTION_TYPE_LIST.subList(0, index));
			tempList.add(TARGET_QUESTION_TYPE_LIST.get(index + 1));
			tempList.add(TARGET_QUESTION_TYPE_LIST.get(index));
			if (index + 2 <= TARGET_QUESTION_TYPE_LIST.size() - 1) {
				tempList.addAll(TARGET_QUESTION_TYPE_LIST.subList(index + 2, TARGET_QUESTION_TYPE_LIST.size()));
			}
			TARGET_QUESTION_TYPE_LIST.clear();
			TARGET_QUESTION_TYPE_LIST.addAll(tempList);
			targetQuesTableView.refresh();
			targetQuesTableView.getSelectionModel().select(index + 1);//选中上一行
		}
	}
	
	@FXML
	public void saveFunc(ActionEvent event) throws SQLException {
		if (StringUtils.isEmpty(totalLb.getText()) || Integer.valueOf(totalLb.getText()) - 100 != 0) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "总分必须100!");
			return;
		}
		//检查输入
		boolean existEmpty = false;
		for (int i=0; i<TARGET_QUESTION_TYPE_LIST.size(); i++) {
			QuestionType qt = TARGET_QUESTION_TYPE_LIST.get(i);
			if (StringUtils.isEmpty(qt.getTypeScoreTx().getText())
					|| StringUtils.isEmpty(qt.getQuesNumsTx().getText())) {
				existEmpty = true;
				break;
			}
		}
		if (existEmpty) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "小题分、小题量都不能为空!");
			return;
		}
		Course course = LtContext.CURR_COURSE;
		//修改教材校验状态
		this.courseService.updateCourseById(course.getId());
		
		this.courseQuestionService.deleteCourseQuestion(course.getId());
		for (int i=0; i<TARGET_QUESTION_TYPE_LIST.size(); i++) {
			QuestionType qt = TARGET_QUESTION_TYPE_LIST.get(i);
			CourseQuestion cq = new CourseQuestion();
			cq.setCourseId(course.getId());
			cq.setQuesNums(Integer.valueOf(qt.getQuesNumsTx().getText()));
			cq.setQuesTypeId(qt.getId());
			cq.setScore(Integer.valueOf(qt.getTypeScoreTx().getText()));
			cq.setOrd((i+1));//排序号
			this.courseQuestionService.insertCourseQuestion(cq);
		}
		//生成ABC卷
		//试卷编号(课程编号+批次号+A/B/C)
		this.testPaperService.deleteTestPaper(course.getId());
		
		String pageNoA = course.getCode() + course.getBatchNumber() + "A";
		TestPaper testPaperA = new TestPaper();
		testPaperA.setPaperNo(pageNoA);
		testPaperA.setCourseCode(course.getCode());
		testPaperA.setCourseName(course.getName());
		testPaperA.setStatus(PaperStageEnum.NEW.ordinal());
		testPaperA.setUserId(LtContext.LOGIN_USER_ID);
		testPaperA.setRemark("");
		testPaperA.setCourseId(course.getId());
		testPaperA.setChapterNumber(course.getChapterNumber());
		
		String pageNoB = course.getCode() + course.getBatchNumber() + "B";
		TestPaper testPaperB = new TestPaper();
		testPaperB.setPaperNo(pageNoB);
		testPaperB.setCourseCode(course.getCode());
		testPaperB.setCourseName(course.getName());
		testPaperB.setStatus(PaperStageEnum.NEW.ordinal());
		testPaperB.setUserId(LtContext.LOGIN_USER_ID);
		testPaperB.setRemark("");
		testPaperB.setCourseId(course.getId());
		testPaperB.setChapterNumber(course.getChapterNumber());
		
		String pageNoC = course.getCode() + course.getBatchNumber() + "C";
		TestPaper testPaperC = new TestPaper();
		testPaperC.setPaperNo(pageNoC);
		testPaperC.setCourseCode(course.getCode());
		testPaperC.setCourseName(course.getName());
		testPaperC.setStatus(PaperStageEnum.NEW.ordinal());
		testPaperC.setUserId(LtContext.LOGIN_USER_ID);
		testPaperC.setRemark("");
		testPaperC.setCourseId(course.getId());
		testPaperC.setChapterNumber(course.getChapterNumber());
		try {
			this.testPaperService.insertTestPaper(testPaperA);
			this.testPaperService.insertTestPaper(testPaperB);
			this.testPaperService.insertTestPaper(testPaperC);
			//刷新试卷列表.
			MainPaneController mainController = (MainPaneController)StageManager.CONTROLLER.get("mainPaneController");
			mainController.selectPaperTable();//刷新 重新查询试卷
		} catch (SQLException e) {
			e.printStackTrace();
		}
		LtContext.CURR_COURSE = null;
		//刷新试卷列表
		DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "成功", "保存成功!");
		//关闭当前窗体
		((Node) (event.getSource())).getScene().getWindow().hide();
		
		Course course1 = new Course();
		course1 = this.courseService.selectCourseById(course.getId());
		course.setId(course1.getId());
		course.setCode(course1.getCode());
		course.setCodeHubei(course1.getCodeHubei());
		course.setName(course1.getName());
		course.setStatusName(course.getStatus() == 0 ? "停用" : "启用");
		course.setOpenEdit(course1.getOpenEdit());
		course.setChapterNumber(course1.getChapterNumber());
		course.setTeachBook(course1.getTeachBook());
		course.setTeachOutline(course1.getTeachOutline());
		course.setSchoolName(LtContext.LOGIN_SCHOOL);
		course.setBatchNumber(course1.getBatchNumber());
		course.setVerificationTextbook(course1.getVerificationTextbook());
		course.setEditor(course1.getEditor());
		course.setEdition(course1.getEdition());
		course.setPress(course1.getPress());
		course.setVerificationTextbookName(course1.getVerificationTextbook() == 0 ? "未校验" : "已校验");
		
		MainPaneController mainController = (MainPaneController)StageManager.CONTROLLER.get("mainPaneController");
		mainController.COURSE_TABLE_DATALIST.clear();//先清理list数据，在添加
		mainController.COURSE_TABLE_DATALIST.add(course);
		mainController.courseTableView.refresh();
		course.getOperBtn().setText("关联题型");
		course.getOperBtn().setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				try {
					LtContext.CURR_COURSE = course;
					FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/setQuestionType.fxml"));
					Parent root = fxmlLoader.load();
					Stage stage = new Stage();
					stage.setResizable(false);
					stage.setTitle("(" + course.getCode() + ") " + course.getName() + "-关联题型");
					stage.setScene(new Scene(root, 1181, 663));
					stage.setAlwaysOnTop(true);
					stage.setMaximized(false);
					stage.show();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		
		course.getOperUpdateBtn().setText("修改课程章节");
		course.getOperUpdateBtn().setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				try {
					LtContext.CURR_COURSE = course;
					FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/UpdateCourseView.fxml"));
					Parent root = fxmlLoader.load();
					Stage stage = new Stage();
					stage.setResizable(false);
					stage.setTitle("(" + course.getCode() + ") " + course.getName() + "-修改课程章节");
					stage.setScene(new Scene(root, 414,184));
					stage.setAlwaysOnTop(true);
					stage.setMaximized(false);
					stage.show();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	@FXML
	public void closeWinFunc(ActionEvent event) {
		LtContext.CURR_COURSE = null;
		((Node) (event.getSource())).getScene().getWindow().hide();
	}
}
