jinpengyong
2020-04-30 d1f1b489eea7730bb1cb78cdae24c626db835298
src/main/java/com/moral/controller/ReportController.java
@@ -1,16 +1,15 @@
package com.moral.controller;
import static com.moral.common.util.ExportExcelUtils.exportData;
import static com.moral.common.util.WebUtils.getParametersStartingWith;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
@@ -19,80 +18,320 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.moral.common.bean.ResultBean;
import com.moral.common.util.ParameterUtils;
import com.moral.common.util.WebUtils;
import com.moral.entity.Device;
import com.moral.entity.MonitorPoint;
import com.moral.entity.charts.LineChartCriteria;
import com.moral.security.auth.JwtAuthenticationToken;
import com.moral.security.model.UserContext;
import com.moral.service.AlarmDailyService;
import com.moral.service.HistoryDailyService;
import com.moral.service.HistoryMinutelyService;
import com.moral.service.MonitorPointService;
@SuppressWarnings({ "unchecked", "rawtypes" })
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import static com.moral.common.util.ExportExcelUtils.exportData;
import static com.moral.common.util.WebUtils.getParametersStartingWith;
@SuppressWarnings({"unchecked", "rawtypes"})
@RestController
@RequestMapping("report")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ReportController {
   @Resource
   private HistoryMinutelyService historyMinutelyService;
    @Resource
    private HistoryMinutelyService historyMinutelyService;
   @Resource
   private AlarmDailyService alarmDailyService;
   @GetMapping("compare")
   public ResultBean<Map<String, List>> getCompareReport(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      Map<String, List> demo = historyMinutelyService.getCompareReport(parameters);
      return new ResultBean<Map<String, List>>(demo);
   }
    @Resource
    private AlarmDailyService alarmDailyService;
   @PostMapping("line-chart")
   public ResultBean<Map<String, List<List<Double>>>> lineChart(@RequestBody LineChartCriteria lineChartCriteria) {
      return new ResultBean<>(historyMinutelyService.queryLineChartDateByCrieria(lineChartCriteria));
   }
    @Resource
    private MonitorPointService monitorPointService;
   @GetMapping("excel")
   public ResultBean<Boolean> getExcelReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      List<Map<String, Object>> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
      List<String> sensors = (List<String>) parameters.get("sensors");
      String[][] exportColumn = new String[sensors.size() + 1][];
      exportColumn[0] = new String[] { "时间", "20", "time" };
      for (int index = 0; index < sensors.size(); index++) {
         String[] split = sensors.get(index).split("-");
         String name = split[1];
         String key = split[0];
         String unit = split[2];
         if (!ObjectUtils.isEmpty(unit) && !"null".equals(unit)) {
            name += "-" + unit;
         }
         exportColumn[index + 1] = new String[] { name, "10", key };
      }
      OutputStream outputStream = exportData(response, "Excel数据", list, exportColumn);
      outputStream.flush();
      outputStream.close();
      return new ResultBean<Boolean>(true);
   }
   @GetMapping("pie")
   public ResultBean<Map<String, Object>> getPieData(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      Map pieData = alarmDailyService.getPieData(parameters);
      return new ResultBean<Map<String, Object>>(pieData);
   }
    @GetMapping("compare")
    public ResultBean<Map<String, List>> getCompareReport(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map<String, List> demo = historyMinutelyService.getCompareReport(parameters);
        return new ResultBean<Map<String, List>>(demo);
    }
   @GetMapping("alarm-year")
   public ResultBean<List<Integer>> getAlarmDataByYear(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      List<Integer> result = alarmDailyService.getAlarmDataByYear(parameters);
      return new ResultBean<List<Integer>>(result);
   }
    @PostMapping("line-chart")
    public ResultBean<Map<String, List<List<Double>>>> lineChart(@RequestBody LineChartCriteria lineChartCriteria) {
        return new ResultBean<>(historyMinutelyService.queryLineChartDateByCrieria(lineChartCriteria));
    }
   @GetMapping("alarm-month")
   public ResultBean<List<Map<String, Object>>> getAlarmDataByMonth(HttpServletRequest request) throws Exception {
      Map<String, Object> parameters = getParametersStartingWith(request, null);
      List<Map<String, Object>> result = alarmDailyService.getAlarmDataByMonth(parameters);
      return new ResultBean<List<Map<String, Object>>>(result);
   }
    @GetMapping("excel")
    public ResultBean<Boolean> getExcelReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
        List<String> sensors = (List<String>) parameters.get("sensors");
        String[][] exportColumn = new String[sensors.size() + 1][];
        exportColumn[0] = new String[]{"时间", "20", "time"};
        for (int index = 0; index < sensors.size(); index++) {
            String[] split = sensors.get(index).split("-");
            String name = split[1];
            String key = split[0];
            String unit = split[2];
            if (!ObjectUtils.isEmpty(unit) && !"null".equals(unit)) {
                name += "-" + unit;
            }
            exportColumn[index + 1] = new String[]{name, "10", key};
        }
        OutputStream outputStream = exportData(response, "Excel数据", list, exportColumn);
        outputStream.flush();
        outputStream.close();
        return new ResultBean<Boolean>(true);
    }
    @GetMapping("newExcel")
    public ResultBean<Boolean> getNExcelReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
        System.out.println(list);
        String type = parameters.get("type").toString();
        String time = parameters.get("time").toString();
        System.out.println(parameters);
        String timeb = "";
        if (parameters.get("timeb") == null) {
            timeb = parameters.get("time").toString();
        } else {
            timeb = parameters.get("timeb").toString();
        }
        String[] endTimes = timeb.split("-");
        String dateFormat = "";
        String beginTime = "";
        String endTime = "";
        List<String> monthList1 = new ArrayList<>();
        monthList1.add("01");
        monthList1.add("03");
        monthList1.add("05");
        monthList1.add("07");
        monthList1.add("08");
        monthList1.add("10");
        monthList1.add("12");
        List<String> monthList2 = new ArrayList<>();
        monthList2.add("04");
        monthList2.add("06");
        monthList2.add("09");
        monthList2.add("11");
        Integer year = Integer.valueOf(endTimes[0]);
        int i = 0;
        if (type.equals("year")) {
            dateFormat = "yyyy-MM";
            beginTime = time + "-01";
            endTime = timeb + "-12";
            i = Calendar.MONTH;
        } else if (type.equals("month")) {
            dateFormat = "yyyy-MM-dd";
            beginTime = time + "-01";
            i = Calendar.DAY_OF_MONTH;
            if (monthList1.contains(endTimes[1])) {
                endTime = timeb + "-31";
            } else if (monthList2.contains(endTimes[1])) {
                endTime = timeb + "-30";
            } else {
                if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                    endTime = timeb + "-29";
                } else {
                    endTime = timeb + "-28";
                }
            }
        } else if (type.equals("day")) {
            dateFormat = "yyyy-MM-dd HH";
            beginTime = time + " 00";
            endTime = timeb + " 23";
            i = Calendar.HOUR_OF_DAY;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(beginTime));
        ArrayList<Map<String, Object>> resultList = new ArrayList<>();
        for (long d = cal.getTimeInMillis(); d <= sdf.parse(endTime).getTime(); cal.set(i, cal.get(i) + 1), d = cal.getTimeInMillis()) {
            String format = sdf.format(d);
            Map<String, Object> map = new HashMap<>();
            map.put("time", format);
            resultList.add(map);
        }
        for (Map<String, Object> map : resultList) {
            for (Map<String, Object> resultMap : list) {
                if (resultMap.get("time").equals(map.get("time"))) {
                    map.putAll(resultMap);
                }
            }
        }
        List<String> sensors = (List<String>) parameters.get("sensors");//[e1,e2]
        String[][] exportColumn = new String[sensors.size() + 1][];
        exportColumn[0] = new String[]{"时间", "20", "time"};
        for (
                int index = 0; index < sensors.size(); index++) {
            String[] split = sensors.get(index).split("-");
            String name = split[1];
            String key = split[0];
            String unit = split[2];
            if (!ObjectUtils.isEmpty(unit) && !"null".equals(unit)) {
                name += "-" + unit;
            }
            exportColumn[index + 1] = new String[]{name, "10", key};
        }
        OutputStream outputStream = exportData(response, "Excel数据", resultList, exportColumn);
        outputStream.flush();
        outputStream.close();
        return new ResultBean<Boolean>(true);
    }
    @GetMapping("pie")
    public ResultBean<Map<String, Object>> getPieData(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map pieData = alarmDailyService.getPieData(parameters);
        return new ResultBean<Map<String, Object>>(pieData);
    }
    @GetMapping("alarm-year")
    public ResultBean<List<Integer>> getAlarmDataByYear(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Integer> result = alarmDailyService.getAlarmDataByYear(parameters);
        return new ResultBean<List<Integer>>(result);
    }
    @GetMapping("alarm-month")
    public ResultBean<List<Map<String, Object>>> getAlarmDataByMonth(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> result = alarmDailyService.getAlarmDataByMonth(parameters);
        return new ResultBean<List<Map<String, Object>>>(result);
    }
    @Resource
    private HistoryDailyService historyDailyService;
    @GetMapping("emissions")
    public ResultBean<List<Map<String, Object>>> getemissionsData(HttpServletRequest request, JwtAuthenticationToken token) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        UserContext userContext = token.getPrincipal();
        Integer orgId = userContext.getOrganizationId();
        parameters.put("orgId", orgId);
        List<Map<String, Object>> result = historyDailyService.getEmissionsData(parameters);
        return new ResultBean<List<Map<String, Object>>>(result);
    }
    @GetMapping("overproof")
    public ResultBean<Map> getOverproofData(HttpServletRequest request, JwtAuthenticationToken token) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        UserContext userContext = token.getPrincipal();
        Integer orgId = userContext.getOrganizationId();
        parameters.put("orgId", orgId);
        //List<Map<String, Object>> result = null;
        Map result = historyDailyService.getOverproofData(parameters);
        return new ResultBean<Map>(result);
    }
    @GetMapping("custom-made-excel")
    public ResultBean<Boolean> getCustomMadeExcelReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        ParameterUtils.getTimeType4Time(parameters);
        String sensorsInfo = parameters.get("sensors").toString();
        String[] sensorsStr = sensorsInfo.split(",");
        List<String> sensorKeys = new ArrayList<>();
        List<String> sensorKeysNames = new ArrayList<>();
        List<String> sensorKeysUnits = new ArrayList<>();
        for (int index = 0; index < sensorsStr.length; index++) {
            String[] split = sensorsStr[index].split("-");
            String key;
            if (index == 0) {
                key = split[0].replace("\"", "").substring(1);
            } else {
                key = split[0].replace("\"", "");
            }
            String name = split[1].replace("\"", "");
            String Unit = split[2].replace("\"", "");
            sensorKeys.add(key);
            sensorKeysNames.add(name);
            sensorKeysUnits.add(Unit);
        }
        parameters.put("sensorKeys", sensorKeys);
        List<String> macList = new ArrayList<>();
        List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsAndDevicesByRegion(parameters);
        for (MonitorPoint m : monitorPoints) {
            for (Device d : m.getDevices()) {
                macList.add(d.getMac());
            }
        }
        parameters.put("macs", macList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(macList)) {
            list = historyMinutelyService.getDevicesSensorsAvgDataToExcel(parameters);
        }
        List<List<Map<String, Object>>> sheets = new ArrayList<>();
        for (int i = 0; i < sensorKeys.size(); i++) {
            List<Map<String, Object>> sheet = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                Map<String, Object> data = new LinkedHashMap<>();
                for (Map.Entry<String, Object> kv : list.get(j).entrySet()) {
                    if ("monitorPointName".equals(kv.getKey())) {
                        data.put("站点名称(单位:" + sensorKeysUnits.get(i) + ")", kv.getValue());
                    } else if ("name".equals(kv.getKey())) {
                        data.put("设备名称", kv.getValue());
                    } else {
                        String sensorsValue = kv.getValue().toString();
                        JSONObject jsonObject = JSONObject.parseObject(sensorsValue);
                        if (jsonObject != null) {
                            List<Object> sensorsValueList = (List<Object>) jsonObject.get(sensorKeys.get(i));
                            if (sensorsValueList != null) {
                                data.put(kv.getKey(), sensorsValueList.get(0));
                            } else {
                                data.put(kv.getKey(), "");
                            }
                        } else {
                            data.put(kv.getKey(), "");
                        }
                    }
                }
                sheet.add(data);
            }
            sheets.add(sheet);
        }
        if (!CollectionUtils.isEmpty(sheets)) {
            ExcelWriter writer = new ExcelWriter(false, sensorKeysNames.get(0));
            writer.write(sheets.get(0), true);
            writer.autoSizeColumnAll();
            writer.setColumnWidth(0, 25);
            writer.setColumnWidth(1, 25);
            if (sheets.size() >= 2) {
                for (int i = 1; i < sheets.size(); i++) {
                    writer.setSheet(sensorKeysNames.get(i));
                    writer.write(sheets.get(i), true);
                    writer.autoSizeColumnAll();
                    writer.setColumnWidth(0, 25);
                    writer.setColumnWidth(1, 25);
                }
            }
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String codedFileName = java.net.URLEncoder.encode("Excel数据", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + codedFileName + ".xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer,释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
        return new ResultBean<>(true);
    }
}