package cn.hmsoft.ltc.controller;

import java.net.URL;
import java.util.ResourceBundle;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hmsoft.ltc.common.util.IexploreUtil;
import cn.hmsoft.ltc.service.iface.AwesomeActionService;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;

/**
 * 细目表.
 * @author zq
 *
 */
@FXMLController
public class AppMainController implements Initializable {
    
	@FXML
	private Button buildBtn;
	
    @FXML
    private Button saveBtn;
    
    @FXML
    private WebView webView;
    
    private WebEngine webEngine;
    
    // Be aware: This is a Spring bean. So we can do the following:
    @Autowired
    private AwesomeActionService actionService;
    
    /**
     * 生成试卷.
     * 这个按钮可以调用的js里面的方法。
     * @param event
     */
    @FXML
    private void buildPaperFunc(ActionEvent event) {
    	
    	//1-从保存的json中生成一个word
    	//WordUtil.writeDoc("test.docx",null);
    	//2-用word打开之前生成的word，这里暂时写死为
    	IexploreUtil.openByUrl("http://localhost:8080/office/word?docName=" + "test.docx");
    }

    /**
     * 保存细目表.
     * @param event
     */
    @FXML
    private void saveTableFunc(ActionEvent event) {
    	//保存到Data目录,json格式
    	Object obj = webEngine.executeScript("build()");
    	System.err.println(obj);
    }
    
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		webEngine = webView.getEngine();
	    webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
	    	@Override
	        public void changed(ObservableValue ov, State oldState, State newState) {
	    		if (newState == Worker.State.SUCCEEDED) {
	            	System.err.println("加载完成..........");
	            	JSObject win = (JSObject) webEngine.executeScript("window");
	            }
	        }
	    });
	    //webEngine.load("http://localhost:8080/detail");
	    webEngine.load(getClass().getResource("/templates/Detail.html").toExternalForm());
	}
	
	public void initGui(double width, double height) {
		this.webView.setMinWidth(width - 45);
		this.webView.setMinHeight(height);
		this.saveBtn.setLayoutX(50);
		this.buildBtn.setLayoutX(200);
	}
}
