package cn.hmsoft.ltc.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.OldExcelFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hmsoft.ltc.common.constants.LtContext;
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.TestPaper;
import cn.hmsoft.ltc.model.Users;
import cn.hmsoft.ltc.service.iface.AwesomeActionService;
import cn.hmsoft.ltc.service.iface.CourseService;
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.TestPaperService;
import cn.hmsoft.ltc.service.iface.UserService;
import cn.hmsoft.ltc.service.impl.CourseServiceImpl;
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.TestPaperServiceImpl;
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.geometry.Rectangle2D;
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.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import javafx.stage.Screen;
import javafx.stage.Stage;

/**
 *主程序页面 
 * @author zq
 *
 */
@FXMLController
public class MainPaneController implements Initializable {
	
	@FXML 
	public BorderPane mainBorderPane;
	@FXML
	public TabPane mainTabPane;
	@FXML
	public Tab sysTab; 
	@FXML
	public Tab detailTab;
	@FXML
	public Tab testPaperTab;
	@FXML
	public Tab questionTypesTab;
	@FXML
	public Tab courseTab;
	@FXML
	public Tab paperTab;
	@FXML
	public AnchorPane mainBorderAnchorPane;
	@FXML
	public AnchorPane detailAnchorPane;
	@FXML
	public AnchorPane questionTypesAnchorPane;
	@FXML
	public AnchorPane testPaperAnchorPane;
	@FXML
	public AnchorPane courseAnchorPane;
	
	@FXML 
	public Label newPwdLabel;
	@FXML 
	public Label pwdLabel; 
	@FXML 
	public PasswordField pwdTextFiled;
	@FXML 
	public PasswordField newPwdTextFiled;
	//--------------------------------课程--相关------------------------------------------------------
    @FXML
    public Button addCourseBtn;
    @FXML
    public Button deleteCourseBtn;
	@FXML
	public Button impCourseBtn;//导入课程
	@FXML
	public Button expCourseBtn;//导出课程
	@FXML
	public Button updateCourseBtn;//修改课程章节
	
	@FXML 
	public TableView<Course> courseTableView;//课程管理表格对象
  	//课程管理列表--数据源
  	public final ObservableList<Course> COURSE_TABLE_DATALIST = FXCollections.observableArrayList(); 
	@FXML 
	public TableColumn<Course, Integer> courseIdCol;
	@FXML 
	public TableColumn<Course, String> courseCodeCol;
	@FXML 
	public TableColumn<Course, String> courseNameCol;
	@FXML 
	public TableColumn<Course, String> courseStatusCol;
	@FXML 
	public TableColumn<Course, Integer> courseChapterNumCol;
	@FXML 
	public TableColumn<Course, String> teachBookCol;
	@FXML 
	public TableColumn<Course, String> editorCol; //【编者】
	@FXML 
	public TableColumn<Course, String> editionCol;  //【版次】
	@FXML 
	public TableColumn<Course, String> pressCol; //【出版社】
	@FXML 
	public TableColumn<Course, String> verificationTextbookCol;  //【教材是否校验】 0:未校验，1：校验
	@FXML 
	public TableColumn<Course, String> teachOutlineCol;
	@FXML 
	public TableColumn<Course, String> batchNumberCol;///批次号
	@FXML 
	public TableColumn<Course, String> courseRemarkCol;
	@FXML 
	public TableColumn<Course, Button> courseOperCol;
	@FXML 
	public TableColumn<Course, Button> courseOperUpdateCol;//修改课程章节
	
	
	//--------------------------------题型表--相关------------------------------------------------------
	@FXML 
	public TableView<QuestionType> questionTypeTableView;
	//题型数据源
	public final ObservableList<QuestionType> DATALIST_QUESTION_TYPE = FXCollections.observableArrayList();
	@FXML 
	public TableColumn<QuestionType, Integer> questionTypeIdCol;
	@FXML 
	public TableColumn<QuestionType, String> questionTypeCodeCol;
	@FXML 
	public TableColumn<QuestionType, String> questionTypeNameCol;
	@FXML 
	public TableColumn<QuestionType, Integer> questionScoreCol;
	@FXML 
	public TableColumn<QuestionType, String> questionTypeStatusCol;
	@FXML 
	public TableColumn<QuestionType, String> correctOptionNameCol;
	@FXML 
	public TableColumn<QuestionType, String> guideTextCol;
	@FXML 
	public TableColumn<QuestionType, Integer> editeStatusCol;
	//------------------------------试卷--列-----------------------------------------------------------
	@FXML
    public Button saveSysBtn;   //保存细目表
	@FXML
	public Button buildBtn;   //编辑试卷
	@FXML
	public Button editAnswerBtn;  //编辑答案
	@FXML
	public Button edintTopicCardBtn;  //编辑答题卡

	@FXML 
	public TableView<TestPaper> paperTableView;//试卷表格对象
  	//课程管理列表--数据源
  	public final ObservableList<TestPaper> PAPER_TABLE_DATALIST = FXCollections.observableArrayList(); 
	@FXML 
	public TableColumn<TestPaper, Integer> pCourseIdCol;
	@FXML 
	public TableColumn<TestPaper, String> paperNoCol; //试卷编号
	@FXML 
	public TableColumn<TestPaper, String> pCourseCodeCol;//课程代码
	@FXML 
	public TableColumn<TestPaper, String> pCourseNameCol;//课程名称
	@FXML 
	public TableColumn<TestPaper, String> pStatusNameCol;//状态名称
	@FXML 
	public TableColumn<TestPaper, String> pRemarkCol;//状态名称
	@FXML 
	public TableColumn<TestPaper, Button> pDetailTableCol;//细目表
	@FXML 
	public TableColumn<TestPaper, Button> pSubjectEditCol;//细目表
	@FXML 
	public TableColumn<TestPaper, Button> pExportPaperCol;//导出试卷
	@FXML 
	public TableColumn<TestPaper, Button> pEstimatedDifficultyCol;//试卷预估难度统计
	/*@FXML 
	public TableColumn<TestPaper, Button> pExpDtBtnCol;//导出细目表
*/  	//------------------------------------------------------------

    @FXML
    public Button addQuestionTypesBtn;
    @FXML
    public Button deleteQuestionTypesBtn;

    //用户
    @FXML
    public TableView<Users> userTableView;
	@FXML 
	public TableColumn<Users, String> userNameCol;//用户名
	@FXML 
	public TableColumn<Users, String> userPassCol;//用户密码
	@FXML 
	public TableColumn<Users, String> userPhoneCol;//用户电话
	public final ObservableList<Users> DATALIST_USERS = FXCollections.observableArrayList();
	
	//服务注入
    @Autowired
    public AwesomeActionService actionService;

	public QuestionTypeService questionTypeService = new QuestionTypeServiceImpl();  //题型
	public CourseService courseService = new CourseServiceImpl();  //课程
	public DetailTableService detailTableService = new DetailTableServiceImpl(); //细目表
	public SubjectService subjectService = new SubjectServiceImpl();
	public SubjectOptionServie subjectOptionServie = new SubjectOptionServieImpl();
    public String chactCount =  "";
    public TestPaperService testPaperService = new TestPaperServiceImpl();  //试卷管理
    private static final Logger LOGGER = Logger.getLogger(MainPaneController.class);
    
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		//普通用户按钮disable
		if (LtContext.CURR_LOGIN_USER.getUserRole().intValue() == 0) {
			addCourseBtn.setDisable(true);
			deleteCourseBtn.setDisable(true);
			impCourseBtn.setDisable(true);
			expCourseBtn.setDisable(true);
		}
		//表格列
		pCourseIdCol.setCellValueFactory(new PropertyValueFactory<TestPaper, Integer>("id"));
		paperNoCol.setCellValueFactory(new PropertyValueFactory<TestPaper, String>("paperNo"));
		pCourseCodeCol.setCellValueFactory(new PropertyValueFactory<TestPaper, String>("courseCode"));
		pCourseNameCol.setCellValueFactory(new PropertyValueFactory<TestPaper, String>("courseName"));
		pStatusNameCol.setCellValueFactory(new PropertyValueFactory<TestPaper, String>("statusName"));
		pRemarkCol.setCellValueFactory(new PropertyValueFactory<TestPaper, String>("remark"));
		pDetailTableCol.setCellValueFactory(new PropertyValueFactory<TestPaper, Button>("detailTableBtn"));
		pSubjectEditCol.setCellValueFactory(new PropertyValueFactory<TestPaper, Button>("subjectEditBtn"));
		pExportPaperCol.setCellValueFactory(new PropertyValueFactory<TestPaper, Button>("exportPaperBtn"));
		pEstimatedDifficultyCol.setCellValueFactory(new PropertyValueFactory<TestPaper, Button>("estimatedDifficultyBtn"));
		
		userNameCol.setCellValueFactory(new PropertyValueFactory<Users, String>("userName"));
		userPassCol.setCellValueFactory(new PropertyValueFactory<Users, String>("passwd"));
		userPhoneCol.setCellValueFactory(new PropertyValueFactory<Users, String>("phone"));
		try {
			if (LtContext.CURR_LOGIN_USER.getUserRole() == 1) {//管理员才显示用户列表
				//查询用户
				userTableView.setVisible(true);
				this.selectUsers();
			} else {
				userTableView.setVisible(false);
			}

			//初始化题型信息
			this.selectQuestionType();
			//初始化课程列表信息
			this.selectCourseTable();
			//查询用户的试卷
			this.selectPaperTable();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	    StageManager.CONTROLLER.put("mainPaneController", this);
	}
	
	private void selectUsers() {
		UserService userService = new UserServiceImpl();
		try {
			DATALIST_USERS.addAll(userService.listUsers());
			userTableView.setItems(DATALIST_USERS);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 密码修改保存
	 * @param event
	 */
	@FXML
	public void doSaveFun(ActionEvent event) {
		//提示框
		try {
			String userName = LtContext.LOGIN_USER_NAME;
			String passWord = pwdTextFiled.getText();
			String verifyPasswd = newPwdTextFiled.getText();
			//新密码不能为空
			if (passWord.length() == 0) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "新密码不能为空，请输入新密码!");
				//如果密码和确认密码不一致，重置为空。
				pwdTextFiled.setText("");
				newPwdTextFiled.setText("");
				return ;
			}
			//新密码和确认密码必须一致
			if (!passWord.trim().equals(verifyPasswd.trim())) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "请检查新密码和确认密码是否一致!");
				//如果密码和确认密码不一致，重置为空。
				pwdTextFiled.setText("");
				newPwdTextFiled.setText("");
				return ;
			}
			UserService userService = new UserServiceImpl();
			boolean flag = userService.updateUserPwd(userName, passWord);
			if(flag == true) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "成功", "密码修改成功！");
			}
		} catch(Exception ee) {
			ee.printStackTrace();
		}
	}
	
	/**
	 *  新增题型
	 * @param event
	 * @throws SQLException 
	 */
	@FXML
	public void doAddQuestionTypesFun(ActionEvent event) throws SQLException {
		try {
			//跳转到注册页面
			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/AddQuestionTypesView.fxml"));
			Parent root = fxmlLoader.load();
			Stage stage = new Stage();
			stage.setTitle("题型新增");
			stage.setScene(new Scene(root,433,517));
			stage.show();
			//关闭当前窗体
			//((Node) (event.getSource())).getScene().getWindow().hide();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除题型信息
	 * @param event
	 * @throws SQLException 
	 */
	@FXML
	public void doDeleteQuestionTypesFun(ActionEvent event) throws SQLException {
		QuestionType questionSelected = questionTypeTableView.getSelectionModel().getSelectedItem();
		//提示框
		if (questionSelected == null) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "请选择!");
			return;
		}
		if (questionSelected.getEditeStatus() == 0) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "不能删除系统内置题型!");
			return;
		}
		if (DialogUtil.confirm("是否删除？", GUIState.getStage())) {
			this.questionTypeService.deleteQuestionType(questionSelected.getId());
			DATALIST_QUESTION_TYPE.remove(questionSelected);//列表删除
		}
	}
	
	
	/**
	 * 查询课程列表信息
	 * @throws SQLException 
	 */
	public void selectCourseTable() throws SQLException {
		courseIdCol.setCellValueFactory(new PropertyValueFactory<Course, Integer>("id"));
		courseCodeCol.setCellValueFactory(new PropertyValueFactory<Course, String>("code"));
		courseNameCol.setCellValueFactory(new PropertyValueFactory<Course, String>("name"));
		courseChapterNumCol.setCellValueFactory(new PropertyValueFactory<Course, Integer>("chapterNumber"));
		teachBookCol.setCellValueFactory(new PropertyValueFactory<Course, String>("teachBook"));
		
		editorCol.setCellValueFactory(new PropertyValueFactory<Course, String>("editor"));
		editionCol.setCellValueFactory(new PropertyValueFactory<Course, String>("edition"));
		pressCol.setCellValueFactory(new PropertyValueFactory<Course, String>("press"));
		verificationTextbookCol.setCellValueFactory(new PropertyValueFactory<Course, String>("verificationTextbookName"));
		
		teachOutlineCol.setCellValueFactory(new PropertyValueFactory<Course, String>("teachOutline"));
		batchNumberCol.setCellValueFactory(new PropertyValueFactory<Course, String>("batchNumber"));
		courseStatusCol.setCellValueFactory(new PropertyValueFactory<Course, String>("statusName"));
		courseRemarkCol.setCellValueFactory(new PropertyValueFactory<Course, String>("remark"));
		courseOperCol.setCellValueFactory(new PropertyValueFactory<Course, Button>("operBtn")); //关联题型
		courseOperUpdateCol.setCellValueFactory(new PropertyValueFactory<Course, Button>("operUpdateBtn"));//修改课程章节
		
		COURSE_TABLE_DATALIST.clear();
		Integer courseId = null;
		String schoolName = null;
		//老师登陆只能看到自己注册选择的课程
		if (LtContext.CURR_LOGIN_USER.getUserRole().intValue() == 0) {
			courseId = LtContext.CURR_LOGIN_USER.getCourseId();
		} else if (LtContext.CURR_LOGIN_USER.getUserRole().intValue() == 1) {
			schoolName = null;//管理员默认查询所有课程.
		}
		COURSE_TABLE_DATALIST.addAll(this.courseService.selectCourse(courseId, schoolName));
		courseTableView.setItems(COURSE_TABLE_DATALIST);
		courseTableView.refresh();
		//绑定
		for (Course course : COURSE_TABLE_DATALIST) {
			course.getOperBtn().setText("关联题型");
			course.getOperBtn().setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					try {
						LtContext.CURR_COURSE = course;
						String checkteacherBook="请校验拿到的命题教材：\r\n" + 
								"【教材名称】：【"+course.getTeachBook()+"】、\r\n"
								+ "【编者】:【"+course.getEditor()+"】、\r\n"
								+ "【版次】:【"+course.getEdition()+"】、\r\n"
								+ "【出版社】:【"+course.getPress()+"】 是否正确！";
						if (DialogUtil.confirm(checkteacherBook, "教材校验", GUIState.getStage())) {
							//修改教材校验状态
							try {
								courseService.updateCourseById(course.getId());
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							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 event) {
					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();
					}
				}
			});
		}
	}
	
	/**
	 * 查询试卷列表信息
	 * @throws SQLException 
	 */
	public void selectPaperTable() throws SQLException {
		PAPER_TABLE_DATALIST.clear();
		PAPER_TABLE_DATALIST.addAll(this.testPaperService.selectTestPaper());
		paperTableView.setItems(PAPER_TABLE_DATALIST);
		for (TestPaper paper : PAPER_TABLE_DATALIST) {
			paper.getDetailTableBtn().setText("编辑细目表");
			paper.getDetailTableBtn().setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					TestPaperService testPaperServiceTemp = new TestPaperServiceImpl();  //试卷管理
					try {
						TestPaper paperTemp = testPaperServiceTemp.selectTestPaperByPageNo(paper.getPaperNo());
						paper.setChapterNumber(paperTemp.getChapterNumber());
						
						LtContext.CURR_PAPER = paper;
						FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/DetailTableView.fxml"));
						Parent root = fxmlLoader.load();
						Stage stage = new Stage();
						stage.setResizable(false);
						stage.setTitle("(" + paper.getCourseCode() + ") " + paper.getCourseName() + "-" + paper.getPaperNo());
						stage.setScene(new Scene(root));
						//stage.setAlwaysOnTop(true);
						stage.setMaximized(false);
						Rectangle2D screen = Screen.getPrimary().getVisualBounds();
						stage.setX(screen.getMinX());
						stage.setY(screen.getMinY());
						stage.setWidth(screen.getWidth());
						stage.setHeight(screen.getHeight());
						stage.show();
					} catch (Exception e) {
						LOGGER.error(e);
					}
				}
			});
			paper.getSubjectEditBtn().setText("编辑题目");
			paper.getSubjectEditBtn().setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					TestPaperService testPaperServiceTemp1 = new TestPaperServiceImpl();  //试卷管理
					try {
						TestPaper paperTemp = testPaperServiceTemp1.selectTestPaperByPageNo(paper.getPaperNo());
						paper.setChapterNumber(paperTemp.getChapterNumber());
						
						LtContext.CURR_PAPER = paper;
						FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/SubjectMainView.fxml"));
						Parent root = fxmlLoader.load();
						Stage stage = new Stage();
						stage.setResizable(false);
						stage.setTitle("(" + paper.getCourseCode() + ") " + paper.getCourseName() + "-" + paper.getPaperNo());
						stage.setScene(new Scene(root));
						stage.setMaximized(false);
						Rectangle2D screen = Screen.getPrimary().getVisualBounds();
						stage.setX(screen.getMinX());
						stage.setY(screen.getMinY());
						stage.setWidth(screen.getWidth());
						stage.setHeight(screen.getHeight());
						stage.show();
					} catch (Exception e) {
						DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "失败", e.getMessage());
						LOGGER.error(e);
					}
				}
			});
			paper.getExportPaperBtn().setText("导出试卷和答案");
			paper.getExportPaperBtn().setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					TestPaperService testPaperServiceTemp2 = new TestPaperServiceImpl();  //试卷管理
					SubjectMainController subjectMainController = getSubjectMainController();
					try {
						if (DialogUtil.confirm("导出试卷和答案时，请仔细在系统中核对试卷和答案，确保导出试卷和答案一致！", GUIState.getStage())) {
							TestPaper paperTemp = testPaperServiceTemp2.selectTestPaperByPageNo(paper.getPaperNo());
							paper.setChapterNumber(paperTemp.getChapterNumber());
							
							LtContext.CURR_PAPER = paper;
							subjectMainController.wordMergeFun1(null);
							String savePath = System.getProperty("user.dir") + File.separator + "papers" + File.separator;
							DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "成功", "导出成功,保存路径:" + savePath);
						}
					} catch (Exception e) {
						DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "失败", e.getMessage());
						LOGGER.error(e);
					}
				}
			});
			paper.getEstimatedDifficultyBtn().setText("试卷预估难度统计");
			paper.getEstimatedDifficultyBtn().setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent event) {
					TestPaperService testPaperServiceTemp1 = new TestPaperServiceImpl();  //试卷管理
					try {
						TestPaper paperTemp = testPaperServiceTemp1.selectTestPaperByPageNo(paper.getPaperNo());
						paper.setChapterNumber(paperTemp.getChapterNumber());
						
						LtContext.CURR_PAPER = paper;
						FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/EstimatedDifficultyView.fxml"));
						Parent root = fxmlLoader.load();
						Stage stage = new Stage();
						stage.setResizable(false);
						stage.setTitle("(" + paper.getCourseCode() + ") " + paper.getCourseName() + "-" + paper.getPaperNo()+"-预估难度统计表");
						stage.setScene(new Scene(root));
						stage.setMaximized(false);
						Rectangle2D screen = Screen.getPrimary().getVisualBounds();
						stage.setX(screen.getMinX());
						stage.setY(screen.getMinY());
						stage.setWidth(screen.getWidth());
						stage.setHeight(screen.getHeight());
						stage.show();
					} catch (Exception e) {
						DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "失败", e.getMessage());
						LOGGER.error(e);
					}
				}
			});
		}
	}
	
	public SubjectMainController getSubjectMainController() {
		SubjectMainController subjectMainController = (SubjectMainController)StageManager.CONTROLLER.get("subjectMainController");
		if (subjectMainController == null) {
			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/SubjectMainView.fxml"));
			try {
				fxmlLoader.load();
				subjectMainController = (SubjectMainController)fxmlLoader.getController();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return subjectMainController;
	}
	
	/**
	 * 查询题型信息
	 * @throws SQLException 
	 */
	public void selectQuestionType() throws SQLException {
		questionTypeIdCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Integer>("id"));
		questionTypeCodeCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("code"));
		questionTypeNameCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("name"));
		correctOptionNameCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("correctOptionsName"));
		questionScoreCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Integer>("defaultScore"));
		questionTypeStatusCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("statusName"));
		guideTextCol.setCellValueFactory(new PropertyValueFactory<QuestionType, String>("guideText"));
		editeStatusCol.setCellValueFactory(new PropertyValueFactory<QuestionType, Integer>("editeStatus"));
		DATALIST_QUESTION_TYPE.clear();
		DATALIST_QUESTION_TYPE.addAll(this.questionTypeService.selectQuestionTypeObs());
		questionTypeTableView.setItems(DATALIST_QUESTION_TYPE);
	}
	
	/** 
	 * 新增课程信息
	 * @param event
	 */
	@FXML
	public void doAddCourseFun(ActionEvent event) {
		try {
			//跳转到注册页面
			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/AddCourseView.fxml"));
			Parent root = fxmlLoader.load();
			Stage stage = new Stage();
			stage.setTitle("课程新增");
			stage.setScene(new Scene(root,372,414));
			stage.setMaximized(false);
			stage.setAlwaysOnTop(true);
			stage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除课程信息
	 * @param event
	 * @throws SQLException 
	 */
	@FXML
	public void doDeleteCourseFun(ActionEvent event) throws SQLException {
		Course courseSelected = courseTableView.getSelectionModel().getSelectedItem();
		//提示框
		if (courseSelected == null) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.WARNING, "提示", "请选择删除的课程！");
			return;
		}
		if (DialogUtil.confirm("是否删除？", GUIState.getStage())) {
			this.courseService.deleteCourse(courseSelected.getId());
			COURSE_TABLE_DATALIST.remove(courseSelected);//列表删除
		}
	}
	
	/**
	 * 修改课程章节
	 * @param event
	 */
	@FXML
	public void doUpdateCourseFun(ActionEvent event) {
		try {
			//跳转到注册页面
			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/UpdateCourseView.fxml"));
			Parent root = fxmlLoader.load();
			Stage stage = new Stage();
			stage.setTitle("课程章节修改");
			stage.setScene(new Scene(root,414,184));
			stage.setMaximized(false);
			stage.setAlwaysOnTop(true);
			stage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 设置窗体大小
	 * @param width
	 * @param height
	 */
	public void initGui(double width, double height) {
		this.saveSysBtn.setLayoutX(50);
	}
	
	/**
	 * 获取课程总章节数
	 * @param code 课程编号
	 * @return
	 * @throws SQLException
	 */
	public int getChapterNumber() throws SQLException {
		String code = "1001";
		int chapTerNumber = this.courseService.selectCourse(code);
		chactCount = String.valueOf(chapTerNumber);
		return chapTerNumber;
	}
	
	/**
	 * 新增题目窗口
	 * @param event
	 */
	@FXML
	public void doAddSubjectFun(ActionEvent event){
		try {
			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/AddSubjectView.fxml"));
			Parent root = fxmlLoader.load();
			Stage stage = new Stage();
			stage.setResizable(false);
			stage.setTitle("题目新增");
			stage.setScene(new Scene(root,900,600));
			stage.show();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void configureFileChooser(final FileChooser fileChooser) {
	    fileChooser.setTitle("课程导入");
		fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));                 
		fileChooser.getExtensionFilters().addAll(
			new FileChooser.ExtensionFilter("xlsx", "*.xlsx"),
			new FileChooser.ExtensionFilter("xls", "*.xls")
		);
	}
	
	/**
	 * 课程导入
	 * @param event
	 */
	@FXML
	public void doImportCourseFun(ActionEvent event){
		final FileChooser fileChooser = new FileChooser();
		configureFileChooser(fileChooser);
		final File excelFile = fileChooser.showOpenDialog(GUIState.getStage());
		if (excelFile != null) {
			try {
				List<Course> exsitCourseList = this.courseService.selectCourse(null, LtContext.LOGIN_SCHOOL);
				final Map<String, Object> map = POIUtil.readExcel(excelFile, exsitCourseList);
				if (map.get("errMsg").equals("")) {
					List<Course> addList = (List<Course>)map.get("data");
					//插入数据库
					for (Course c : addList) {
						if (!COURSE_TABLE_DATALIST.contains(c)) {
							COURSE_TABLE_DATALIST.add(c);
							c.setStatus(1);
							c.setStatusName("启用");
							try {
								Integer id = courseService.insertCourse(c);
								c.setId(id);
								
								//新导入的课程关联操作按钮
								c.getOperBtn().setText("关联题型");
								c.getOperBtn().setOnAction(new EventHandler<ActionEvent>() {
									@Override
									public void handle(ActionEvent arg0) {
										try {
											LtContext.CURR_COURSE = c;
											FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/setQuestionType.fxml"));
											Parent root = fxmlLoader.load();
											Stage stage = new Stage();
											stage.setResizable(false);
											stage.setTitle("(" + c.getCode() + ") " + c.getName() + "-关联题型");
											stage.setScene(new Scene(root, 1181, 663));
											//stage.setAlwaysOnTop(true);
											stage.setMaximized(false);
											stage.show();
										} catch (IOException e) {
											e.printStackTrace();
										}
									}
								});
								
								//新导入的课程关联操作按钮
								c.getOperUpdateBtn().setText("修改课程章节");
								c.getOperUpdateBtn().setOnAction(new EventHandler<ActionEvent>() {
									@Override
									public void handle(ActionEvent arg0) {
										try {
											LtContext.CURR_COURSE = c;
											FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/UpdateCourseView.fxml"));
											Parent root = fxmlLoader.load();
											Stage stage = new Stage();
											stage.setResizable(false);
											stage.setTitle("(" + c.getCode() + ") " + c.getName() + "-修改课程章节");
											stage.setScene(new Scene(root, 414,184));
											//stage.setAlwaysOnTop(true);
											stage.setMaximized(false);
											stage.show();
										} catch (IOException e) {
											e.printStackTrace();
										}
									}
								});
							} catch (SQLException e) {
								DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "失败", "插入课程失败" + e.getMessage());
							}
						}
					}
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "成功", "成功导入!");
				} else {
					DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "失败", map.get("errMsg").toString());
				}
			} catch (OldExcelFormatException e) {
				DialogUtil.showAlertDialog(GUIState.getStage(), Alert.AlertType.ERROR, "提示", "当前格式为excel-95，请另存为97-2003格式后再导入!");
			} catch (SQLException e1) {
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.ERROR, "失败", e1.getMessage());
			}
		}
	}
	
	@FXML
	public void doExportCourseFun(ActionEvent event) {
		if (DialogUtil.confirm("是否导出？", GUIState.getStage())) {
			String savePath = System.getProperty("user.dir") + File.separator + "命题课程" + File.separator;
			File fDir = new File(savePath);
			if (!fDir.exists()) {
				fDir.mkdirs();
			}
			POIUtil.writeToXlsx(COURSE_TABLE_DATALIST, savePath + "课程导出.xls");
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "成功", "成功导出.");
		}
	}
	
}
