TBCarGasConsumptionController.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package cn.com.lzt.oilconsumption.controller;
  2. import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
  3. import cn.afterturn.easypoi.excel.entity.ExportParams;
  4. import cn.com.lzt.common.util.DateUtil;
  5. import cn.com.lzt.common.util.StringUtil;
  6. import cn.com.lzt.oilconsumption.entity.*;
  7. import cn.com.lzt.oilconsumption.service.TBCarGasRefuelService;
  8. import cn.com.lzt.useractiviti.data.controller.ActivitiToolsController;
  9. import com.alibaba.fastjson.JSONObject;
  10. import com.daju.mix.dao.entity.TBAlarm;
  11. import com.daju.mix.entity.CarMileageInfo;
  12. import com.daju.mix.vendor.dao.entity.ECarMil;
  13. import com.daju.mix.vendor.service.ECarVehicleService;
  14. import org.apache.commons.collections.CollectionUtils;
  15. import org.apache.commons.lang.StringUtils;
  16. import org.apache.poi.hssf.usermodel.HSSFRow;
  17. import org.apache.poi.hssf.usermodel.HSSFSheet;
  18. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  19. import org.apache.poi.ss.usermodel.CellStyle;
  20. import org.jeecgframework.core.common.model.json.DataGrid;
  21. import org.jeecgframework.core.common.service.CommonService;
  22. import org.jeecgframework.core.util.ResourceUtil;
  23. import org.jeecgframework.tag.core.easyui.TagUtil;
  24. import org.jeecgframework.web.system.service.SystemService;
  25. import org.springframework.beans.factory.annotation.Autowired;
  26. import org.springframework.stereotype.Controller;
  27. import org.springframework.ui.ModelMap;
  28. import org.springframework.validation.ObjectError;
  29. import org.springframework.web.bind.annotation.RequestMapping;
  30. import org.springframework.web.servlet.ModelAndView;
  31. import javax.annotation.Resource;
  32. import javax.servlet.ServletOutputStream;
  33. import javax.servlet.http.HttpServletRequest;
  34. import javax.servlet.http.HttpServletResponse;
  35. import java.io.OutputStream;
  36. import java.math.BigDecimal;
  37. import java.math.BigInteger;
  38. import java.net.URLEncoder;
  39. import java.text.ParseException;
  40. import java.text.SimpleDateFormat;
  41. import java.util.*;
  42. import java.util.logging.Logger;
  43. import java.util.stream.Collectors;
  44. @Controller
  45. @RequestMapping("/tBCarGasConsumptionController")
  46. public class TBCarGasConsumptionController extends ActivitiToolsController {
  47. private static final Logger logger = Logger.getLogger(String.valueOf(TBCarGasConsumptionController.class));
  48. @Autowired
  49. private SystemService systemService;
  50. @Resource
  51. private ECarVehicleService eCarVehicleService;
  52. /**
  53. * 车辆加油管理列表 页面跳转
  54. *
  55. * @return
  56. */
  57. @RequestMapping(params = "list")
  58. public ModelAndView list(HttpServletRequest request) {
  59. return new ModelAndView("cn/com/lzt/sign/tbCarGasConsumption/tBCarGasConsumption");
  60. }
  61. /**
  62. * easyui AJAX请求数据
  63. *
  64. * @param request
  65. * @param response
  66. * @param dataGrid
  67. */
  68. @RequestMapping(params = "datagrid")
  69. public void datagrid(TBConsumptionReq tbConsumptionReq, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
  70. String startDateStr = request.getParameter("startDate_begin");
  71. String endDateStr = request.getParameter("startDate_end");
  72. //查询carIdsql拼装 start
  73. StringBuilder carIdSql = new StringBuilder("select gas.car_id,c.type,gas.car_plate from t_b_car_gas_refuel gas left join t_b_car c on gas.car_id=c.id where 1=1");
  74. if (!StringUtil.isEmpty(tbConsumptionReq.getCarPlate())) {
  75. carIdSql.append(" and gas.car_plate='").append(tbConsumptionReq.getCarPlate()).append("'");
  76. }
  77. if (!StringUtil.isEmpty(tbConsumptionReq.getCarType())) {
  78. carIdSql.append(" and c.type='").append(tbConsumptionReq.getCarType()).append("'");
  79. }
  80. if (!StringUtil.isEmpty(startDateStr)) {
  81. carIdSql.append(" and gas.refuel_date>='").append(startDateStr).append(" 00:00:00'");
  82. }
  83. if (!StringUtil.isEmpty(endDateStr)) {
  84. carIdSql.append(" and gas.refuel_date<='").append(endDateStr).append(" 00:00:00'");
  85. }
  86. carIdSql.append(" group by car_id ");
  87. //查询carIdsql拼装 end
  88. List<BigInteger> count = systemService.findListbySql("select count(*) from " + "(" + carIdSql + ") a");
  89. //查询carId列表
  90. String beginRow = String.valueOf((dataGrid.getPage() - 1) * dataGrid.getRows());
  91. carIdSql.append("").append(" limit ").append(beginRow).append(",").append(dataGrid.getRows());
  92. List<Object[]> carIdList = systemService.findListbySql(carIdSql.toString());
  93. //拼装数据
  94. StringBuilder getLastTwoData = new StringBuilder("select quantity,refuel_date from t_b_car_gas_refuel where car_id=? ");
  95. if (!StringUtil.isEmpty(startDateStr)) {
  96. getLastTwoData.append(" and refuel_date>='").append(startDateStr).append(" 00:00:00'");
  97. }
  98. if (!StringUtil.isEmpty(endDateStr)) {
  99. getLastTwoData.append(" and refuel_date<='").append(endDateStr).append(" 00:00:00'");
  100. }
  101. getLastTwoData.append(" order by refuel_date desc");
  102. if (StringUtil.isEmpty(startDateStr) && StringUtil.isEmpty(endDateStr)) {
  103. getLastTwoData.append(" limit 2");
  104. }
  105. List<TBConsumptionRep> reps = new ArrayList<>();
  106. carIdList.forEach(e -> {
  107. List<Object[]> datas = systemService.findListbySql(getLastTwoData.toString().replace("?", "'" + e[0] + "'"));
  108. String startDate = "", endDate = "", allConsumption = "";
  109. if (CollectionUtils.isNotEmpty(datas)) {
  110. double sum = datas.stream().mapToDouble(quantity -> Double.parseDouble(quantity[0].toString())).sum();
  111. allConsumption = Double.toString(sum);
  112. endDate = Optional.ofNullable(datas.get(0)[1]).map(Object::toString).orElse("");
  113. if (datas.size() > 1)
  114. startDate = Optional.ofNullable(datas.get(datas.size() - 1)[1]).map(Object::toString).orElse("");
  115. }
  116. TBConsumptionRep build = build(Optional.ofNullable(e[0]).map(Object::toString).orElse(""),
  117. Optional.ofNullable(e[2]).map(Object::toString).orElse(""), Optional.ofNullable(e[1]).map(Object::toString).orElse(""), startDate, endDate, allConsumption);
  118. reps.add(build);
  119. });
  120. dataGrid.setResults(reps);
  121. dataGrid.setTotal(count.get(0).intValue());
  122. TagUtil.datagrid(response, dataGrid);
  123. }
  124. private TBConsumptionRep build(String carId, String carPlate, String carType, String startDate, String endDate, String allConsumption) {
  125. BigDecimal allMile = BigDecimal.ZERO;
  126. List<String> days = new ArrayList<>();
  127. if (!StringUtil.isEmpty(startDate) && !StringUtil.isEmpty(endDate)) {
  128. try {
  129. days = DateUtil.getDays(startDate, endDate);
  130. } catch (ParseException e) {
  131. e.printStackTrace();
  132. }
  133. } else {
  134. if (!StringUtil.isEmpty(startDate)) days.add(startDate);
  135. if (!StringUtil.isEmpty(endDate)) days.add(endDate);
  136. }
  137. for (String day : days) {
  138. ECarMil<CarMileageInfo> result = eCarVehicleService.request_vehicleTrip(carId, day);
  139. if (result.getCode() == 0) {
  140. String mile = result.getData().getMileage();
  141. allMile = allMile.add(new BigDecimal(mile));
  142. }
  143. }
  144. TBConsumptionRep tbConsumptionRep = new TBConsumptionRep();
  145. tbConsumptionRep.setCarPlate(carPlate);
  146. tbConsumptionRep.setCarType(carType);
  147. tbConsumptionRep.setStartDate(startDate);
  148. tbConsumptionRep.setEndDate(endDate);
  149. tbConsumptionRep.setMileages(allMile.toString());
  150. tbConsumptionRep.setAllConsumption(allConsumption);
  151. if (!StringUtil.isEmpty(allConsumption) && !allMile.equals(BigDecimal.ZERO)) {
  152. BigDecimal all = new BigDecimal(allConsumption);
  153. BigDecimal val = all.divide(allMile, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
  154. tbConsumptionRep.setConsumptionHundred(val.toString());
  155. }
  156. return tbConsumptionRep;
  157. }
  158. /**
  159. * 油耗管理-》车辆油耗统计
  160. *
  161. * @param request
  162. * @param response
  163. * @param dataGrid
  164. * @author 刘梦祥
  165. * @Date 2022年1月6日14:01:30
  166. */
  167. @RequestMapping(params = "newDatagrid")
  168. public void newDatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
  169. try {
  170. queryToTBCarGasRefuel(request, dataGrid);
  171. } catch (Exception e) {
  172. e.printStackTrace();
  173. log.error("车辆油耗统计 error:" + getClass(), e);
  174. }
  175. TagUtil.datagrid(response, dataGrid);
  176. }
  177. /**
  178. * 车辆油耗统计查询主方法
  179. *
  180. * @param request
  181. * @param dataGrid
  182. * @author 刘梦祥
  183. * @Date 2022年1月12日13:17:35
  184. */
  185. public void queryToTBCarGasRefuel(HttpServletRequest request, DataGrid dataGrid) {
  186. String startDateStr = request.getParameter("queryDate_begin");
  187. String endDateStr = request.getParameter("queryDate_end");
  188. String plate = request.getParameter("plate");
  189. String carType = request.getParameter("carType");
  190. String gasStation = request.getParameter("gasStation");
  191. String queryType = request.getParameter("queryType");
  192. // 默认按车辆统计
  193. if (StringUtils.isEmpty(queryType)) {
  194. queryType = "1";
  195. }
  196. Map<String, String> queryTypeMap = new HashMap<>();
  197. queryTypeMap.put("1", "tbcgr.car_id");
  198. queryTypeMap.put("2", "tbc.type");
  199. queryTypeMap.put("3", "tbcgr.gas_station");
  200. String sqlStr = "SELECT\n" +
  201. "\ttbcgr.car_id carId,\n" +
  202. "\tgroup_concat(DISTINCT tbc.plate) plate,\n" +
  203. "\tgroup_concat(DISTINCT tbc.type) carType,\n" +
  204. "\tgroup_concat(DISTINCT tbcgr.gas_station) gasStation,\n" +
  205. "\tMIN(tbcgr.refuel_date) refuelStartTime,\n" +
  206. "\tMAX(tbcgr.refuel_date) refuelEndTime,\n" +
  207. "\tSUM(tbcgr.quantity / 100) quantity,\n" +
  208. "\ttbcmd.totalMileage totalMileage,\n" +
  209. "\tSUM(tbcgr.quantity)/tbcmd.totalMileage baseQuantity,\n" +
  210. "\tSUM(tbcgr.refuel_money / 100) refuelMoney,\n" +
  211. "\ttbcmd.startTime startTime,\n" +
  212. "\ttbcmd.endTime endTime,\n" +
  213. "\tIF(SUM(tbcgr.quantity)/tbcmd.totalMileage > 100,'异常','正常') errStatus\n" +
  214. "FROM\n" +
  215. "\tt_b_car_gas_refuel tbcgr\n" +
  216. "LEFT JOIN t_b_car tbc ON tbc.id = tbcgr.car_id\n" +
  217. "LEFT JOIN (\n" +
  218. "\tSELECT\n" +
  219. "\t\tcar_id,\n" +
  220. "\t\tSUM(mileage) totalMileage,\n" +
  221. "\t\tMIN(date) startTime,\n" +
  222. "\t\tMAX(update_time) endTime\n" +
  223. "\tFROM\n" +
  224. "\t\tt_b_car_mileage_day\n";
  225. // 封装查询时间范围条件
  226. if (StringUtils.isNotEmpty(startDateStr) && StringUtils.isNotEmpty(endDateStr)) {
  227. sqlStr += "where DATE_FORMAT(date,'%Y-%d-%m') >= \"" + startDateStr + "\" and DATE_FORMAT(update_time,'%Y-%d-%m') <= \"" + endDateStr + "\"\n";
  228. }
  229. sqlStr += "\tGROUP BY\n" +
  230. "\t\tcar_id\n" +
  231. "\tORDER BY\n" +
  232. "\t\tMIN(date) DESC\n" +
  233. ") tbcmd ON tbcmd.car_id = tbcgr.car_id\n" +
  234. "\twhere tbc.`enable` = \"1\"\n";
  235. // 封装查询时间范围条件
  236. if (StringUtils.isNotEmpty(startDateStr) && StringUtils.isNotEmpty(endDateStr)) {
  237. sqlStr += "\tand tbcgr.refuel_date BETWEEN \"" + startDateStr + "\" and \"" + endDateStr + "\"\n";
  238. }
  239. // 封装车牌号查询条件
  240. if (StringUtils.isNotEmpty(plate)) {
  241. sqlStr += "\tand tbc.plate like \"%" + plate + "%\"\n";
  242. }
  243. // 封装车辆类型查询条件
  244. if (StringUtils.isNotEmpty(carType)) {
  245. sqlStr += "\tand tbc.type = \"" + carType + "\"\n";
  246. }
  247. // 封装加油站点模糊查询条件
  248. if (StringUtils.isNotEmpty(gasStation)) {
  249. sqlStr += "\tand tbcgr.gas_station like \"%" + gasStation + "%\"\n";
  250. }
  251. sqlStr += "GROUP BY\n" +
  252. "\t" + queryTypeMap.get(queryType) + "\n" +
  253. "ORDER BY\n" +
  254. "\tMIN(tbcgr.refuel_date) DESC ";
  255. List<Map<String, Object>> totalData = systemService.findForJdbc(sqlStr);
  256. dataGrid.setTotal(totalData.size());
  257. Double totalOil = 0.00D;
  258. Double totalMileage = 0.00D;
  259. Double totalMoney = 0.00D;
  260. for (Map<String, Object> totalDataItem : totalData) {
  261. if(totalDataItem.containsKey("quantity") && totalDataItem.get("quantity") != null){
  262. totalOil += Double.parseDouble(String.valueOf(totalDataItem.get("quantity")));
  263. }
  264. if(totalDataItem.containsKey("totalMileage") && totalDataItem.get("totalMileage") != null){
  265. totalMileage += Double.parseDouble(String.valueOf(totalDataItem.get("totalMileage")));
  266. }
  267. if(totalDataItem.containsKey("refuelMoney") && totalDataItem.get("refuelMoney") != null){
  268. totalMoney += Double.parseDouble(String.valueOf(totalDataItem.get("refuelMoney")));
  269. }
  270. }
  271. Map<String, Double> totalDataMap = new HashMap<>();
  272. totalDataMap.put("totalOil", totalOil);
  273. totalDataMap.put("totalMileage", totalMileage);
  274. totalDataMap.put("totalMoney", totalMoney);
  275. totalDataMap.put("queryType", Double.parseDouble(queryType));
  276. dataGrid.setObj(totalDataMap);
  277. // 封装分页条件
  278. sqlStr += "LIMIT " + (dataGrid.getPage() - 1) * dataGrid.getRows() + "," + (dataGrid.getPage()) * dataGrid.getRows() + ";";
  279. List<Map<String, Object>> returndata = systemService.findForJdbc(sqlStr);
  280. dataGrid.setResults(returndata);
  281. }
  282. /**
  283. * 车辆油耗统计导出方法接口
  284. *
  285. * @param request
  286. * @param response
  287. * @param dataGrid
  288. * @param modelMap
  289. * @return
  290. */
  291. @RequestMapping(params = "exportXls")
  292. public void exportXlsByT(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
  293. try {
  294. List<TBCarGasRefuelExcelEntity> list = new ArrayList<>();
  295. // 执行sql查询出所有的车辆类型字段对照
  296. String getCarTypeSqlStr = "select * from t_s_type where typegroupid = (select id from t_s_typegroup where typegroupcode = \"cartype\")";
  297. List<Map<String, Object>> carTypeList = systemService.findForJdbc(getCarTypeSqlStr);
  298. Map<Object, Object> carTypeMap = new HashMap<>();
  299. if (carTypeList.size() > 0) {
  300. for (Map<String, Object> carTypeListItem : carTypeList) {
  301. carTypeMap.put(carTypeListItem.get("typecode"), carTypeListItem.get("typename"));
  302. }
  303. }
  304. queryToTBCarGasRefuel(request, dataGrid);
  305. List<Map<String, Object>> selectData = (List<Map<String, Object>>) dataGrid.getResults();
  306. if (selectData.size() > 0) {
  307. for (Map<String, Object> selectItem : selectData) {
  308. TBCarGasRefuelExcelEntity tbCarGasRefuelExcelEntity = JSONObject.parseObject(JSONObject.toJSONString(selectItem), TBCarGasRefuelExcelEntity.class);
  309. tbCarGasRefuelExcelEntity.setCarType(String.valueOf(carTypeMap.get(tbCarGasRefuelExcelEntity.getCarType())));
  310. list.add(tbCarGasRefuelExcelEntity);
  311. }
  312. }
  313. Map<String, Object> queryType = JSONObject.parseObject(JSONObject.toJSONString(dataGrid.getObj()));
  314. int queryTypeI = 0;
  315. if (queryType.containsKey("queryType") && queryType.get("queryType") != null) {
  316. queryTypeI = Integer.parseInt(String.valueOf(queryType.get("queryType")));
  317. }
  318. Map<Integer, String> queryLiNameMap = new HashMap<>();
  319. queryLiNameMap.put(0, "未知统计模式");
  320. queryLiNameMap.put(1, "车牌号");
  321. queryLiNameMap.put(2, "车辆类型");
  322. queryLiNameMap.put(3, "加油点");
  323. HSSFWorkbook wb = new HSSFWorkbook();
  324. HSSFSheet sheet = wb.createSheet("车辆油耗统计");
  325. HSSFRow title = sheet.createRow(0);
  326. title.createCell(0).setCellValue(queryLiNameMap.get(queryTypeI));
  327. title.createCell(1).setCellValue("加油统计开始时间");
  328. title.createCell(2).setCellValue("加油统计结束时间");
  329. title.createCell(3).setCellValue("里程统计开始时间");
  330. title.createCell(4).setCellValue("里程统计结束时间");
  331. title.createCell(5).setCellValue("加油量(L)");
  332. title.createCell(6).setCellValue("加油费(¥)");
  333. title.createCell(7).setCellValue("总里程(Km)");
  334. title.createCell(8).setCellValue("百公里油耗(L/100*Km)");
  335. title.createCell(9).setCellValue("油耗状态");
  336. for (int i = 1; i < list.size() + 1; i++) {
  337. TBCarGasRefuelExcelEntity item = list.get(i - 1);
  338. HSSFRow row = sheet.createRow(i);
  339. String setCellCalueStr = "";
  340. switch (queryTypeI) {
  341. case 1:
  342. setCellCalueStr = item.getPlate();
  343. break;
  344. case 2:
  345. setCellCalueStr = item.getCarType();
  346. break;
  347. case 3:
  348. setCellCalueStr = item.getGasStation();
  349. break;
  350. default:
  351. setCellCalueStr = "未知统计模式";
  352. break;
  353. }
  354. row.createCell(0).setCellValue(setCellCalueStr);
  355. row.createCell(1).setCellValue(toDateStrBySql(item.getRefuelStartTime()));
  356. row.createCell(2).setCellValue(toDateStrBySql(item.getRefuelEndTime()));
  357. row.createCell(3).setCellValue(toDateStrBySql(item.getStartTime()));
  358. row.createCell(4).setCellValue(toDateStrBySql(item.getEndTime()));
  359. row.createCell(5).setCellValue(item.getQuantity());
  360. row.createCell(6).setCellValue(item.getRefuelMoney());
  361. row.createCell(7).setCellValue(item.getTotalMileage());
  362. row.createCell(8).setCellValue(item.getBaseQuantity());
  363. row.createCell(9).setCellValue(item.getErrStatus());
  364. }
  365. HSSFRow totalRow = sheet.createRow(list.size()+2);
  366. totalRow.createCell(0).setCellValue("总计:");
  367. totalRow.createCell(1).setCellValue("");
  368. totalRow.createCell(2).setCellValue("");
  369. totalRow.createCell(3).setCellValue("");
  370. totalRow.createCell(4).setCellValue("");
  371. totalRow.createCell(5).setCellValue(queryType.containsKey("totalOil") && queryType.get("totalOil") != null ? String.valueOf(queryType.get("totalOil")) : "0");
  372. totalRow.createCell(6).setCellValue(queryType.containsKey("totalMoney") && queryType.get("totalMoney") != null ? String.valueOf(queryType.get("totalMoney")) : "0");
  373. totalRow.createCell(7).setCellValue(queryType.containsKey("totalMileage") && queryType.get("totalMileage") != null ? String.valueOf(queryType.get("totalMileage")) : "0");
  374. totalRow.createCell(8).setCellValue("");
  375. totalRow.createCell(9).setCellValue("");
  376. ServletOutputStream servletOutputStream = response.getOutputStream();
  377. response.reset();
  378. response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("车辆油耗统计") + ".xls");
  379. response.setContentType("application/vnd.ms-excel");
  380. wb.write((OutputStream) servletOutputStream);
  381. servletOutputStream.close();
  382. } catch (Exception e) {
  383. e.printStackTrace();
  384. }
  385. }
  386. /**
  387. * 时间戳字符串转时间
  388. * @param sqlTime(秒)
  389. * @return
  390. */
  391. public String toDateStrBySql(String sqlTime){
  392. if(sqlTime != null){
  393. Long time = Long.valueOf(sqlTime);
  394. return new SimpleDateFormat("yyyy-MM-dd").format(new Date(time));
  395. }else{
  396. return "";
  397. }
  398. }
  399. }