使用laydate和echarts做資料統計
阿新 • • 發佈:2019-01-08
1.頁面
2.controller層<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>摘星</title> <meta name="keywords" content="設定關鍵詞..." /> <meta name="description" content="設定描述..." /> <meta name="author" content="DeathGhost" /> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"> <link rel="icon" href="static/base/images/icon/favicon.ico" type="image/x-icon"> <link rel="stylesheet" type="text/css" href="../static/base/javascript/plug-ins/layerUi/mobile/need/layer.css" /> <link rel="stylesheet" type="text/css" href="../static/base/css/style.css" /> <style> .line{ height:1px;margin:0px auto;padding:0px;background-color:black;overflow:hidden; } .kuangkuang{ width: 22%; height: 159px; border-style: solid; border-width: 1px; float: left; border-color:rgb(201,201,201); } .kuangkuang-up{ line-height:96px; text-align: center; font-size: 32px; position: relative; } .kuangkuang-down{ text-align: center; line-height: 65px; font-size: 20px; background-color: rgb(233, 233, 233); } </style> </head> <body style="width: 100%;height: 120%"> <br> <div class="page-container"> <div style="height:159px;text-align:center;"> <div class="kuangkuang" style="margin-left:2%;"> <div class="kuangkuang-down">入庫單</div> <div class="kuangkuang-up" id="rkd"> 0單 </div> </div> <div class="kuangkuang" style="margin-left:2%;"> <div class="kuangkuang-down">出庫單</div> <div class="kuangkuang-up" id="ckd"> 0單 </div> </div> <div class="kuangkuang" style="margin-left:2%;"> <div class="kuangkuang-down">總收入</div> <div class="kuangkuang-up" id="shouru"> 0¥ </div> </div> <div class="kuangkuang" style="margin-left:2%;"> <div class="kuangkuang-down">總支出</div> <div class="kuangkuang-up" id="zhichu"> 0¥ </div> </div> </div> <br> <br> <input type="text" id="stime" placeholder="選擇時間" class="form-control" style="width:140px;float: right;margin-right: 4%;"> <span style="float: right;margin-right:1%;margin-top:5px;">選擇時間:</span> <br> <br> <div id="main1" style="width:45%;height:450px;float:left;"></div> <div id="main2" style="width:45%;height:480px;float:left;"></div> </div> <script src="../static/base/javascript/jquery.js"></script> <script src="../static/base/javascript/plug-ins/layerUi/layer.js"></script> <script src="../static/laydate/laydate.js"></script> <script src="../static/echarts/echarts.min.js"></script> <script src="../static/js/tools.js"></script> <script type="text/javascript"> //日期範圍 laydate.render({ elem: '#stime', type: 'datetime', range: true, done: function(value, date, endDate){ console.log(value); //得到日期生成的值,如:2017-08-18 console.log(date); //得到日期時間物件:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0} console.log(endDate); //得結束的日期時間物件,開啟範圍選擇(range: true)才會返回。物件成員同上。 changedata(date,endDate,2); } }); //給layDate一個預設值 $(document).ready(function () { var now1 = new Date(); now1.setDate(now1.getDate()-7); now1.setHours(0); now1.setMinutes(0); now1.setSeconds(0); now1.setMilliseconds(0); var now2 = new Date(); now2.setHours(23); now2.setMinutes(59); now2.setSeconds(59); var time1 = formatTime(now1,"yyyy-MM-dd hh:mm:ss"); var time2 = formatTime(now2,"yyyy-MM-dd hh:mm:ss"); $("#stime").val(time1 +' - '+ time2); changedata(now1,now2,1); }); function changedata(date,endDate,type){ if(type == 1){ date = formatTime(date, "yyyy-MM-dd hh:mm:ss") endDate = formatTime(endDate, "yyyy-MM-dd hh:mm:ss") }else{ date=date.year+'-'+date.month+'-'+date.date+' '+date.hours+':'+date.minutes+':'+date.seconds endDate=endDate.year+'-'+endDate.month+'-'+endDate.date+' '+endDate.hours+':'+endDate.minutes+':'+endDate.seconds } $.ajax({ type: "POST", url: serverWeb+"home/getKuNameAndCount", data: { date:date, endDate:endDate }, success: function(data){ data = JSON.parse(data); console.log(data); if(data.status){ $("#rkd").html(data.record.rcount + "單") $("#ckd").html(data.record.ccount + "單") $("#shouru").html(data.record.shouru + "¥") $("#zhichu").html(data.record.zhichu + "¥") myChart1.setOption({ xAxis: { data: data.record.xAxis1 }, series: [{ data: data.record.data1 },{ data: data.record.data2 }] }); //這裡設定圖片自適應 window.addEventListener("resize",function(){ myChart1.resize(); }); myChart2.setOption({ xAxis: { data: data.record.xAxis2 }, series: [{ data: data.record.data3 },{ data: data.record.data4 }] }); //這裡設定圖片自適應 window.addEventListener("resize",function(){ myChart2.resize(); }); } } }); } /*---------------------------------樹狀圖------------------------------*/ //基於準備好的dom,初始化echarts例項 var myChart1 = echarts.init(document.getElementById('main1')); // 指定圖表的配置項和資料 var option1 = { title: { text: '出入庫數量' }, tooltip: {}, legend: { bottom:'-1%', data:['入庫量', '出庫量'] }, grid: { left: '3%', right: '4%', bottom: '9%', containLabel: true }, xAxis: { data: ["java基礎","C++程式設計","高等數學","統計學原理","網路原理","三劍客教程"] }, yAxis: {}, series: [{ name: '入庫量', type: 'bar', data: [5, 20, 36, 10, 10, 20] },{ name: '出庫量', type: 'bar', data: [8, 15, 52, 16, 17, 22] }] }; // 使用剛指定的配置項和資料顯示圖表。 myChart1.setOption(option1); /*---------------------------------折線圖--------------------------------*/ var myChart2 = echarts.init(document.getElementById('main2')); option2 = { title: { text: '支出/收入' }, tooltip: { trigger: 'axis' }, legend: { bottom:'4%', data:['收入','支出'] }, grid: { left: '3%', right: '4%', bottom: '9%', containLabel: true }, toolbox: { feature: { saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: [ '2018/1/1', '2018/1/2', '2018/1/3', '2018/1/4', '2018/1/2', '2018/1/3', '2018/1/4' ], axisLabel: { rotate: 45 } }, yAxis: { type: 'value' }, series: [ { name:'收入', type:'line', data:[0, 0, 0, 0, 0, 0, 0] },{ name:'支出', type:'line', data:[0, 0, 0, 0, 0, 0, 0] } ] }; myChart2.setOption(option2); /*---------------------------------------------------------------*/ </script> </body> </html>
3.service層package com.project.controller; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.project.service.ICangkuService; import com.project.service.IRecordService; import com.project.utils.DateUtil; import com.project.utils.JSONFZ; /** * 前端控制器 */ @Controller @RequestMapping("/home") public class HomeController extends BaseController{ private Logger logger= Logger.getLogger(HomeController.class); @Autowired private ICangkuService cangkuService; @Autowired private IRecordService recordService; //得到出入庫產品名稱和數量 @RequestMapping("/getKuNameAndCount") @ResponseBody public String getKuNameAndCount(HttpServletRequest request, HttpServletResponse response) { logger.info("get引數 : " + JSON.toJSONString(request.getParameterMap())); String dates = request.getParameter("date"); String endDates = request.getParameter("endDate"); Date startDate = null; Date endDate = null; if(StringUtils.isNotBlank(dates)){ startDate = DateUtil.parseDate(dates); } if(StringUtils.isNotBlank(endDates)){ endDate = DateUtil.parseDate(endDates); } try { JSONObject jsonobject = cangkuService.getKuNameAndCount(startDate, endDate); return new JSONFZ().put("status", true).put("record", jsonobject).toJSONString(); } catch (Exception e) { e.printStackTrace(); return new JSONFZ().put("status", false).toJSONString(); } } }
public JSONObject getKuNameAndCount(Date startDate, Date endDate) { JSONObject jsonobject = new JSONObject(); //1.查詢入庫單,出庫單,收入和支出 EntityWrapper<Record> rWrapper = new EntityWrapper<Record>(); rWrapper.between("createTime", startDate, endDate); List<Record> rList = recordMapper.selectList(rWrapper); int rcount = 0,ccount = 0; BigDecimal shouru = new BigDecimal(0); BigDecimal zhichu = new BigDecimal(0); Calendar cal1 = Calendar.getInstance(); for (Record record : rList) { if(record.getType() == 4){ //出庫 ccount++; shouru =record.getTotalpriced().add(shouru); }else{ //入庫 rcount++; zhichu =record.getTotalpriced().add(zhichu); } //將createTime的時分秒去掉 cal1.setTime(record.getCreateTime()); // 將時分秒,毫秒域清零 cal1.set(Calendar.HOUR_OF_DAY, 0); cal1.set(Calendar.MINUTE, 0); cal1.set(Calendar.SECOND, 0); cal1.set(Calendar.MILLISECOND, 0); record.setCreateTime(cal1.getTime()); } jsonobject.put("rcount", rcount); jsonobject.put("ccount", ccount); jsonobject.put("zhichu", zhichu); jsonobject.put("shouru", shouru); //2.折線圖資料,精確到天 /*List<String> zxname = rList.stream() .map(s -> DateUtil.format(s.getCreateTime())).distinct() .sorted() .collect(Collectors.toList());*/ List<String> zxname = Lists.newArrayList(); cal1.setTime(startDate); boolean bContinue = true; while(bContinue){ cal1.add(Calendar.DAY_OF_MONTH, 1); if (endDate.after(cal1.getTime())) { zxname.add(DateUtil.format(cal1.getTime())); }else{ bContinue = false; } } List<BigDecimal> total1 = Lists.newArrayList(); List<BigDecimal> total2 = Lists.newArrayList(); for (String name : zxname) { BigDecimal shourun = new BigDecimal(0); BigDecimal zhichun = new BigDecimal(0); for (Record record : rList) { if(StringUtils.equals(name, DateUtil.format(record.getCreateTime()))){ if(record.getType() == 4){ //出庫,即收入 shourun = shourun.add(record.getTotalpriced()); }else{ //入庫,即支出 zhichun = zhichun.add(record.getTotalpriced()); } } } total1.add(shourun); total2.add(zhichun); //去掉後面的時分秒 name = name.substring(0,name.indexOf(" ")); } List<String> xAxis2 = zxname.stream() .map(s -> s.substring(0, s.indexOf(" "))) .collect(Collectors.toList()); jsonobject.put("xAxis2", xAxis2); jsonobject.put("data3", total1); jsonobject.put("data4", total2); //3.查找出所有在當前時間範圍內的產品名稱(包括出庫和入庫) EntityWrapper<RecordProduct> rpWrapper = new EntityWrapper<RecordProduct>(); rpWrapper.between("createTime", startDate, endDate); List<RecordProduct> rpList = recordProductService.selectList(rpWrapper); List<String> pName = rpList.stream() .map(s-> s.getProductName()).distinct() .collect(Collectors.toList()); //3.根據type(出庫/入庫)分組 Map<Integer, List<RecordProduct>> rpMap = rpList.stream().collect( Collectors.groupingBy(RecordProduct::getType)); List<RecordProduct> ckRPList = rpMap.get(1); List<RecordProduct> rkRPList = rpMap.get(2); jsonobject.put("xAxis1", pName); List<Long> value1 = Lists.newArrayList(); List<Long> value2 = Lists.newArrayList(); for (String rpName : pName) { Long sum1 = ckRPList.stream() .filter(s -> StringUtils.equals(rpName, s.getProductName())) .mapToLong(RecordProduct :: getCount).sum(); value1.add(sum1); Long sum2 = rkRPList.stream() .filter(s -> StringUtils.equals(rpName, s.getProductName())) .mapToLong(RecordProduct :: getCount).sum(); value2.add(sum2); } Long[] v1 = (Long[])value1.toArray(new Long[value1.size()]); Long[] v2 = (Long[])value2.toArray(new Long[value2.size()]); jsonobject.put("data1", v1); jsonobject.put("data2", v2); return jsonobject; }