package cn.hmsoft.ltc.controller;

import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
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.POIUtil;
import cn.hmsoft.ltc.common.util.StageManager;
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.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.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 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.AlertType;
import javafx.scene.control.Button;
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.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * 预估难度控制器
 * @author zq
 *
 */
@FXMLController
public class EstimatedDifficultyController implements Initializable {
	@FXML
	public Button wordBtn;
  	//预计难度
  	@FXML
  	public ComboBox<String> subjectDifficultSelectBox;

  	@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> 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;//备注

	
	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(EstimatedDifficultyController.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("请选择");

		
	}
	
	/**
	 * 题目查询
	 */
	@FXML
	public void doQuerySubjectFun(ActionEvent event){
		TestPaper paper = LtContext.CURR_PAPER;
		QuestionType questionType = subjectQuestionTypeSelectBox.getValue();
		String difficult = subjectDifficultSelectBox.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);
		}
		try {
			subjectTableView.getItems().clear();
			subjectColId.setCellValueFactory(new PropertyValueFactory<Subject, Integer>("id"));
			subjectColCourse.setCellValueFactory(new PropertyValueFactory<Subject, Integer>("courseId"));
			index.setCellValueFactory(new PropertyValueFactory<Subject, Integer>("ord"));
			subjectColQuestionTypeName.setCellValueFactory(new PropertyValueFactory<Subject, String>("questionTypeName"));
			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"));
			SUBJECT_DATALIST.addAll(this.subjectService.selectEstimatedDifficulty(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
	 */
	@FXML
	public void exportPaperEstimatedFun(ActionEvent event) {
		TestPaper paper = LtContext.CURR_PAPER;
		//查询试卷细目表信息
		List<DetailTable> tableList = null;
		try {
			tableList = detailTableService.selectDetailTable(paper.getPaperNo());
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (paper == null || tableList.size()==0) {
			DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "提示", "试卷未编辑结构细目表！");
		} else {
			if (DialogUtil.confirm("是否导出？", GUIState.getStage())) {
				
				String savePath =System.getProperty("user.dir") + File.separator + "papers" + File.separator;
				//String savePath = System.getProperty("user.dir") + File.separator + "命题课程" + File.separator;
				File fDir = new File(savePath);
				if (!fDir.exists()) {
					fDir.mkdirs();
				}
				POIUtil.exportPaperEstimatedToXlsx(SUBJECT_DATALIST, savePath +paper.getPaperNo()+ ".xls");
				DialogUtil.showAlertDialog(GUIState.getStage(), AlertType.INFORMATION, "成功", "成功导出.");
			}
		}
		
		
	}
	
	/**
	 * 编辑题目窗口
	 * @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);
			}
		}
	}
	

}
