1. 程式人生 > >【備忘錄】Java後臺和Echart圖表資料互動

【備忘錄】Java後臺和Echart圖表資料互動

package com.epoint.PingBiao_Common.spc.bim.domain;

import java.util.ArrayList;
import java.util.List;

/**
 * 存放Echart資料
 *  [一句話功能簡述]
 *  [功能詳細描述]
 * @作者 Faep
 * @version [版本號, 2018年8月13日]
 * @see [相關類/方法]
 * @since [產品/模組版本]
 */
public class EchartData
{
    public List<String> legend = new ArrayList<String>();//資料分組  
    public List<String> category = new ArrayList<String>();//橫座標  
    public List<Series> series = new ArrayList<Series>();//縱座標  


    public EchartData(List<String> legendList, List<String> categoryList, List<Series> seriesList) {  
        super();  
        this.legend = legendList;  
        this.category = categoryList;  
        this.series = seriesList;  
    }  

}
package com.epoint.PingBiao_Common.spc.bim.domain;

import java.util.List;
/**
 * 存放Echart資料
 *  [一句話功能簡述]
 *  [功能詳細描述]
 * @作者 Faep
 * @version [版本號, 2018年8月14日]
 * @see [相關類/方法]
 * @since [產品/模組版本]
 */
public class Series
{
    public String name;  

    public String type;  

    public List<Double> data;  
    public Series( String name, String type, List<Double> data) {  
        super();  
        this.name = name;  
        this.type = type;  
        this.data = data;  
    }  
}
package com.epoint.PingBiao_Common.spc.bim.action;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RestController;

import com.epoint.PingBiao_Common.spc.bim.domain.EchartData;
import com.epoint.PingBiao_Common.spc.bim.domain.Series;
import com.epoint.ZtbCommon.ZtbCommonDao;
import com.epoint.basic.controller.BaseController;
import com.epoint.core.dto.base.TreeNode;
import com.epoint.core.dto.model.TreeModel;
import com.epoint.core.grammar.Record;
import com.epoint.database.config.JdbcConstantValue;
import com.epoint.database.jdbc.connection.DataSourceConfig;

/**
 * 
 *  資金趨勢顯示後臺action
 *  介面:spcplancapitaltrend.html
 *  指令碼:spcplancapitaltrend.js
 *  [功能詳細描述]
 * @作者 Faep
 * @version [版本號, 2018年8月14日]
 * @see [相關類/方法]
 * @since [產品/模組版本]
 */
@RestController("spcplancosttrendaction")
@Scope("request")
public class SpcPlanCostTrendAction extends BaseController
{
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;

    /**
     * 獲取人材機樹
     */
    private TreeModel treeModel;

    /**
     * 獲取疊加複選框狀態
     */
    private Boolean djstatus;

    /**
     * 樹結點code
     */
    private String treecode;
    
    /**
     * 構件ID
     */
    @SuppressWarnings("unused")
    private String instanceguids;

    /**
     * 初始化
     * 已驗證+1
     */
    @Override
    public void pageLoad() {
//        // 獲取url傳遞過來的instanceguids
//        instanceguids = getRequestParameter("instanceguids");
//        // 通過構件集合字串獲取對應的條件sql
//        if (StringUtils.isNotBlank(instanceguids)) {
//            if (instanceguids.contains(",")) {
//                String[] lst = instanceguids.split(",");
//                instanceguids = "'" + StringUtil.join(lst, "','") + "'";
//            }
//            else if (!instanceguids.equals("")) {
//                instanceguids = "'" + instanceguids + "'";
//            }
//        }
    }
    
    private ZtbCommonDao getSQLiteDao(){
        String path = "E:\\待辦\\BIM\\程式碼demo\\111.bc-jgk";
        DataSourceConfig config = new DataSourceConfig(path, JdbcConstantValue.SQLLite);
        ZtbCommonDao dao = ZtbCommonDao.getInstance(config);
        
        return dao;
    }

    /**
     * 
     *  [獲取人材機樹]
     *  [功能詳細描述]
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    @SuppressWarnings("serial")
    public TreeModel getTree() {
        if (treeModel == null) {
            treeModel = new TreeModel()
            {
                @Override
                public List<TreeNode> fetch(TreeNode treeNode) {
                    List<TreeNode> list = new ArrayList<TreeNode>();
                    TreeNode root = new TreeNode();
                    root.setText("全部");
                    root.setId("0");
                    root.setPid("-1");
                    list.add(root);
                    root.setExpanded(true);//展開下一層節點
                    TreeNode node1 = new TreeNode();
                    node1.setText("人工");
                    node1.setId("1");
                    node1.setPid("0");
                    node1.setLeaf(true);
                    list.add(node1);
                    TreeNode node2 = new TreeNode();
                    node2.setText("材料");
                    node2.setId("2");
                    node2.setPid("0");
                    list.add(node2);
                    TreeNode node21 = new TreeNode();
                    node21.setText("黃沙");
                    node21.setId("21");
                    node21.setPid("2");
                    node21.setLeaf(true);
                    list.add(node21);
                    TreeNode node22 = new TreeNode();
                    node22.setText("水泥");
                    node22.setId("22");
                    node22.setPid("2");
                    node22.setLeaf(true);
                    list.add(node22);
                    TreeNode node23 = new TreeNode();
                    node23.setText("混凝土");
                    node23.setId("23");
                    node23.setPid("2");
                    node23.setLeaf(true);
                    list.add(node23);
                    TreeNode node3 = new TreeNode();
                    node3.setText("機械");
                    node3.setId("3");
                    node3.setPid("0");
                    node3.setLeaf(true);
                    list.add(node3);
                    return list;
                }
            };
        }
        return treeModel;
    }

    /**
     * 
     *  根據選擇人材機時顯示圖表資料
     *  [功能詳細描述]
     *  @param clbhjsonstr
     *  材料編號的json字串
     *  @param unitguid
     *  工程guid
     *  @param isMonth
     *  顯示每月資金
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    public EchartData lineData() {
        List<String> legend = new ArrayList<String>();//縱座標資料展示
        List<Series> series = new ArrayList<Series>();//縱座標資料展示
        List<String> serisData = new ArrayList<String>();//橫座標資料展示
        List<String> monthList = dateList();//獲取x軸的月份列表
        List<Double> jihuaList = new ArrayList<Double>();//計劃
        List<Double> shijiList = new ArrayList<Double>();//實際
        List<Record> jihuaRecord = dataList(treecode);//getAllFyjh();
        List<Record> shijiRecord = dataList(treecode);//getAllFysj();
        for (int i = 0; i < monthList.size(); i++) {
            serisData.add(monthList.get(i));
            boolean flagJh = false;
            for (Record record : jihuaRecord) {
                if (record.getStr("realend").equals(monthList.get(i))) {
                    switch (treecode) {
                        case "0":
                            jihuaList.add(record.getDouble("zfy"));
                            break;
                        default:
                            jihuaList.add(record.getDouble("totalprice"));
                            break;
                    }
                    flagJh = true;
                    break;
                }
            }
            if (!flagJh) {
                jihuaList.add(0.0);
            }
            boolean flagSj = false;
            for (Record record : shijiRecord) {
                if (record.getStr("realend").equals(monthList.get(i))) {
                    switch (treecode) {
                        case "0":
                            shijiList.add(record.getDouble("zfy"));
                            break;
                        default:
                            shijiList.add(record.getDouble("totalprice"));
                            break;
                    }
                    flagSj = true;
                    break;
                }
            }
            if (!flagSj) {
                shijiList.add(0.0);
            }
        }
        jihuaList = getData(djstatus, jihuaList);
        shijiList = getData(djstatus, shijiList);
        
        //賦值series變數的資料
        series.addAll(getSeriesByData(jihuaList, shijiList));
        
        //賦值legen變數的資料
        legend.add("計劃日期");
        legend.add("實際日期");
        
        EchartData data = new EchartData(legend, monthList, series);
        
        return data;
    }
    
    /**
     * 獲取日期月份
     *  [一句話功能簡述]
     *  [功能詳細描述]
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    private List<String> dateList(){
        ZtbCommonDao dao = getSQLiteDao();
        String sql = "select realend from ComponentTime";
        List<String> dateList = dao.findList(sql, String.class);
        dao.close();
        dao = null;
        return dateList;
    }
    
    /**
     * 獲取人材機資料
     *  [一句話功能簡述]
     *  [功能詳細描述]
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    private List<Record> dataList(String treecode){
        ZtbCommonDao dao = getSQLiteDao();
        String where = "";
        switch (treecode) {
            case "0":
                return getAllPriceCost();
            case "1":
                where = "1.0";
                break;
            case "2":
                where = "2.0";
                break;
            case "3":
                where = "3.0";
                break;
            default:
                break;
        }
        
        String sql = "select a.realend,b.componentid,sum(c.price) as totalprice from componenttimeinstance b LEFT JOIN "
                + "componenttime a on a.id = b.componenttimeid LEFT JOIN zaojiarcj c where b.componentid = c.instanceid "
                + "and c.rcjlb='" + where + "' GROUP BY a.realend";
        
        List<Record> dateList = dao.findList(sql, Record.class);
        dao.close();
        dao = null;
        return dateList;
    }
    
    /**
     * 獲取總價
     *  [一句話功能簡述]
     *  [功能詳細描述]
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    private List<Record> getAllPriceCost(){
        ZtbCommonDao dao = getSQLiteDao();
        String sql = "select realend,cost*10000.0 as zfy from ComponentTime";
        List<Record> list = dao.findList(sql, Record.class);
        dao.close();
        dao = null;
        return list;
    }
    
    
    /**
     * 
     *  [選擇材料時顯示圖表]
     *  [功能詳細描述]
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    public EchartData lineDataClbh() {
        List<String> legend = new ArrayList<String>();//縱座標資料展示
        List<Series> series = new ArrayList<Series>();//縱座標資料展示
        List<String> serisData = new ArrayList<String>();//橫座標資料展示
        //獲取x軸的月份列表
        List<String> monthList = dateList();
        List<Double> jihuaList = new ArrayList<Double>();
        List<Double> shijiList = new ArrayList<Double>();
        List<Record> jihuaRecord = new ArrayList<Record>();
        List<Record> shijiRecord = new ArrayList<Record>();
        
        jihuaRecord = dataCLList(treecode);
        shijiRecord = dataCLList(treecode);//TODO 目前二者一樣,如何區別
        
        for (int i = 0; i < monthList.size(); i++) {
            serisData.add(monthList.get(i));
            boolean flagJh = false;
            for (Record record : jihuaRecord) {
                if (record.getStr("realend").equals(monthList.get(i))) {
                    jihuaList.add(record.getDouble("totalprice"));
                    flagJh = true;
                    break;
                }
            }
            if (!flagJh) {
                jihuaList.add(0.0);
            }
            boolean flagSj = false;
            for (Record record : shijiRecord) {
                if (record.getStr("realend").equals(monthList.get(i))) {//TODO
                    shijiList.add(record.getDouble("totalprice"));
                    flagSj = true;
                    break;
                }
            }
            if (!flagSj) {
                shijiList.add(0.0);
            }
        }
        jihuaList = getData(djstatus, jihuaList);
        shijiList = getData(djstatus, shijiList);
        
        //賦值series變數的資料
        series.addAll(getSeriesByData(jihuaList, shijiList));
        
        //賦值legen變數的資料
        legend.add("計劃日期");
        legend.add("實際日期");
        
        EchartData data = new EchartData(legend, monthList, series);
        
        return data;
    }
    
    /**
     * 獲取材料細則資料
     *  [一句話功能簡述]
     *  [功能詳細描述]
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    private List<Record> dataCLList(String treecode){
        ZtbCommonDao dao = getSQLiteDao();
        String where = "";
        switch (treecode) {
            case "21":
                where = "'%黃沙%'";
                break;
            case "22":
                where = "'%水泥%'";
                break;
            case "23":
                where = "'%混凝土%'";
                break;
            default:
                break;
        }
        
        String sql = "select a.realend,b.componentid,sum(c.price) as totalprice from componenttimeinstance b LEFT JOIN "
                + "componenttime a on a.id = b.componenttimeid LEFT JOIN zaojiarcj c where b.componentid = c.instanceid "
                + "and c.rcjlb='2' and c.name like " + where + " GROUP BY a.realend";
        
        List<Record> dateList = dao.findList(sql, Record.class);
        dao.close();
        dao = null;
        return dateList;
    }

    /**
     * 
     *  根據list資料按照月份是否累計得到新的集合資料
     *  [功能詳細描述]
     *  @param isMonth
     *  @param list
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    private List<Double> getData(boolean isMonth, List<Double> list) {
        //判斷是否按月統計(true表示按月統計,false表示按月累計)
        if (!isMonth) {
            return list;
        }
        else {
            List<Double> lstResult = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                lstResult.add(getListLJ(list, i));
            }
            return lstResult;
        }
    }
    
    /**
     * 獲取月份累計預算
     */
    private double getListLJ(List<Double> list, int index){
        double val = 0;
        for (int i = 0; i < index; i++) {
            val += list.get(i);
        }
        return val;
    }

    /**
     * 
     *  根據list資料獲取Series資料
     *  [功能詳細描述]
     *  @param jhlist
     *  @param sjlist
     *  @return    
     * @exception/throws [違例型別] [違例說明]
     * @see [類、類#方法、類#成員]
     */
    private List<Series> getSeriesByData(List<Double> jhlist, List<Double> sjlist) {
        List<Series> series = new ArrayList<Series>();

        series.add(new Series("計劃成本", "line", jhlist));
        series.add(new Series("實際成本", "line", sjlist));
        return series;
    }

    public Boolean getDjstatus() {
        return djstatus;
    }

    public void setDjstatus(Boolean djstatus) {
        this.djstatus = djstatus;
    }

    public String getTreecode() {
        return treecode;
    }

    public void setTreecode(String treecode) {
        this.treecode = treecode;
    }

}
<!-- page/costtrend/spcplancosttrend.html -->
<!DOCTYPE html>
<html>
<head>
<title>計劃成本趨勢</title>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="../../../../../fui/js/cssboot.js"></script>
<style type="text/css">
.mini-checkbox {
    font-size: 9pt;
    line-height: 26px;
    position: relative;
    font-family: Microsoft Yahei;
    margin-right: 15px;
}
</style>
</head>
<body>
	<!-- 必須有,載入時的loading效果 -->
	<div class="page-loading"></div>
	<!-- 左側條件區域 -->
	<div class="fui-left">
		<div role="body">
			<ul id="rcj-tree" class="mini-tree" action="getTree" style="width:100%;height:100%;"></ul>
			<input class="mini-hidden" id="treecode" bind="treecode" />
		</div>
	</div>
	<!-- 右側圖表區域 -->
	<div class="fui-right">
		<div class="fui-toolbar">
			<div id="dj-checkbox" bind="djstatus" text="按日期累計" class="mini-checkbox"  onvaluechanged="onDjValueChanged"></div>
		</div>

		<div class="fui-content" style="padding-top: 10px;">
			<div id="main" style="width: 85%; height: 95%; margin-left: 6%"></div>
		</div>
	</div>
	<script src="../../../../../fui/js/jsboot.js"></script>
	<script src="./js/spcplancosttrend.js"></script>
	
</body>
</html>
/*
 * 成本趨勢指令碼(costtrend/spcplancosttrend.js)
 * 介面:spcplancosttrend.html
 */
document.write("<script language=javascript src='../../../../../js/echarts/echarts-all.js'></script>");
var unit = mini.get("unit-combobox");//獲取工程下拉框物件
var mini_rcj_tree = mini.get('rcj-tree')//獲取人材機樹物件
var mini_treecode=mini.get('treecode');//獲取treecode對應的隱藏域
epoint.initPage('spcplancosttrendaction',null,function(data){
	mini.get("dj-checkbox").setValue(true);
	mini_treecode.setValue('0');
	getChart();//預設展示第一個工程下全部的費用的圖表展示
	getChartfunc(data);
	
});
function onunitchanged(){
	getChart();
}

/*
 * 通過點選左側材料樹,圖表資訊切換展示
 */
mini_rcj_tree.on('nodeclick', function(e) {
	mini_treecode.setValue(e.node.id);
	//epoint.alert(e.node.id);
	if(e.node.id.length == 1){
		getChart();
	}else{
		epoint.execute('lineDataClbh', '', [ ], getChartfunc);
	}

})
/*
 * 通過勾選疊加按鈕,圖表資訊切換展示
 */
function onDjValueChanged(){
	if(mini_treecode.getValue().length == 1){
		getChart();		
	}else{
		epoint.execute('lineDataClbh', '', [ ], getChartfunc);
	}
}
/*
 * 根據介面人材機組選擇,顯示圖表資訊
 */
function getChart() {
	epoint.execute('lineData', '', [ ], getChartfunc);
}

/*
 * 圖表資訊展示核心函式
 */
function getChartfunc(result) {
	var myChart = echarts.init(document.getElementById('main'));
	myChart.showLoading({
		text : "圖表資料正在努力載入..."
	});
	
	// 定義圖表options
	options = {
		title : {
			text : '計劃成本趨勢圖'
		},
		tooltip : {
			trigger : 'axis',

		},
		legend : {
			data : []
		},
		grid : {
			left : '3%',
			right : '10%',
			bottom : '3%',
			containLabel : true
		},
		toolbox : {
			right : '35',
			itemSize : 20,
			itemGap : 20,
			feature : {
				saveAsImage : {
					title : '儲存為圖片'
				}
			},

		},
		xAxis : {
			type : 'category',
			boundaryGap : false,
			data : [],
			name:'日期'
		},
		yAxis : {
			type : 'value',
			axisLabel : {
				formatter : '{value} 元'
			},
			name:'金額'
		},
		series : []
	};
	

	// 先把可選項注入myChart中(時間軸)
	options.xAxis.data = result.category;
	
	// 獲取當前月份的資料
	options.series = result.series;
	
	var namearray = new Array();
	if(options.series != 'undefined' && options.series != null){
		for (var i = 0; i < options.series.length; i++) {
			namearray[i] = options.series[i].name;
		}
		options.legend.data = namearray;
	}
	
	myChart.hideLoading();
	myChart.clear();
	myChart.setOption(options);
	// 隨螢幕解析度自適應
	window.onresize = myChart.resize;
}