package com.hmsoft.bizpanel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.poi.hssf.OldExcelFormatException;
import com.alibaba.fastjson.JSON;
import com.hmsoft.app.Manage;
import com.hmsoft.common.AppConst;
import com.hmsoft.common.BatchConst;
import com.hmsoft.common.MsgTypeConst;
import com.hmsoft.common.util.BatchDataUtil;
import com.hmsoft.common.util.CoursePlanDataUtil;
import com.hmsoft.common.util.DialogUtil;
import com.hmsoft.common.util.POIUtil;
import com.hmsoft.common.util.ShoolDateUtil;
import com.hmsoft.common.util.StringHelper;
import com.hmsoft.model.Batch;
import com.hmsoft.model.CoursePlan;
import com.hmsoft.model.School;
import com.hmsoft.model.request.BizRequest;
import com.hmsoft.remote.rmi.common.utils.NamedThreadFactory;
import com.hmsoft.remote.rmi.model.Message;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 * 命题征集
 * @author zq
 *
 */
public class MtzjTab extends Tab {
	public static Button BTN_MANUAL = null;
	public static Button BTN_DELETE = null;
	public static Button BTN_IMP = null;
	public static Button BTN_START = null;
	public static Button BTN_EXPORT = null;
	public static Button BTN_PUBLISH = null;
	public static Button BTN_SPECIFIC = null;
	public static final TableView<CoursePlan> TABLE = new TableView<CoursePlan>();
	public static final ObservableList<CoursePlan> DATALIST = FXCollections.observableArrayList();//base数据集,客户选择后体现这里
	public static final ObservableList<CoursePlan> FILTER_DATALIST = FXCollections.observableArrayList();//查询过滤用
	public static final List<School> SPECIFIC_SCHOOL_MAP = new ArrayList<School>();//命题办指定的学校
	//批次下拉框对象.
	public static final ComboBox<Batch> BATCH_SELECT_BOX = new ComboBox<Batch>();
	//批次下拉框数据源.
	public static final ObservableList<Batch> BATCH_COMBO_DATA_LIST = FXCollections.observableArrayList();
	//定时刷新服务
	private static final ScheduledThreadPoolExecutor SCHEDULE_FRESH_SERVICE = 
			new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("MtzjFreshTimer", true));
	private volatile ScheduledFuture<?> SCHEDULE_FUTRUE = null;
	
	public MtzjTab(final Stage stage) {
		super();
		this.setText("命题征集");
		this.setId("collectTabId");
		this.setClosable(false);
		stage.setResizable(false);
		//Grid
		GridPane gp = new GridPane();
		gp.setPadding(new Insets(20));
		gp.setHgap(5);
		gp.setVgap(5);
		//创建彼此下拉框
		this.createComboBox(gp, stage);
		//创建按钮
		this.createBtn(gp, stage);
		//创建表格
		this.createMtzjTable(gp, stage);
		//grid内容
		this.setContent(gp);
	}
	
	//批次下拉框
	private void createComboBox(final GridPane gp, final Stage stage) {
		//批次号
		BATCH_SELECT_BOX.setPromptText("批次号");
		BATCH_SELECT_BOX.setEditable(false);
		BATCH_COMBO_DATA_LIST.addAll(BatchDataUtil.loadBatchData());
		BATCH_SELECT_BOX.setItems(BATCH_COMBO_DATA_LIST);
		BATCH_SELECT_BOX.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				//加载该批次之前已经导入的课程计划
				DATALIST.clear();
				DATALIST.addAll(CoursePlanDataUtil.loadCoursePlanData(SELECTED_BATCH.getBatchId()));
				TABLE.setItems(DATALIST);
				if (SELECTED_BATCH.getStatus() == BatchConst.STATUS_COLLECTING
						&& SCHEDULE_FUTRUE == null) {
					startSheduleThread(stage);
				}
				if (SELECTED_BATCH.getStatus() == BatchConst.STATUS_NEW) {
					BTN_IMP.setDisable(false);
					BTN_START.setDisable(false);
					BTN_PUBLISH.setDisable(true);
					BTN_SPECIFIC.setDisable(true);
					BTN_MANUAL.setDisable(true);
					BTN_DELETE.setDisable(false);
					BTN_EXPORT.setDisable(true);
				} else if (SELECTED_BATCH.getStatus() == BatchConst.STATUS_IMPORTED) {
					BTN_IMP.setDisable(false);
					BTN_START.setDisable(false);
					BTN_PUBLISH.setDisable(true);
					BTN_SPECIFIC.setDisable(true);
					BTN_MANUAL.setDisable(true);
					BTN_DELETE.setDisable(false);
					BTN_EXPORT.setDisable(true);
				} else if (SELECTED_BATCH.getStatus() == BatchConst.STATUS_COLLECTING) {
					BTN_IMP.setDisable(false);
					BTN_START.setDisable(false);
					BTN_PUBLISH.setDisable(false);
					BTN_SPECIFIC.setDisable(false);
					BTN_MANUAL.setDisable(false);
					if (SystTab.FRSH_MINUTES >=0) {
						BTN_MANUAL.setDisable(true);
					} else {
						BTN_MANUAL.setDisable(false);
					}
					BTN_DELETE.setDisable(false);
					BTN_EXPORT.setDisable(true);
				} else if (SELECTED_BATCH.getStatus() == BatchConst.STATUS_PUBLISHED) {
					BTN_IMP.setDisable(true);
					BTN_START.setDisable(true);
					BTN_PUBLISH.setDisable(true);
					BTN_SPECIFIC.setDisable(true);
					BTN_MANUAL.setDisable(true);
					BTN_DELETE.setDisable(true);
					BTN_EXPORT.setDisable(false);
				}
			}
		});
		//批次下拉框
		gp.add(BATCH_SELECT_BOX, 0, 0);
	}
	
	private void setAllBtnInitDisable() {
		BTN_IMP.setDisable(true);
		BTN_START.setDisable(true);
		BTN_PUBLISH.setDisable(true);
		BTN_SPECIFIC.setDisable(true);
		BTN_MANUAL.setDisable(true);
		BTN_DELETE.setDisable(true);
		BTN_EXPORT.setDisable(true);
	}
	
	private void createBtn(final GridPane gp, final Stage stage) {
		//导入
		BTN_IMP = new Button();
		BTN_IMP.setText("导入征集计划");
		//删除课程
		BTN_DELETE = new Button();
		BTN_DELETE.setText("删除课程");
		//开始征集,刷新服务端列表数据到客户端
		BTN_START = new Button();
		BTN_START.setText("开启征集");
		//手动刷新
		BTN_MANUAL = new Button();
		BTN_MANUAL.setText("手动刷新");
		
		//命题办指定
		BTN_SPECIFIC = new Button();
		BTN_SPECIFIC.setText("指定学校");
		//最终发布
		BTN_PUBLISH = new Button();
		BTN_PUBLISH.setText("最终发布");
		//导出最终结果
		BTN_EXPORT = new Button();
		BTN_EXPORT.setText("导出最终计划");
		BTN_MANUAL.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				if (DialogUtil.confirm("确认刷新？", stage)) {
					pushLastestZjDataFunc(stage);
					//刷新征集下拉框学校显示
					filterZjSelectList();
				}
			}
		});
		//初始化所有按钮disable
		setAllBtnInitDisable();
		Text likeText = new Text(" 模糊匹配：");
		final TextField likeQuery = new TextField();
		likeQuery.setMaxWidth(200);
		FILTER_DATALIST.addAll(DATALIST);
		likeQuery.textProperty().addListener(new ChangeListener<String>() {

			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				FILTER_DATALIST.clear();
				for (CoursePlan cp : DATALIST) {
					if (cp.getCourseCode().indexOf(newValue) != -1 || cp.getCourseName().indexOf(newValue) != -1) {
						FILTER_DATALIST.add(cp);
					}
		        }
				TABLE.setItems(FILTER_DATALIST);
			}
			
		});
		
		//删除课程
		BTN_DELETE.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				deleteCoursePlan(stage);
				
			}
		});
		
		
		//导入
		BTN_IMP.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				impPlanFunc(stage);
			}
		});
		
		//命题办指定学校
		BTN_SPECIFIC.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				if (SELECTED_BATCH == null) {
					DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择批次号!");
					return;
				}
				if (DialogUtil.confirm("是否指定学校？", stage)) {
					specificFunc(stage);
				}
			}
		});
		
		//开启征集
		BTN_START.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				if (SELECTED_BATCH == null) {
					DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择批次号!");
					return;
				}
				if (DialogUtil.confirm("是否开启征集？", stage)) {
					startMtzjFunc(stage);//开启征集
					if (SCHEDULE_FUTRUE == null) {
						startSheduleThread(stage);//定时刷新线程是否开启
					}
				}
			}
		});
		//最终发布
		BTN_PUBLISH.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				if (SELECTED_BATCH == null) {
					DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择批次号!");
					return;
				}
				//只有征集中才能到发布
				if (SELECTED_BATCH.getStatus() == BatchConst.STATUS_COLLECTING) {
					if (DialogUtil.confirm("是否最终发布？", stage)) {
						finalPublishFunc(stage, SELECTED_BATCH);
					}
				}
			}
		});
		//导出最终征集结果
		BTN_EXPORT.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				if (SELECTED_BATCH == null) {
					DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择批次号!");
					return;
				}
				if (DialogUtil.confirm("是否导出？", stage)) {
					FileChooser fileChooser = new FileChooser();
					fileChooser.setTitle("导出");
					fileChooser.setInitialFileName(SELECTED_BATCH.getBatchNo() + ".xls");
					fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("XLS Files", "*.xls"));
					File file = fileChooser.showSaveDialog(stage);
					if(file != null) {
						POIUtil.writeToXlsx(MtzjTab.DATALIST, file.getAbsolutePath());
					}
				}
				
			}
		});
		
		//加入容器
		gp.add(BTN_IMP, 1, 0);
		gp.add(BTN_START, 2, 0);
		gp.add(BTN_MANUAL, 3, 0);
		gp.add(BTN_SPECIFIC, 4, 0);
		gp.add(BTN_DELETE, 5, 0);
		gp.add(BTN_PUBLISH, 6, 0);
		gp.add(BTN_EXPORT, 7, 0);
		gp.add(likeText, 8, 0);
		gp.add(likeQuery, 9, 0);
	}
	
	protected void deleteCoursePlan(final Stage stage) {
		Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
		if (SELECTED_BATCH == null) {
			DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择批次号!");
			return;
		}
		CoursePlan delObj = TABLE.getSelectionModel().getSelectedItem();
		if (delObj == null) {
			DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选课程计划!");
			return;
		}
		if (SELECTED_BATCH.getStatus() != BatchConst.STATUS_IMPORTED &&
				SELECTED_BATCH.getStatus() != BatchConst.STATUS_COLLECTING) {
			DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "只能删除'已导入'和'征集中'计划!");
			return;
		}
		if (DialogUtil.confirm("确认删除课程'" + delObj.getCourseCode() + "'？", stage)) {
			MtzjTab.DATALIST.remove(delObj);
			final List<CoursePlan> delList = new ArrayList<CoursePlan>();
			delList.add(delObj);
			final BizRequest req = new BizRequest();
			req.setReqType(AppConst.SRV_DELETE_COURSE);
			req.setSourceList(delList);
			req.setBatchNo(SELECTED_BATCH.getBatchNo());
			String json = JSON.toJSONString(req);
			final Message msg = new Message(MsgTypeConst.TYPE_BIZ_RESP_TO_CLIENT, json);
			try {
				//IFuture future = 
				Object obj = Manage.CLIENT.requestTwoWay(msg);
				//TODO
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void createMtzjTable(final GridPane gp, final Stage stage) {
		//表格宽度
		TABLE.setMinWidth(stage.getWidth() - 70);
		TABLE.setMinHeight(stage.getHeight() - 170);
		
		//表格列
		final TableColumn<CoursePlan, Integer> coursePlanId = new TableColumn<CoursePlan, Integer>("序号");
		coursePlanId.setCellValueFactory(new PropertyValueFactory<CoursePlan, Integer>("coursePlanId"));
		coursePlanId.setMinWidth(10);
		final TableColumn<CoursePlan, String> courseCode = new TableColumn<CoursePlan, String>("课程代码");
		courseCode.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("courseCode"));
		courseCode.setMinWidth(30);
		final TableColumn<CoursePlan, String> courseName = new TableColumn<CoursePlan, String>("课程名称");
		courseName.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("courseName"));
		courseName.setMinWidth(30);
		final TableColumn<CoursePlan, String> outlineName = new TableColumn<CoursePlan, String>("课程大纲");
		outlineName.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("outlineName"));
		outlineName.setMinWidth(60);
		final TableColumn<CoursePlan, String> bookName = new TableColumn<CoursePlan, String>("教材名称");
		bookName.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("bookName"));
		bookName.setMinWidth(50);
		final TableColumn<CoursePlan, String> bianZhu = new TableColumn<CoursePlan, String>("编著");
		bianZhu.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("bianZhu"));
		bianZhu.setMinWidth(30);
		final TableColumn<CoursePlan, String> press = new TableColumn<CoursePlan, String>("出版社");
		press.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("press"));
		press.setMinWidth(30);
		final TableColumn<CoursePlan, String> publications = new TableColumn<CoursePlan, String>("版次");
		publications.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("publications"));
		publications.setMinWidth(30);
		final TableColumn<CoursePlan, String> cengci = new TableColumn<CoursePlan, String>("层次");
		cengci.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("cengci"));
		cengci.setMinWidth(30);
		//学校选择的课程IDs
		final TableColumn<CoursePlan, String> schSelectIds = new TableColumn<CoursePlan, String>("选择课程ID");
		schSelectIds.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("schSelectIds"));
		schSelectIds.setVisible(false);
		final TableColumn<CoursePlan, String> schSelectNames = new TableColumn<CoursePlan, String>("选择该课程学校");
		schSelectNames.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("schSelectNames"));
		schSelectNames.setMinWidth(120);
		//该课程最后被学校选择的时间
		final TableColumn<CoursePlan, String> schSelectTime = new TableColumn<CoursePlan, String>("选择时间");
		schSelectTime.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("schSelectTime"));
		schSelectTime.setMinWidth(120);
		//命题办指定的学校ID
		final TableColumn<CoursePlan, String> specificId = new TableColumn<CoursePlan, String>("命题办指定ID");
		specificId.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("schoolId"));
		specificId.setMinWidth(200);
		specificId.setVisible(false);
		
		final TableColumn<CoursePlan, ComboBox<School>> comboBoxCol = new TableColumn<CoursePlan, ComboBox<School>>("命题办指定学校");
		comboBoxCol.setCellValueFactory(new PropertyValueFactory<CoursePlan, ComboBox<School>>("comboBox"));
		comboBoxCol.setMinWidth(250);
		
		//最终认定学校
//		final TableColumn<CoursePlan, String> affirmSchoole = new TableColumn<CoursePlan, String>("最终认定学校");
//		affirmSchoole.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("affirmSchooleName"));
//		affirmSchoole.setMinWidth(150);
	//	affirmSchoole.setVisible(false);
		
		final TableColumn<CoursePlan, String> confirmDescCol = new TableColumn<CoursePlan, String>("是否已确认");
		confirmDescCol.setCellValueFactory(new PropertyValueFactory<CoursePlan, String>("confirmDesc"));
		confirmDescCol.setMinWidth(90);
		
		
		TABLE.setItems(DATALIST);
		TABLE.getColumns().addAll(coursePlanId, courseCode, courseName, outlineName, bookName, 
				bianZhu, press, publications, cengci, schSelectIds, schSelectNames, schSelectTime, specificId, comboBoxCol, //affirmSchoole,
				confirmDescCol);
		
		final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(TABLE);
        
        gp.add(vbox, 0, 1, 10, 1);
	}
	
	//导入征集计划
	private void impPlanFunc(final Stage stage) {
		Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
		if (SELECTED_BATCH == null) {
			DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择批次号!");
			return;
		}
		final FileChooser fileChooser = new FileChooser();
		configureFileChooser(fileChooser);
		final File excelFile = fileChooser.showOpenDialog(stage);
		if (excelFile != null) {
			try {
				//解析excel文件并导入.
				final Map<String, Object> map = POIUtil.readExcel(excelFile);
				if (map.get("errMsg").equals("")) {
					List<CoursePlan> coursePlanList = (List<CoursePlan>)map.get("data");
					final List<School> schoolList = ShoolDateUtil.loadSchoolData();
					for (CoursePlan course : coursePlanList) {
						course.getComboBox().getItems().addAll(schoolList);
					}
					DATALIST.clear();
					DATALIST.addAll(coursePlanList);
					//save to file
					CoursePlanDataUtil.writeCoursePlan(coursePlanList, SELECTED_BATCH.getBatchId());
					//update batch status
					BatchDataUtil.updateBatchStatus(SELECTED_BATCH.getBatchId(), BatchConst.STATUS_IMPORTED);
					//更新下拉框显示-下拉框显示
					updateComboShow(Integer.valueOf(BatchConst.STATUS_IMPORTED));
					//提示
			        DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "成功", "成功导入征集计划.");
				} else {
					//显示导入报错信息.
					//TODO ...
				}
			} catch (OldExcelFormatException e) {
				DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "当前格式为excel-95，请另存为97-2003格式后再导入!");
			}
        }
	}
	
	private void configureFileChooser(final FileChooser fileChooser) {
		    fileChooser.setTitle("选择征集计划.");
		fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));                 
		fileChooser.getExtensionFilters().addAll(
			new FileChooser.ExtensionFilter("xls", "*.xls"),
		    new FileChooser.ExtensionFilter("xlsx", "*.xlsx")
		  
		);
	}
	
	//提交命题办干预-指定的学校,学校收到不能改
	private void specificFunc(final Stage stage) {
		final BizRequest req = new BizRequest();
		req.setReqType(AppConst.SRV_SPECIFIC_COURSE);
		final List<CoursePlan> specificList = new ArrayList<CoursePlan>();
		for (CoursePlan courseplan : DATALIST) {
			School specificSchool = courseplan.getComboBox().getSelectionModel().getSelectedItem();
			if (specificSchool != null) {//命题办指定了学校,貌似初始值为0
				courseplan.setSchoolId(specificSchool.getSchoolId());
				courseplan.setSchoolName(specificSchool.getSchoolName());
				specificList.add(courseplan);
			}
		}
		if (specificList.size() == 0) {
			DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择学校!");
			return;
		}
		req.setSourceList(specificList);
		String json = JSON.toJSONString(req);
		Message msg = new Message(MsgTypeConst.TYPE_BIZ_RESP_TO_CLIENT, json);
		try {
			//IFuture future = 
			Object obj = Manage.CLIENT.requestTwoWay(msg);
			if (obj != null) {
				//提示
		        DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "成功", "成功指定学校.");
			}
		} catch (Exception e) {
			e.printStackTrace();
			//TODO
		}
	}
	
	//发送数据到客户端.
	private void startMtzjFunc(Stage stage) {
		final BizRequest req = new BizRequest();
		req.setZjStatus(BatchConst.STATUS_COLLECTING);
		req.setReqType(AppConst.SRV_FRESH_INIT_LIST);
		req.setSourceList(DATALIST);
		String json = JSON.toJSONString(req);
		Message msg = new Message(MsgTypeConst.TYPE_BIZ_RESP_TO_CLIENT, json);
		try {
			//IFuture future = 
			Object retObj = Manage.CLIENT.requestTwoWay(msg);
			if (retObj.toString().equals("0")) {
				//update batch status
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				BatchDataUtil.updateBatchStatus(SELECTED_BATCH.getBatchId(), BatchConst.STATUS_COLLECTING);
				//更新下拉框显示-下拉框显示
				updateComboShow(Integer.valueOf(BatchConst.STATUS_COLLECTING));
				DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "成功", "已开启征集.");
			} else {
				//失败了，有客户端没有收到!
				DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "部分失败", "有客户端没有收到征集!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//定时刷新线程
	private void startSheduleThread(final Stage stage) {
		if (SystTab.FRSH_MINUTES > 0) {
			Runnable command = new Runnable() {

				@Override
				public void run() {
					try {
						pushLastestZjDataFunc(stage);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
			};
			int firstDelay = SystTab.FRSH_MINUTES;
			SCHEDULE_FUTRUE = SCHEDULE_FRESH_SERVICE.scheduleAtFixedRate(command, firstDelay, SystTab.FRSH_MINUTES, TimeUnit.SECONDS);
		}
	}
	
	//推送最新选择情况到学校
	private void pushLastestZjDataFunc(final Stage stage) {
		final List<CoursePlan> notifyList = new ArrayList<CoursePlan>();
		for (CoursePlan courseplan : DATALIST) {
			if (courseplan.getSchSelectIds() != null && courseplan.getSchSelectIds().length() > 0) {
				final CoursePlan cp = new CoursePlan();
				cp.setCoursePlanId(courseplan.getCoursePlanId());
				cp.setSchSelectIds(courseplan.getSchSelectIds());
				notifyList.add(cp);
			}
		}
		if (notifyList.size() > 0) {
			final BizRequest req = new BizRequest();
			req.setReqType(AppConst.SRV_TRIGGER_FRESH);
			req.setSourceList(notifyList);
			String json = JSON.toJSONString(req);
			final Message msg = new Message(MsgTypeConst.TYPE_BIZ_RESP_TO_CLIENT, json);
			try {
				//IFuture future = 
				//Manage.CLIENT.requestToClient(msg).get();
				Object obj = Manage.CLIENT.requestTwoWay(msg);
				if (obj != null) {
					DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "成功", "成功刷新客户端.");
				}
			} catch (Exception e) {
				e.printStackTrace();
				//TODO...
			}
		}
	}
	
	//刷新后把征集下拉框中学校过滤显示
	private void filterZjSelectList() {
		for (CoursePlan cp : DATALIST) {
			if (StringHelper.isNotEmpty(cp.getSchSelectIds())) {
				cp.getComboBox().getItems().clear();
				cp.getComboBox().getItems().addAll(cp.getMultiSelectList());
			}
		}
		TABLE.refresh();
	}
	
	//最终发布
	private void finalPublishFunc(Stage stage, Batch selectBatch) {
		for (CoursePlan courseplan : DATALIST) {
			if (courseplan.getComboBox().getSelectionModel().getSelectedItem() == null
					&& courseplan.getSchSelectIds() == null) {//命题办指定了学校,貌似初始值为0
				DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "提示", 
						"课程代码:" + courseplan.getCourseCode() + " 征集学校为空,请确认!");
				return;
			}
			//存在多个学校选择情况
			if (courseplan.getSchSelectIds() != null && courseplan.getSchSelectIds().contains("|")
					&& courseplan.getComboBox().getSelectionModel().getSelectedItem() == null) {
				DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "提示", 
						"课程代码:" + courseplan.getCourseCode() + " 需指定学校!");
				return;
			}
		}
		final BizRequest req = new BizRequest();
		req.setReqType(AppConst.SRV_FINAL_PUBLISH);
		req.setSourceList(DATALIST);
		req.setBatchNo(selectBatch.getBatchNo());
		String json = JSON.toJSONString(req);
		final Message msg = new Message(MsgTypeConst.TYPE_BIZ_RESP_TO_CLIENT, json);
		try {
			//IFuture future = 
			Object obj = Manage.CLIENT.requestTwoWay(msg);
			if (obj != null && obj.toString().equals("0")) {
				//修改服务端数据库文件
				for (CoursePlan courseplan : DATALIST) {
					School specificSchool = courseplan.getComboBox().getSelectionModel().getSelectedItem();
					if (specificSchool != null) {
						courseplan.setSchoolId(specificSchool.getSchoolId());
						courseplan.setSchoolName(specificSchool.getSchoolName());
					}
				}
				//修改批次为已发布
				//save to file
				Batch SELECTED_BATCH = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
				CoursePlanDataUtil.updateCoursePlan(DATALIST, SELECTED_BATCH.getBatchId());
				//更新批次文件
				BatchDataUtil.updateBatchStatus(SELECTED_BATCH.getBatchId(), BatchConst.STATUS_PUBLISHED);
				//更新下拉框显示-下拉框
				updateComboShow(Integer.valueOf(BatchConst.STATUS_PUBLISHED));
				//停止刷新
				destroyScheduleFreshCommand();
				//提示
				DialogUtil.showAlertDialog(stage, Alert.AlertType.INFORMATION, "成功", "成功发布计划.");
				disablePubBtn();
			}
		} catch (Exception e) {
			e.printStackTrace();
			//TODO
		}
	}
	//发布后修改按钮状态
	private void disablePubBtn() {
		//其他按钮disable
		BTN_IMP.setDisable(true);
		BTN_PUBLISH.setDisable(true);
		BTN_START.setDisable(true);
		BTN_SPECIFIC.setDisable(true);
		BTN_MANUAL.setDisable(true);
		BTN_DELETE.setDisable(true);
		BTN_EXPORT.setDisable(false);
	}
	
    private synchronized void destroyScheduleFreshCommand() {
        try {
            if (SCHEDULE_FUTRUE != null && !SCHEDULE_FUTRUE.isDone()) {
            	SCHEDULE_FUTRUE.cancel(true);
            	SCHEDULE_FRESH_SERVICE.purge();
            	SCHEDULE_FUTRUE = null;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
	
	private void updateComboShow(final Integer status) {
		int oldSelectIdx = BATCH_SELECT_BOX.getSelectionModel().getSelectedIndex();
		Batch oldSelect = BATCH_SELECT_BOX.getSelectionModel().getSelectedItem();
		oldSelect.setStatus(status);
		oldSelect.setStatusDes(BatchDataUtil.getStatusCaption(status.byteValue()));
		BATCH_COMBO_DATA_LIST.remove(oldSelectIdx);
		BATCH_COMBO_DATA_LIST.add(oldSelect);
		BATCH_SELECT_BOX.getSelectionModel().select(oldSelect);
		//修改批次列表状态显示
		for (Batch ba : BatchTab.DATALIST) {
			if (ba.getBatchId().longValue() == oldSelect.getBatchId().longValue()) {
				ba.setStatus(status);
				ba.setStatusDes(oldSelect.getStatusDes());
				break;
			}
		}
		BatchTab.TABLE.refresh();
	}
	
	/**
	 * 新增学校后改变征集列表的 学校下拉框.
	 * @param school
	 */
	public static void addSchoolToListCombo(final School school) {
		for (CoursePlan courseplan : DATALIST) {
			courseplan.getComboBox().getItems().add(school);
		}
	}
	
	/**
	 * 删除学校后改变征集列表的 学校下拉框.
	 * @param school
	 */
	public static void delSchoolToListCombo(final School school) {
		for (CoursePlan courseplan : DATALIST) {
			courseplan.getComboBox().getItems().remove(school);
		}
	}
}
