package com.ht.ui.alarm;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ToolBar;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.util.Duration;

import com.ht.ui.GlobalSettings;
import com.ht.ui.MainApplication;
import com.ht.ui.controls.BreadcrumbBar;
import com.ht.ui.util.MessageConstants;
import com.ht.ui.util.UserSecurityUtil;
import com.ht.util.UserSession;
import com.ht.web.hessian.HessianFactoryManger;
import com.ht.web.mongo.domain.Alarm;
import com.ht.web.mongo.domain.Fault;
import com.ht.web.mongo.domain.OnOffShift;
import com.ht.web.mongo.domain.SOE;
import com.ht.web.mongo.domain.User;
import com.ht.web.mongo.domain.UserOperation;

/**
 * 实时报警窗口
 * @author Administrator
 *
 */
public class AlarmInfoWindow extends BorderPane {

	private TranslateTransition transition;

	private LinkedList<Node> historyInfoNode = new LinkedList<Node>();
	private final int maxHistorySize = 100;
	private int currentNodeIndex = -1;

	private double height = 150;
	private double width = 800;
	private double translateX = 0;

	public AlarmInfoWindow() {
		setId("alarm-window");
		getStyleClass().addAll("window", "shadow");

		setPrefSize(width, height);
		setMaxSize(width, height);

		Rectangle2D rect = Screen.getPrimary().getVisualBounds();
		setTranslateY(rect.getHeight() - height - 20);
		translateX = (width - rect.getWidth()) / 2;
		setTranslateX((width - rect.getWidth()) / 2 - width - 10);

		// this.setOpacity(0.8);

		transition = new TranslateTransition(Duration.seconds(1), this);
		transition.setAutoReverse(true);

		HBox hbox = new HBox();
		hbox.setAlignment(Pos.CENTER);

		preBtn = new Button();
		//preBtn.setId("alarm-window-pre");
		preBtn.setGraphic(new ImageView(getClass().getResource("images/arrow_left.png").toExternalForm()));
		preBtn.getStyleClass().add("image-button2");
		preBtn.setPrefSize(20, 22);
		preBtn.setMinSize(20, 22);
		preBtn.setTooltip(new Tooltip("上一条信息"));
		preBtn.setDisable(true);
		preBtn.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent actionEvent) {
				currentNodeIndex--;
				setCenter(historyInfoNode.get(currentNodeIndex));
				if (currentNodeIndex <= 0) {
					preBtn.setDisable(true);
				}
				nexBtn.setDisable(false);
			}
		});
		hbox.getChildren().add(preBtn);

		nexBtn = new Button();
		//nexBtn.setId("alarm-window-next");
		nexBtn.setGraphic(new ImageView(getClass().getResource("images/arrow_right.png").toExternalForm()));
		nexBtn.getStyleClass().add("image-button2");
		nexBtn.setPrefSize(20, 22);
		nexBtn.setMinSize(20, 22);
		nexBtn.setTooltip(new Tooltip("下一条信息"));
		nexBtn.setDisable(true);
		nexBtn.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent actionEvent) {
				currentNodeIndex++;
				setCenter(historyInfoNode.get(currentNodeIndex));
				if (currentNodeIndex >= (historyInfoNode.size() - 1)) {
					nexBtn.setDisable(true);
				}
				preBtn.setDisable(false);
			}
		});
		hbox.getChildren().add(nexBtn);
		
		Button openTable = new Button();
		openTable.getStyleClass().add("image-button");
		openTable.setGraphic(new ImageView(getClass().getResource("images/list_go.png").toExternalForm()));
		hbox.getChildren().add(openTable);

		Region spacer = new Region();
		HBox.setHgrow(spacer, Priority.ALWAYS);
		hbox.getChildren().add(spacer);
		
		infoLabel = new Label("暂无未确认信息");
		infoLabel.setTextFill(Color.DIMGRAY);
		hbox.getChildren().add(infoLabel);
		
		Region spacer2 = new Region();
		HBox.setHgrow(spacer2, Priority.ALWAYS);
		hbox.getChildren().add(spacer2);

		Button closeBtn = new Button();
		//closeBtn.setId("alarm-window-close");
		closeBtn.setGraphic(new ImageView(getClass().getResource("images/close.png").toExternalForm()));
		closeBtn.getStyleClass().add("image-button2");
		closeBtn.setPrefSize(20, 22);
		closeBtn.setMinSize(20, 22);
		closeBtn.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent actionEvent) {
				hidden();
			}
		});
		hbox.getChildren().add(closeBtn);

		setTop(hbox);

	}

	@Override
	protected void layoutChildren() {
		super.layoutChildren();

		// setTranslateX(-width - 60 - getLayoutBounds().getMinX());
	}

	private void show() {
		if (GlobalSettings.INSTANCE.showAlarmProperty().getValue() && this.getTranslateX() < translateX) {
			// transition.setFromX(-getWidth() - 10);
			// transition.setToX(10);
			transition.setFromX(translateX - getWidth() - 10);
			transition.setToX(translateX + 10);
			transition.play();
		}
	}

	private void hidden() {
		// transition.setFromX(10);
		// transition.setToX(-getWidth() - 10);
		Runnable run = new Runnable() {

			@Override
			public void run() {

				User user = UserSession.INSTANCE.getUser();
				if (user != null) {

					if (user.getGroup().getAlarmAffirm()) {
						transition.setFromX(translateX + 10);
						transition.setToX(translateX - getWidth() - 10);
						transition.play();

						try {
							HessianFactoryManger.INSTANCE.getUserService()
									.submitUserOpreation(
											new UserOperation("报警确认",
													new Date(), user));
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						MainApplication.getMainApp().showMessage(
								MessageConstants.INFO_PERMISSION_DENIED);
					}
				}
			}
		};
		UserSecurityUtil.verifyUserAuthority(run);
	}

	public void fireRSChangeEvent(OnOffShift bean) {
		String tagPath = bean.getTagPath();
		String info = bean.getInfo();
		String datetime = dateFormat.format(bean.getDatetime());
		String color = "green";// 越下限
		if (bean.isValue()) {// 越上限
			color = "red";
		}

		createWarningContent("遥信变位:", tagPath, info, null, null, datetime,
				color);
	}

	private synchronized void addNewAlarmInfo(BorderPane borderPane) {
		setCenter(borderPane);

		historyInfoNode.addLast(borderPane);
		currentNodeIndex = historyInfoNode.size() - 1;
		nexBtn.setDisable(true);
		if (historyInfoNode.size() > 1) {
			preBtn.setDisable(false);
		}
		if (historyInfoNode.size() > maxHistorySize) {
			historyInfoNode.removeFirst();
		}
		this.show();
	}

	private DecimalFormat decimalFormat = new DecimalFormat(".##");

	public void fireSOEEvent(SOE bean) {

		String tagPath = bean.getTagPath();
		String info = bean.getInfo();
		String value = decimalFormat.format(bean.getValue());
		String settingValue = decimalFormat.format(bean.getSettingValue());
		String datetime = dateFormat.format(bean.getDatetime());
		String color = "green";// 越下限
		if (bean.getValue().doubleValue() > bean.getSettingValue()
				.doubleValue()) {// 越上限
			color = "red";
		}

		createWarningContent("titleLabel", tagPath, info, value, settingValue,
				datetime, color);
	}

	private void createWarningContent(String title, String tagPath,
			String info, String value, String settingValue, String datetime,
			String color) {
		BorderPane borderPane = new BorderPane();
		// borderPane.setStyle("-fx-font-size:18px;");

		/* 标题 */
		// Label titleLabel = new Label(title);
		// titleLabel.getStyleClass().add("title");
		// BorderPane.setAlignment(titleLabel, Pos.TOP_LEFT);
		// borderPane.setTop(titleLabel);

		/* 内容 */
		VBox vbox = new VBox(10);
		BorderPane.setAlignment(vbox, Pos.TOP_CENTER);

		// 变量位置 变量名称
		ToolBar toolbar = new ToolBar();
		toolbar.getStyleClass().add("mini-toolbar");

		BreadcrumbBar tagPathBar = new BreadcrumbBar();
		tagPathBar.setPath(tagPath);
		toolbar.getItems().add(tagPathBar);
		vbox.getChildren().add(toolbar);

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

		// 报警信息
		Label infoLabel = new Label(info);
		infoLabel.getStyleClass().add("info");
		infoLabel.setWrapText(true);// 文字自动折行
		infoLabel.setContentDisplay(ContentDisplay.CENTER);// 矩形框居中显示
		infoLabel.setStyle("-fx-background-color:" + color + ";");

		hb.getChildren().add(infoLabel);

		// 报警值
		if (value != null) {

			Label l1 = new Label("动作值: " + value);
			l1.getStyleClass().add("info");
			Label l2 = new Label("设定值: " + settingValue);
			l2.getStyleClass().add("info");
			hb.getChildren().addAll(l1, l2);
		}
		vbox.getChildren().add(hb);

		borderPane.setCenter(vbox);

		/* 时间 */
		Label datetimeLabel = new Label("发生时间:" + datetime);
		datetimeLabel.setAlignment(Pos.CENTER_RIGHT);
		datetimeLabel.setStyle("-fx-font-size:14px;");
		VBox.setVgrow(datetimeLabel, Priority.ALWAYS);

		borderPane.setBottom(datetimeLabel);
		BorderPane.setAlignment(datetimeLabel, Pos.CENTER_RIGHT);

		addNewAlarmInfo(borderPane);
	}

	public void fireFaultEvent(Fault bean) {
		String tagPath = bean.getTagPath();
		String tagName = bean.getTagName();
		String info = bean.getInfo();
		String datetime = dateFormat.format(bean.getDatetime());
		String color = "green";// 越下限
		if (bean.isValue()) {// 越上限
			color = "red";
		}

		createWarningContent("故障信息:", tagPath, info, null, null, datetime,
				color);
	}

	public void fireAlarmEvent(Alarm bean) {
		String tagPath = bean.getTagPath();
		String info = bean.getInfo();
		String value = decimalFormat.format(bean.getValue());
		String settingValue = decimalFormat.format(bean.getSettingValue());
		String datetime = dateFormat.format(bean.getDatetime());
		String color = "green";// 越下限
		if (bean.getValue().doubleValue() > bean.getSettingValue()
				.doubleValue()) {// 越上限
			color = "red";
		}

		createWarningContent("遥测越限:", tagPath, info, value, settingValue,
				datetime, color);

	}

	private SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日 HH:mm:ss:SS");

	private Button preBtn;

	private Button nexBtn;

	private Label infoLabel;
}
