package com.ht.ui.energy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.geometry.VPos;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.FileChooserBuilder;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafxprint.PrintUtils;

import javax.print.PrintException;

import org.w3c.dom.Document;

import com.ht.ui.MainApplication;
import com.ht.util.WorkQueue;
import com.ht.web.hessian.HessianFactoryManger;

public class ReportViewer extends Region {

	private WebView webView = new WebView();
	private WebEngine webEngine = webView.getEngine();
	private VBox mainPanel = new VBox(10);

	private StackPane modalPanel = new StackPane();
	// private ProgressBar bar = new ProgressBar();
	private ProgressIndicator indicator = new ProgressIndicator();
	private String reportFileName;

	public ReportViewer() {

		setId("ReportViewer");
		getStyleClass().add("window");
		Rectangle2D rect = Screen.getPrimary().getVisualBounds();
		setMaxSize(800, rect.getHeight() * 0.8);
		// webView.setPrefSize(rect.getWidth() * 0.8, rect.getHeight() * 0.618);

		setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent t) {
				t.consume();
			}
		});

		configMainPanel();

		configProgressBar();

	}

	public void showHTML(String url, String reportFileName) {
		// modalPanel.setVisible(true);
		webEngine.load(url);
		this.reportFileName = reportFileName;
	}

	private void configMainPanel() {
		mainPanel.setStyle("-fx-padding: 10;");
		getChildren().add(mainPanel);

		createToolBar();
		configWebView();
	}

	private void configProgressBar() {
		modalPanel.setStyle("-fx-background-color: rgba(0,0,0,.5);");
		modalPanel.setAlignment(Pos.CENTER);
		modalPanel.getChildren().add(indicator);
		getChildren().add(modalPanel);
	}

	private void configWebView() {
		webView.setStyle("-fx-border-width: 1px;-fx-border-color:dimgray;");
		webEngine.documentProperty().addListener(
				new ChangeListener<Document>() {

					@Override
					public void changed(
							ObservableValue<? extends Document> observable,
							Document oldValue, Document newValue) {
						if (newValue != null) {
							modalPanel.setVisible(false);
						}
					}
				});

		mainPanel.getChildren().add(webView);
	}

	@Override
	protected void layoutChildren() {

		double w = getWidth();
		double h = getHeight();

		// bar.setPrefSize(w * 0.618, 20);
		indicator.setPrefSize(50, 50);
		indicator.setMaxSize(50, 50);
		webView.setPrefSize(w, h - 72);

		layoutInArea(mainPanel, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
		layoutInArea(modalPanel, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
	}

	private void createToolBar() {
		HBox hb = new HBox(5);
		hb.setAlignment(Pos.CENTER_LEFT);

		Button word = new Button();
		word.getStyleClass().add("header-button");
		word.setId("word");
		word.setPrefSize(32, 32);
		word.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {

				export("*.doc", "doc");

			};
		});

		Button excel = new Button();
		excel.getStyleClass().add("header-button");
		excel.setId("excel");
		excel.setPrefSize(32, 32);
		excel.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {

				export("*.xls", "xls");

			};
		});

		Button pdf = new Button();
		pdf.getStyleClass().add("header-button");
		pdf.setId("pdf");
		pdf.setPrefSize(32, 32);
		pdf.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {

				export("*.pdf", "pdf");

			};
		});

		Button printer = new Button();
		printer.getStyleClass().add("header-button");
		printer.setId("printer");
		printer.setPrefSize(32, 32);
		printer.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {

				// export("*.ps", "postscript", "energy_monthly.rptdesign");
				InputStream is = null;
				try {
					is = HessianFactoryManger.INSTANCE.getReportService()
							.download("energy_monthly.rptdesign", "pdf");
					PrintUtils.printPDF(is);
				} catch (PrintException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
//				try {
//					PrintUtils.printNode(webView);
//				} catch (PrinterException e) {
//					e.printStackTrace();
//				} catch (PrintException e) {
//					e.printStackTrace();
//				} catch (IOException e) {
//					e.printStackTrace();
//				} catch (AWTException e) {
//					e.printStackTrace();
//				}

			};
		});

		//hb.getChildren().addAll(word, excel, pdf, printer);
		hb.getChildren().addAll(word, excel, pdf);
		mainPanel.getChildren().add(hb);
	}

	private void export(final String filter, final String extension) {
		
		final String reportFile = this.reportFileName;
		
		if (reportFile == null || reportFile.isEmpty()) {
			return;
		}
		
		FileChooser fileChooser = FileChooserBuilder.create().title("保存")
				.extensionFilters(new ExtensionFilter(filter, filter)).build();
		Stage stage = new Stage();
		stage.centerOnScreen();
		final File file = fileChooser.showSaveDialog(stage);

		if (file != null) {

			WorkQueue.INSTANCE.execute(new Runnable() {
				
				@Override
				public void run() {
					InputStream is = null;
					FileOutputStream fos = null;
					try {

						String filePath = file.getPath();
						if (!filePath.endsWith(extension)) {
							filePath += "." + extension;
						}
						//fos = new FileOutputStream(file);
						fos = new FileOutputStream(filePath);

						is = HessianFactoryManger.INSTANCE.getReportService()
								.download(reportFile, extension);

						byte[] buf = new byte[512];
						int count = 0;
						while ((count = is.read(buf)) != -1) {
							fos.write(buf, 0, count);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (fos != null) {
							try {
								fos.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						if (is != null) {
							try {
								is.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						Platform.runLater(new Runnable() {
							
							@Override
							public void run() {
								modalPanel.setVisible(false);
								MainApplication.getMainApp().showMessage("文件已保存");
							}
						});
					}
					
				}
			});
			// new Thread(task).start();
			modalPanel.setVisible(true);

		}
	}

}
