package com.ht.ui.user;

import java.util.HashMap;
import java.util.Map;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.util.Duration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ht.ui.MainApplication;
import com.ht.ui.util.MessageConstants;
import com.ht.util.UserSession;
import com.ht.web.hessian.HessianFactoryManger;
import com.ht.web.mongo.domain.User;
import com.ht.web.remoting.HessianResponse;

public class UserInfoEditor extends VBox {

	private static final Logger log = LoggerFactory
			.getLogger(UserInfoEditor.class);

	// private RedoUndoManager redoUndoManager;
	// private Button undoButton;
	// private Button redoButton;

	private TextField usernameValue;
	private TextField nameValue;
	private ComboBox<String> genderValue;
	private TextField departmentValue;
	private TextField emailValue;
	private TextField telphoneValue;
	private TextField addressValue;
	private TextField userGroupValue;

	private Label message;
	private Timeline messageAnimate;

	private PasswordField oldPasswordText;

	private PasswordField newPasswordText;

	private PasswordField renewPasswordText;

	private GridPane passwordGridPane;

	private Runnable savePasswordRun = new Runnable() {
		public void run() {
			try {
				HessianResponse resp = HessianFactoryManger.INSTANCE
						.getUserService().changePassword(
								oldPasswordText.getText().trim(),
								newPasswordText.getText().trim());
				if (resp.isSuccessful()) {
					passwordGridPane.setVisible(false);
					oldPasswordText.clear();
					newPasswordText.clear();
					renewPasswordText.clear();
					showMessage(resp.getMsg());
				} else {
					UserLoginDialog.getInstance().showDialog(null, resp.getMsg());
				}
			} catch (Exception e) {
				showMessage(MessageConstants.ERROR_SERVER_ERROR);
			}
		}
	};

	public UserInfoEditor() {
		super(20);
		setStyle("-fx-padding: 0px 20;");

		// 基本信息面板
		createBaseInfoPane();
		// 修改密码
		createPasswordPane();

		// 底部按钮
		createBottomButton();
	}

	private void createPasswordPane() {

		VBox vbox = new VBox(10);

		HBox hb1 = new HBox(5);

		Button passwordButton = new Button("修改密码");
		passwordButton.setStyle("-fx-base: orange;");
		passwordButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				passwordGridPane.setVisible(true);
			}
		});

		Button changeUserButton = new Button("切换用户");
		changeUserButton.setStyle("-fx-base: lightgreen;");
		changeUserButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {

				HessianFactoryManger.INSTANCE.getUserService().logout();
				UserLoginDialog.getInstance().showDialog(null);
			}
		});

		Button logoutButton = new Button("用户退出");
		logoutButton.setStyle("-fx-base: lightgreen;");
		logoutButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				HessianFactoryManger.INSTANCE.getUserService().logout();
				MainApplication.getMainApp().showDefaultView();
				MainApplication.getMainApp().showMessage("您已安全退出");
			}
		});

		hb1.getChildren()
				.addAll(passwordButton, changeUserButton, logoutButton);
		vbox.getChildren().add(hb1);

		createPasswordPanel();

		vbox.getChildren().add(passwordGridPane);

		getChildren().add(vbox);
	}

	private void createPasswordPanel() {
		passwordGridPane = new GridPane();
		passwordGridPane.setHgap(6);
		passwordGridPane.setVgap(10);
		passwordGridPane.setVisible(false);

		// GridPane.setConstraints(button, 0, 0);
		// GridPane.setHalignment(button, HPos.LEFT);
		// gridPane.getChildren().add(button);

		Label oldPasswordLabel = new Label("旧密码:");
		GridPane.setConstraints(oldPasswordLabel, 0, 0);
		GridPane.setHalignment(oldPasswordLabel, HPos.RIGHT);
		passwordGridPane.getChildren().add(oldPasswordLabel);

		oldPasswordText = new PasswordField();
		oldPasswordText.setPromptText("请输入旧密码");
		oldPasswordText.setMinWidth(150);
		GridPane.setConstraints(oldPasswordText, 1, 0);
		GridPane.setHalignment(oldPasswordText, HPos.LEFT);
		passwordGridPane.getChildren().add(oldPasswordText);

		Label newPasswordLabel = new Label("新密码:");
		GridPane.setConstraints(newPasswordLabel, 0, 1);
		GridPane.setHalignment(newPasswordLabel, HPos.RIGHT);
		passwordGridPane.getChildren().add(newPasswordLabel);

		newPasswordText = new PasswordField();
		newPasswordText.setPromptText("请输入新密码");
		newPasswordText.setMinWidth(150);
		GridPane.setConstraints(newPasswordText, 1, 1);
		GridPane.setHalignment(newPasswordText, HPos.LEFT);
		passwordGridPane.getChildren().add(newPasswordText);

		Label renewPasswordLabel = new Label("新密码确认:");
		GridPane.setConstraints(renewPasswordLabel, 0, 2);
		GridPane.setHalignment(renewPasswordLabel, HPos.RIGHT);
		passwordGridPane.getChildren().add(renewPasswordLabel);

		renewPasswordText = new PasswordField();
		renewPasswordText.setPromptText("请再次输入新密码");
		renewPasswordText.setMinWidth(150);
		GridPane.setConstraints(renewPasswordText, 1, 2);
		GridPane.setHalignment(renewPasswordText, HPos.LEFT);
		passwordGridPane.getChildren().add(renewPasswordText);

		HBox hb = new HBox(10);
		hb.setAlignment(Pos.CENTER);

		Button okButton = new Button("确定");
		okButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				// 保存密码
				if (newPasswordText.getText().trim().isEmpty()
						|| newPasswordText.getText().trim().isEmpty()
						|| renewPasswordText.getText().trim().isEmpty()) {
					showMessage("输入项不允许为空，请重新输入");
				} else if (!newPasswordText.getText().trim()
						.equals(renewPasswordText.getText().trim())) {
					showMessage("两次输入的密码不一致，请重新输入");
				} else {

					if (UserSession.INSTANCE.getUser() == null) {

						UserLoginDialog.getInstance().showDialog(null,
								"您已自动退出,请重新登录.");
					} else {
						savePasswordRun.run();
					}

				}
			}
		});
		Button cancelButton = new Button("取消");
		cancelButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				passwordGridPane.setVisible(false);
				oldPasswordText.clear();
				newPasswordText.clear();
				renewPasswordText.clear();
			}
		});

		hb.getChildren().addAll(okButton, cancelButton);

		GridPane.setConstraints(hb, 0, 3, 4, 1);
		GridPane.setHalignment(hb, HPos.CENTER);
		passwordGridPane.getChildren().add(hb);
	}

	private void createBaseInfoPane() {
		GridPane gridPane = new GridPane();
		gridPane.setHgap(6);
		gridPane.setVgap(10);

		Label usernameLabel = new Label("用户名:");
		GridPane.setConstraints(usernameLabel, 0, 0);
		GridPane.setHalignment(usernameLabel, HPos.RIGHT);
		gridPane.getChildren().add(usernameLabel);

		usernameValue = new TextField();
		usernameValue.setDisable(true);
		usernameValue.textProperty().bind(UserSession.INSTANCE.usernameProperty());
		GridPane.setConstraints(usernameValue, 1, 0);
		GridPane.setHalignment(usernameValue, HPos.LEFT);
		gridPane.getChildren().add(usernameValue);

		Label nameLabel = new Label("姓名:");
		GridPane.setConstraints(nameLabel, 2, 0);
		GridPane.setHalignment(nameLabel, HPos.RIGHT);
		gridPane.getChildren().add(nameLabel);

		nameValue = new TextField();
		nameValue.setMaxWidth(120);
		nameValue.textProperty().bindBidirectional(UserSession.INSTANCE.nameProperty());
		GridPane.setConstraints(nameValue, 3, 0);
		GridPane.setHalignment(nameValue, HPos.LEFT);
		gridPane.getChildren().add(nameValue);

		Label genderLabel = new Label("性别:");
		GridPane.setConstraints(genderLabel, 4, 0);
		GridPane.setHalignment(genderLabel, HPos.RIGHT);
		gridPane.getChildren().add(genderLabel);

		genderValue = new ComboBox<String>(FXCollections.observableArrayList("男", "女"));
		genderValue.getSelectionModel().select(UserSession.INSTANCE.genderProperty().getValue());
		UserSession.INSTANCE.genderProperty().bindBidirectional(genderValue.valueProperty());
		//genderValue.valueProperty().bind(UserSession.INSTANCE.genderProperty());
		
		// genderValue.getSelectionModel().selectFirst();
		GridPane.setConstraints(genderValue, 5, 0);
		GridPane.setHalignment(genderValue, HPos.LEFT);
		gridPane.getChildren().add(genderValue);

		Label departmentLabel = new Label("部门:");
		GridPane.setConstraints(departmentLabel, 6, 0);
		GridPane.setHalignment(departmentLabel, HPos.RIGHT);
		gridPane.getChildren().add(departmentLabel);

		departmentValue = new TextField();
		departmentValue.textProperty().bindBidirectional(UserSession.INSTANCE.departmentProperty());
		// departmentValue.setMaxWidth(100);
		GridPane.setConstraints(departmentValue, 7, 0);
		GridPane.setHalignment(departmentValue, HPos.LEFT);
		gridPane.getChildren().add(departmentValue);

		Label emailLabel = new Label("Email:");
		GridPane.setConstraints(emailLabel, 0, 1);
		GridPane.setHalignment(emailLabel, HPos.RIGHT);
		gridPane.getChildren().add(emailLabel);

		emailValue = new TextField();
		emailValue.setMinWidth(150);
		emailValue.textProperty().bindBidirectional(UserSession.INSTANCE.emailProperty());
		GridPane.setConstraints(emailValue, 1, 1);
		GridPane.setHalignment(emailValue, HPos.LEFT);
		gridPane.getChildren().add(emailValue);

		Label telPhoneLabel = new Label("电话:");
		GridPane.setConstraints(telPhoneLabel, 2, 1);
		GridPane.setHalignment(telPhoneLabel, HPos.RIGHT);
		gridPane.getChildren().add(telPhoneLabel);

		telphoneValue = new TextField();
		telphoneValue.setMaxWidth(120);
		telphoneValue.textProperty().bindBidirectional(UserSession.INSTANCE.telphoneProperty());
		GridPane.setConstraints(telphoneValue, 3, 1);
		GridPane.setHalignment(telphoneValue, HPos.LEFT);
		gridPane.getChildren().add(telphoneValue);

		Label addressLabel = new Label("地址:");
		GridPane.setConstraints(addressLabel, 4, 1);
		GridPane.setHalignment(addressLabel, HPos.RIGHT);
		gridPane.getChildren().add(addressLabel);

		addressValue = new TextField();
		addressValue.setMinWidth(250);
		addressValue.textProperty().bindBidirectional(UserSession.INSTANCE.addressProperty());
		GridPane.setConstraints(addressValue, 5, 1, 3, 1);
		GridPane.setHalignment(addressValue, HPos.LEFT);
		gridPane.getChildren().add(addressValue);

		Label userGroupLabel = new Label("用户组:");
		GridPane.setConstraints(userGroupLabel, 0, 2);
		GridPane.setHalignment(userGroupLabel, HPos.RIGHT);
		gridPane.getChildren().add(userGroupLabel);

		userGroupValue = new TextField();
		userGroupValue.setDisable(true);
		userGroupValue.textProperty().bind(UserSession.INSTANCE.groupProperty());
		GridPane.setConstraints(userGroupValue, 1, 2);
		GridPane.setHalignment(userGroupValue, HPos.LEFT);
		gridPane.getChildren().add(userGroupValue);

		getChildren().add(gridPane);
	}

	private void createBottomButton() {

		final Runnable saveBaseInfo = new Runnable() {

			@Override
			public void run() {
				Map<String, Object> changedData = new HashMap<String, Object>();
				changedData.put("name", nameValue.getText());
				changedData.put("gender", genderValue.getSelectionModel()
						.getSelectedItem());
				changedData.put("department", departmentValue.getText());
				changedData.put("address", addressValue.getText());
				changedData.put("email", emailValue.getText());
				changedData.put("telphone", telphoneValue.getText());

				User user = UserSession.INSTANCE.getUser();
				user.setName(nameValue.getText());
				user.setGender(genderValue.getSelectionModel()
						.getSelectedItem());
				user.setDepartment(departmentValue.getText());
				user.setAddress(addressValue.getText());
				user.setEmail(emailValue.getText());
				user.setTelphone(telphoneValue.getText());

				try {
					HessianResponse resp = HessianFactoryManger.INSTANCE
							.getUserService().update(user);
					if (resp.isSuccessful()) {
						showMessage(resp.getMsg());
					} else {
						UserLoginDialog.getInstance().showDialog(null,
								resp.getMsg());
					}
				} catch (Exception e) {
					showMessage(MessageConstants.ERROR_SERVER_ERROR);
				}

			}
		};

		HBox hb = new HBox(5);
		hb.setAlignment(Pos.CENTER);

		Button saveBtn = new Button("保存");
		saveBtn.setPrefWidth(80);
		saveBtn.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {

				if (UserSession.INSTANCE.getUser() == null) {

					UserLoginDialog.getInstance().showDialog(saveBaseInfo);
				} else {
					saveBaseInfo.run();
				}
			}
		});

		hb.getChildren().add(saveBtn);

		Region spacer = new Region();
		VBox.setVgrow(spacer, Priority.ALWAYS);
		VBox.setMargin(hb, new Insets(5));

		message = new Label();
		message.getStyleClass().add("message");
		message.setOpacity(0);
		messageAnimate = TimelineBuilder
				.create()
				.keyFrames(
						new KeyFrame(Duration.seconds(.5),
								new EventHandler<ActionEvent>() {

									public void handle(ActionEvent t) {
									}
								}, new KeyValue(message.opacityProperty(), 0,
										Interpolator.EASE_BOTH))).build();
		messageAnimate.setDelay(Duration.seconds(3));
		// messageAnimate.setAutoReverse(true);
		// messageAnimate.setCycleCount(2);

		getChildren().addAll(spacer, message, hb);
	}

	public void reload() {
		User user = UserSession.INSTANCE.getUser();
		if (user == null) {
			log.debug("用户未登录,或已经超时");
			return;
		}

//		usernameValue.setText(user.getUsername());
//		if (user.getName() != null) {
//			nameValue.setText(user.getName());
//		}
//		if (user.getGender() != null) {
//			genderValue.getSelectionModel().select(user.getGender());
//		}
//		if (user.getDepartment() != null) {
//			departmentValue.setText(user.getDepartment());
//		}
//		if (user.getEmail() != null) {
//			emailValue.setText(user.getEmail());
//		}
//		if (user.getAddress() != null) {
//
//			addressValue.setText(user.getAddress());
//		}
//		if (user.getTelphone() != null) {
//
//			telphoneValue.setText(user.getTelphone());
//		}
//		if (user.getGroup() != null) {
//
//			userGroupValue.setText(user.getGroup().getName());
//		}
	}

	private void showMessage(String content) {
		message.setText(content);
		message.setOpacity(1);
		messageAnimate.play();
	}
}
