package com.hmsoft.bizpanel;

import java.util.Optional;
import com.hmsoft.common.util.DialogUtil;
import com.hmsoft.common.util.ShoolDateUtil;
import com.hmsoft.model.School;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
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.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
 * 
 * @author zq
 *
 */
public class SchoolTab extends Tab {

	private Button btnAdd;
	private Button btnDelete;
	public static final TableView<School> SCH_TABLE = new TableView<School>();
	public static final ObservableList<School> DATALIST = FXCollections.observableArrayList();
	
	public SchoolTab(final Stage stage) {
		super();
		this.setText("学校维护");
		this.setId("schoolTab");
		this.setClosable(false);
		
		//Grid容器
		GridPane gp = new GridPane();
		gp.setPadding(new Insets(20));
		gp.setHgap(5);
		gp.setVgap(5);
		
		//创建按钮
		this.createBtn(stage, gp);
		//创建表格
		this.createSchoolTable(gp, stage);
		//grid布局加到容器
		this.setContent(gp);
	}
	
	private void createBtn(final Stage stage, final GridPane gp) {
		//按钮
		btnAdd = new Button();
		btnAdd.setText("添加学校");
		
		btnDelete = new Button();
		btnDelete.setText("删除学校");
		
		Button btnPassReset = new Button();
		btnPassReset.setText("密码重置");
	
		btnAdd.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				btnAdd.setDisable(true);
				showCreateWin();
			}
		});
		
		btnDelete.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				deleteSchoolFunc(stage);
			}
		});
		
		btnPassReset.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				resetPassFunc(stage, "123456");
			}
		});
		
		gp.add(btnAdd, 0, 0);
		gp.add(btnDelete, 1, 0);
		gp.add(btnPassReset, 2, 0);
	}
	
	@SuppressWarnings("unchecked")
	private void createSchoolTable(final GridPane gp, final Stage stage) {
		//设置表格整体宽度
		SCH_TABLE.setMinWidth(stage.getWidth() - 70);
		SCH_TABLE.setMinHeight(stage.getHeight() - 170);
		//表格列
		final TableColumn<School, Integer> idCol = new TableColumn<School, Integer>("序号");
		idCol.setCellValueFactory(new PropertyValueFactory<School, Integer>("id"));
		idCol.setMinWidth(30);
		final TableColumn<School, Integer> schoolIdCol = new TableColumn<School, Integer>("学校序号");
		schoolIdCol.setCellValueFactory(new PropertyValueFactory<School, Integer>("schoolId"));
		schoolIdCol.setMinWidth(30);
		final TableColumn<School, String> schoolNameCol = new TableColumn<School, String>("学校名称");
		schoolNameCol.setCellValueFactory(new PropertyValueFactory<School, String>("schoolName"));
		schoolNameCol.setMinWidth(200);
		final TableColumn<School, String> userNameCol = new TableColumn<School, String>("登录账号");
		userNameCol.setCellValueFactory(new PropertyValueFactory<School, String>("userName"));
		userNameCol.setMinWidth(150);
		final TableColumn<School, String> statusCol = new TableColumn<School, String>("连接状态");
		statusCol.setCellValueFactory(new PropertyValueFactory<School, String>("statusDesc"));
		statusCol.setMinWidth(150);
		final TableColumn<School, String> connectedTimeCol = new TableColumn<School, String>("开始连接时间");
		connectedTimeCol.setCellValueFactory(new PropertyValueFactory<School, String>("connectedTime"));
		connectedTimeCol.setMinWidth(150);
		final TableColumn<School, String> disconnectTimeCol = new TableColumn<School, String>("断开时间");
		disconnectTimeCol.setCellValueFactory(new PropertyValueFactory<School, String>("disconnectTime"));
		disconnectTimeCol.setMinWidth(150);
		//添加列到表格
		SCH_TABLE.getColumns().addAll(idCol,schoolIdCol, schoolNameCol, userNameCol, statusCol, connectedTimeCol, disconnectTimeCol);
		DATALIST.addAll(ShoolDateUtil.loadSchoolData());
		SCH_TABLE.setItems(DATALIST);
		//添加显示表格
		final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(SCH_TABLE);
        
        gp.add(vbox, 0, 1, 3, 1);
	}
	
	/**
	 * 弹出新建窗口.
	 */
	private void showCreateWin() {
		final Stage addStage = new Stage();
		addStage.setTitle("添加学校");
		final GridPane grid = new GridPane();
		grid.setAlignment(Pos.CENTER);
		grid.setHgap(10);
		grid.setVgap(10);
		grid.setPadding(new Insets(50));
		
		//学校名称框
		Label schoolName = new Label("学校名称: ");
		grid.add(schoolName, 0, 1);
		final TextField schoolNameField = new TextField();
		grid.add(schoolNameField, 1, 1);
		//登录账号框
		Label schoolActNo = new Label("登录账号:");
		grid.add(schoolActNo, 0, 2);
		final TextField schoolActNoField = new TextField();
		grid.add(schoolActNoField, 1, 2);
		//登录密码
		Label schoolActPassWord = new Label("登录密码:");
		grid.add(schoolActPassWord, 0, 3);
		final TextField schoolActPassWordField = new TextField();
		schoolActPassWordField.setOnKeyPressed(new EventHandler<KeyEvent>() {
			@Override
			public void handle(KeyEvent event) {
				if (event.getCode() == KeyCode.ENTER) {
					createSchoolFunc(addStage, schoolNameField, schoolActNoField, schoolActPassWordField);
				}
			}
		});
		grid.add(schoolActPassWordField, 1, 3);
		
		final HBox hbBtn = new HBox(10);
		grid.add(hbBtn, 1, 4);
		
		Button btnSave = new Button("保存");
		Button btncancel = new Button("取消");
		hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
		hbBtn.getChildren().add(btnSave);
		hbBtn.getChildren().add(btncancel);
		
		//新建窗口退出事件
		addStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
			@Override
			public void handle(WindowEvent event) {
				btnAdd.setDisable(false);
			}
		});
		
		btnSave.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				createSchoolFunc(addStage, schoolNameField, schoolActNoField, schoolActPassWordField);
			}
		});
		
		btncancel.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				btnAdd.setDisable(false);
				addStage.close();
			}
		});
		
		Scene scene = new Scene(grid, 400, 220);
		addStage.setScene(scene);
		addStage.setResizable(false);
		addStage.alwaysOnTopProperty();
		addStage.show();
	}
	
	/**
	 * 删除批次.
	 */
	private void deleteSchoolFunc(Stage stage) {
		School selected = SCH_TABLE.getSelectionModel().getSelectedItem();
		if (selected == null) {
			DialogUtil.showAlertDialog(stage, Alert.AlertType.WARNING, "提示", "请选择学校!");
			return;
		}
		Alert confirm = new Alert(Alert.AlertType.CONFIRMATION,
				"", 
				new ButtonType("否", ButtonData.NO),
                new ButtonType("是", ButtonData.YES));
		confirm.setTitle("请确认");
		confirm.setHeaderText("是否删除？");
		confirm.initOwner(stage);
		Optional<ButtonType> btnType = confirm.showAndWait();
		if (btnType.get().getButtonData().equals(ButtonData.YES)) {
			ShoolDateUtil.deleteSchool(selected.getSchoolId());
			DATALIST.remove(selected);//列表删除
			//删除征集列表 学校下拉框对应学校
			MtzjTab.delSchoolToListCombo(selected);
		}
	}
	
	private void createSchoolFunc(final Stage addStage, final TextField schoolNameField, 
			final TextField schoolActNoField, final TextField schoolActPassWordField) {
		try {
			for (School school : DATALIST) {
				if (school.getSchoolName().equals(schoolNameField.getText())) {
					DialogUtil.showAlertDialog(addStage, Alert.AlertType.WARNING, "提示", "学校名称不能重复!");
					return;
				}
				if (school.getUserName().equals(schoolActNoField.getText())) {
					DialogUtil.showAlertDialog(addStage, Alert.AlertType.WARNING, "提示", "学校登录账号不能重复!");
					return;
				}
			}
			final School school = new School();
			school.setSchoolId(System.currentTimeMillis());
			school.setSchoolName(schoolNameField.getText());
			school.setUserName(schoolActNoField.getText());
			school.setPassWord(schoolActPassWordField.getText());
			ShoolDateUtil.insertSchool(school);
			DATALIST.add(school);
			//修改征集列表 学校下拉框
			MtzjTab.addSchoolToListCombo(school);
		} catch(Exception e) {
			e.printStackTrace();
		}
		addStage.close();
		btnAdd.setDisable(false);
	}
	
	private void resetPassFunc(final Stage addStage, final String passwd) {
		School school = SCH_TABLE.getSelectionModel().getSelectedItem();
		if (school == null) {
			DialogUtil.showAlertDialog(addStage, Alert.AlertType.WARNING, "提示", "请选择学校!");
			return;
		}
		if (DialogUtil.confirm("确认重置？", addStage)) {
			ShoolDateUtil.resetPasswd(school.getSchoolId(), passwd);
			changeTablePasswdData(school.getSchoolId(), passwd);
			DialogUtil.showAlertDialog(addStage, Alert.AlertType.INFORMATION, "成功", "密码已重置.");
		}
	}
	
	public static void changeTablePasswdData(long schId, String passwd) {
		for (School sch : SchoolTab.DATALIST) {
			if (sch.getSchoolId().longValue() == schId) {
				sch.setPassWord(passwd);
				break;
			}
		}
	}
}
