package com.ht.ui.taginfo;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TitledPane;
import javafx.scene.control.ToolBar;
import javafx.scene.control.TreeItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;

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

import com.ht.tags.model.index.IndexTreeNode;
import com.ht.tags.model.index.IndexType;
import com.ht.tags.model.tag.TagVar;
import com.ht.ui.MainApplication;
import com.ht.ui.controls.BreadcrumbBar;
import com.ht.ui.controls.BreadcrumbBar.PathChangeListener;
import com.ht.ui.controls.IndexNodeTreeItem;
import com.ht.web.hessian.HessianFactoryManger;
import com.ht.web.mongo.domain.YMHistoryData;
import com.ht.web.remoting.HessianResponse;

public class TagInfoViewer extends VBox {
	private static final Logger log = LoggerFactory
			.getLogger(TagInfoViewer.class);

	private MainIndexNodeTree tagVarTreeView;
	private BuildingTreeView buildingTreeView;
	private TagVarTreeSelectedListener tagVarListener = new TagVarTreeSelectedListener();
	private BuildingSelectedListener buildingTreeListener = new BuildingSelectedListener();
	private Map<String, IndexNodeTreeItem> indexTreeNodeMap = new HashMap<String, IndexNodeTreeItem>();


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

	private BreadcrumbBar breadcrumbBar;

	private SplitPane splitPane;

	private VBox rightPanel;

	// private Label parentValueLabel;
	// private Label childrenValueLabel;
	// private Label errorLabel;
	// private GridPane cmpMessageBox;
	// private TextField cmpTimeValue;

	private TagVarTableView tagVarTableView;

	private CmpPanel cmpPanel;// 比对面板

	private VBox tagVarInfoPanel;// 变量信息面板
	private BuildingInfoPanel buildingInfoPanel;// 变量信息面板

	private ManualPanel manualPanel;// 人工输入面板


	private Accordion accordion;

	public TagInfoViewer() {
		super(5);

		setId("TagInfoViewer");
		getStyleClass().add("window");
		setCache(true);

		visibleProperty().addListener(new ChangeListener<Boolean>() {
			@Override
			public void changed(ObservableValue<? extends Boolean> observable,
					Boolean oldValue, Boolean newValue) {
				if (newValue) {
					tagVarTreeView.updateIndexTree();
					buildingTreeView.updateIndexTree();
				}
			}
		});

		createToolBar();
		createTagVarTreeView();
		createRightPanel();

		splitPane = new SplitPane();
		splitPane.setId("page-splitpane");
		splitPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
		GridPane.setConstraints(splitPane, 0, 1);

		splitPane.getItems().addAll(accordion, rightPanel);
		splitPane.setDividerPosition(0, 0.2);

		VBox.setVgrow(splitPane, Priority.ALWAYS);

		getChildren().add(splitPane);
	}

	private void createToolBar() {
		ToolBar toolbar = new ToolBar();
		toolbar.getStyleClass().add("mini-toolbar");

		Button backButton = new Button();
		backButton.setGraphic(new ImageView(new Image(MainApplication.class
				.getResourceAsStream("images/back.png"))));
		backButton.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				String path = breadcrumbBar.getPath();
				if (path.lastIndexOf("/") > 0) {
					// breadcrumbBar.setPath(path.substring(0,
					// path.lastIndexOf("/")));
					IndexNodeTreeItem item = indexTreeNodeMap.get(path
							.substring(0, path.lastIndexOf("/")));
					if (item.getValue().getIndexType().equals(IndexType.MAIN)) {
						tagVarTreeView.getSelectionModel().select(item);
					} else {
						buildingTreeView.getSelectionModel().select(item);
					}
				}
			}
		});
		backButton.setMaxHeight(Double.MAX_VALUE);

		breadcrumbBar = new BreadcrumbBar(new PathChangeListener() {

			@Override
			public void pathChanged(String path) {

				IndexNodeTreeItem item = indexTreeNodeMap.get(path);
				if (item.getValue().getIndexType().equals(IndexType.MAIN)) {
					tagVarTreeView.getSelectionModel().select(item);
				} else {
					buildingTreeView.getSelectionModel().select(item);
				}

			}
		});

		toolbar.getItems().addAll(backButton, breadcrumbBar);

		getChildren().add(toolbar);
	}

	private void createRightPanel() {

		rightPanel = new VBox();
		rightPanel.getStyleClass().add("info-pane");

		createTagVarPanel();
		createBuildingPanel();
		createCmpPanel();
		createManuaPanel();

		rightPanel.getChildren().add(tagVarInfoPanel);
	}

	private void createBuildingPanel() {
		buildingInfoPanel = new BuildingInfoPanel();
	}

	private void createTagVarPanel() {
		tagVarInfoPanel = new VBox();

		Label title1 = new Label("支路信息");
		title1.getStyleClass().add("info-pane-header");

		tagVarTableView = new TagVarTableView();
		//createTagVarTable();

		Region spacer = new Region();
		spacer.setMinHeight(20);

		tagVarInfoPanel.getChildren().addAll(title1, tagVarTableView, spacer);
	}

	private void createManuaPanel() {
		manualPanel = new ManualPanel(new EventHandler<ActionEvent>() {

			private SimpleDateFormat timeFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");

			@Override
			public void handle(ActionEvent event) {
				try {
					Map<String, YMHistoryData> tagVarValueMap = new HashMap<String, YMHistoryData>();
					Date time = timeFormat.parse(manualPanel.getDateTimeText());

					for (TagVar tagVar : tagVarTableView.getItems()) {
						Double value = tagVarTableView.getTagVarValue(tagVar);
						if (value != null) {

							YMHistoryData data = new YMHistoryData(time, value);
							tagVarValueMap.put(tagVar.getTagPath(), data);
						} else {
							manualPanel.showMessage("请输入能耗数据");
							return;
						}
					}
					try {
						HessianResponse resp = HessianFactoryManger.INSTANCE
								.getTagVarService().manualInput(tagVarValueMap);
						manualPanel.showMessage(resp.getMsg());
					} catch (Exception e) {
						manualPanel.showMessage("服务器响应超时");
					}
				} catch (NumberFormatException e) {
					manualPanel.showMessage("能耗数据只能为数字");
				} catch (ParseException e) {
					manualPanel.showMessage("请输入正确的时间，格式为【小时:分钟】");
				}
			}
		});

	}

	private void createCmpPanel() {
		cmpPanel = new CmpPanel(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				if (!tagVarTableView.getItems().isEmpty()) {
					int hour = cmpPanel.getCmpTime();
					Calendar c = Calendar.getInstance();
					c.add(Calendar.HOUR_OF_DAY, -hour);

					try {
						List<String> list = new ArrayList<String>(tagVarTableView.getItems().size());
						int parentTagCount = 0;
						int childrenTagCount = 0;
						for (TagVar v : tagVarTableView.getItems()) {
							//list.add(v.getTagPath());
							list.add(v.getVarId());
							if (v.isParent()) {
								parentTagCount++;
							} else {
								childrenTagCount++;
							}
						}
						if (parentTagCount == 0) {
							cmpPanel.showMessage("[" + breadcrumbBar.getPath() + "]未安装电能表");
						} else if(childrenTagCount == 0) {
							cmpPanel.showMessage("[" + breadcrumbBar.getPath() + "]引出支路中未安装电能表");
						} else {
							HessianResponse resp = HessianFactoryManger.INSTANCE
									.getTagVarService().getTagValue(list,
											c.getTime());
							tagVarValueCallBack(resp);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					cmpPanel.showMessage("[" + breadcrumbBar.getPath() + "]及其引出支路中均未安装电能表");
				}
			}
		});

	}

	private void createTagVarTreeView() {

		accordion = new Accordion();

		tagVarTreeView = new MainIndexNodeTree(indexTreeNodeMap, tagVarListener);

		buildingTreeView = new BuildingTreeView(indexTreeNodeMap, buildingTreeListener);

		TitledPane t1 = new TitledPane("支路信息", tagVarTreeView);
		t1.setAnimated(false);
		accordion.getPanes().add(t1);

		TitledPane t2 = new TitledPane("建筑信息", buildingTreeView);
		t2.setAnimated(false);
		accordion.getPanes().add(t2);

	}

	/**
	 * 树选择监听器
	 * 
	 * @author Administrator
	 * 
	 */
	private class TagVarTreeSelectedListener implements
			ChangeListener<TreeItem<IndexTreeNode>> {

		@Override
		public void changed(
				ObservableValue<? extends TreeItem<IndexTreeNode>> observable,
				TreeItem<IndexTreeNode> oldValue,
				TreeItem<IndexTreeNode> newValue) {
			if (newValue != null) {
				cmpPanel.hiddenCmpMessage();
				// cmpMessageBox.setVisible(false);

				breadcrumbBar.setPath(newValue.getValue().getPath());
				tagVarTableView.getSelectionModel().clearSelection();
				tagVarTableView.getItems().clear();

				HessianResponse resp;
				try {
					resp = HessianFactoryManger.INSTANCE.getTagService()
							.getEnergyTagVarByIndex(
									newValue.getValue().getPath());

					if (resp.isSuccessful() && resp.getData() != null) {
						List<TagVar> list = (List<TagVar>) resp.getData();
						tagVarTableView.setAllTagVarItems(list);
							
						if (!list.isEmpty()) {
							TagVar tagVar = list.get(0);
							rightPanel.getChildren().clear();
							rightPanel.getChildren().addAll(tagVarInfoPanel,
									tagVar.isManual() ? manualPanel : cmpPanel);
							
							int parentTagCount = 0;
							int childrenTagCount = 0;
							for (TagVar v : list) {
								System.out.println(v.getVarId());
								if (v.isParent()) {
									parentTagCount++;
								} else {
									childrenTagCount++;
								}
							}
							if (parentTagCount == 0) {
								cmpPanel.showMessage("[" + breadcrumbBar.getPath() + "]未安装电能表");
							} else if(childrenTagCount == 0) {
								cmpPanel.showMessage("[" + breadcrumbBar.getPath() + "]引出支路中未安装电能表");
							}
						} else {
							cmpPanel.showMessage("[" + breadcrumbBar.getPath() + "]及其引出支路中均未安装电能表");
						}

					}
				} catch (Exception e) {
				}
			}
		}

	}

	private class BuildingSelectedListener implements
			ChangeListener<TreeItem<IndexTreeNode>> {

		@Override
		public void changed(
				ObservableValue<? extends TreeItem<IndexTreeNode>> observable,
				TreeItem<IndexTreeNode> oldValue,
				TreeItem<IndexTreeNode> newValue) {
			if (newValue != null) {

				breadcrumbBar.setPath(newValue.getValue().getPath());

				HessianResponse resp;
				try {
					resp = HessianFactoryManger.INSTANCE.getTagService()
							.getBuildingInfoByIndex(newValue.getValue().getPath());

					if (resp.isSuccessful() && resp.getData() != null) {
						Map<String, String> map = (Map<String, String>) resp.getData();
						System.out.println(Arrays.toString(map.keySet().toArray()));
							buildingInfoPanel.setInfoMap(newValue.getValue(), map);
							rightPanel.getChildren().clear();
							rightPanel.getChildren().addAll(buildingInfoPanel);

					}
				} catch (Exception e) {
				}
			}
		}

	}

	private void tagVarValueCallBack(HessianResponse resp) {
		if (resp == null) {
			MainApplication.getMainApp().showMessage("服务器响应超时.");
			return;
		}
		if (resp.isSuccessful()) {
			log.debug("返回数据: {}", resp.getData());

			double parentValue = 0;
			double childrenValue = 0;

			Map<String, Double> dataMap = (Map<String, Double>) resp.getData();

			int hour = cmpPanel.getCmpTime();
			for (TagVar tagVar : tagVarTableView.getItems()) {
				
				Double value = dataMap.get(tagVar.getTagPath());

				if (value == null && tagVar.getRatedPower() != null) {
					try {
						value = Double.parseDouble(tagVar.getRatedPower())
								* hour;
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
				}
				if (value == null) {
					continue;
				}

				tagVarTableView.setTagVarValue(tagVar, decimalFormat.format(value));

				if (tagVar.isParent()) {
					parentValue += value;
				} else {
					childrenValue += value;
				}
			}
			
			cmpPanel.setParentValue(decimalFormat.format(parentValue));
			cmpPanel.setChildrenValue(decimalFormat.format(childrenValue));
			String errorStyle = parentValue >= childrenValue ? "-fx-text-fill:green;"
					: "-fx-text-fill:red;";
			if (parentValue > 0) {
				cmpPanel.showCmpInfo(
						decimalFormat.format((parentValue - childrenValue) * 100
								/ parentValue)
								+ "%", errorStyle);
			} else {
				
			}

		} else if (!resp.getMsg().isEmpty()) {
			MainApplication.getMainApp().showMessage(resp.getMsg());
		}
	}

}
