From 2b6148810343ad6bace3d3c1a78a121a861b0a70 Mon Sep 17 00:00:00 2001 From: tyty Date: Thu, 27 Jul 2023 10:59:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B0=B4=E7=94=B5=E7=AB=99=E6=9C=88=E6=8A=A5?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hzims/operational/report/vo/CheckChartVo.java | 38 + .../report/vo/MonPowerPercentageVo.java | 43 + .../operational/report/vo/TicketChartCell.java | 23 + .../hzims/operational/report/vo/TicketChartVo.java | 22 + hzims-service/operational/pom.xml | 6 + .../service/impl/ImsDutyEmergencyServiceImpl.java | 3 + .../main/controller/AreaMonthReportController.java | 16 + .../main/service/IAreaMonthReportService.java | 3 + .../service/impl/AreaMonthReportServiceImpl.java | 2183 ++++++++++++-------- .../com/hnac/hzims/operational/util/JFreeUtil.java | 627 +----- .../com/hnac/hzims/operational/util/TimeUtils.java | 121 +- 11 files changed, 1683 insertions(+), 1402 deletions(-) create mode 100644 hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/CheckChartVo.java create mode 100644 hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/MonPowerPercentageVo.java create mode 100644 hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartCell.java create mode 100644 hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartVo.java diff --git a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/CheckChartVo.java b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/CheckChartVo.java new file mode 100644 index 0000000..aba8c73 --- /dev/null +++ b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/CheckChartVo.java @@ -0,0 +1,38 @@ +package com.hnac.hzims.operational.report.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author hx + */ +@Data +@ApiModel("缺陷统计表") +public class CheckChartVo { + @ApiModelProperty(value = "场站名称") + private String deptName; + + @ApiModelProperty(value = "缺陷分类") + private String checkLevel; + @ApiModelProperty(value = "本月-发现缺陷") + private Integer findShortagesMon; + @ApiModelProperty(value = "本月-消缺数") + private Integer shortagesMon; + @ApiModelProperty(value = "本年-发现缺陷") + private Integer findShortagesYear; + @ApiModelProperty(value = "本年-消缺数") + private Integer shortagesYear; + @ApiModelProperty(value = "本年-消缺率") + private Double shortagesRate; + + public CheckChartVo(String deptName, String checkLevel, Integer findShortagesMon, Integer shortagesMon, Integer findShortagesYear, Integer shortagesYear, Double shortagesRate) { + this.deptName=deptName; + this.checkLevel=checkLevel; + this.findShortagesMon=findShortagesMon; + this.shortagesMon=shortagesMon; + this.findShortagesYear=findShortagesYear; + this.shortagesYear=shortagesYear; + this.shortagesRate=shortagesRate; + } +} diff --git a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/MonPowerPercentageVo.java b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/MonPowerPercentageVo.java new file mode 100644 index 0000000..0ca99b7 --- /dev/null +++ b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/MonPowerPercentageVo.java @@ -0,0 +1,43 @@ +package com.hnac.hzims.operational.report.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author ysj + */ +@Data +@ApiModel(value = "水电站发电量同比数据对象") +public class MonPowerPercentageVo { + + @ApiModelProperty(value = "机构Id") + private Long deptId; + + @ApiModelProperty(value = "机构名称") + private String deptName; + + @ApiModelProperty(value = "设备名称") + private String deviceName; + + @ApiModelProperty(value = "年计划发电量") + private Float planPower; + @ApiModelProperty(value = "今年发电量") + private Float powerYear; + @ApiModelProperty(value = "去年发电量") + private Float powerYearBefore; + @ApiModelProperty(value = "当月发电量") + private Float powerMon; + @ApiModelProperty(value = "上个月发电量") + private Float powerMonBefore; + @ApiModelProperty(value = "去年当月发电量") + private Float powerMonYearBefore; + @ApiModelProperty(value = "两年间:年发电量环比") + private Float powerYearPercentage; + @ApiModelProperty(value = "两年间:月发电量环比") + private Float powerMonPercentage; + @ApiModelProperty(value = "年计划完成率") + private Float planPercentage; + + +} diff --git a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartCell.java b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartCell.java new file mode 100644 index 0000000..96d937e --- /dev/null +++ b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartCell.java @@ -0,0 +1,23 @@ +package com.hnac.hzims.operational.report.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author hx + */ +@Data +@ApiModel("两票统计单元格") +public class TicketChartCell { + @ApiModelProperty(value = "票名") + private String ticketName; + @ApiModelProperty(value = "本月数量") + private Integer ticketMon; + @ApiModelProperty(value = "本月合格率") + private Double ticketMonPerc; + @ApiModelProperty(value = "本年数量") + private Integer ticketYear; + @ApiModelProperty(value = "本年合格率") + private Double ticketYeaPercr; +} diff --git a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartVo.java b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartVo.java new file mode 100644 index 0000000..5079d73 --- /dev/null +++ b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/report/vo/TicketChartVo.java @@ -0,0 +1,22 @@ +package com.hnac.hzims.operational.report.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author hx + */ +@Data +@ApiModel("两票统计表") +public class TicketChartVo { + @ApiModelProperty(value = "场站名称") + private String deptName; + + @ApiModelProperty(value = "数量和合格率") + private List chartCells; + + +} diff --git a/hzims-service/operational/pom.xml b/hzims-service/operational/pom.xml index 75b4324..3000a95 100644 --- a/hzims-service/operational/pom.xml +++ b/hzims-service/operational/pom.xml @@ -74,6 +74,12 @@ poi-ooxml-schemas 3.15 + + + org.apache.poi + ooxml-schemas + 1.1 + org.jfree jcommon diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyEmergencyServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyEmergencyServiceImpl.java index 8067b69..4badcdc 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyEmergencyServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyEmergencyServiceImpl.java @@ -80,6 +80,9 @@ public class ImsDutyEmergencyServiceImpl extends BaseServiceImpl { R user = userClient.userInfoById(sig.getRegistrant()); + if (!user.isSuccess()&&ObjectUtils.isNotEmpty(user)){ + + } sig.setRegistrantName(user.getData().getName()); R userR = userClient.userInfoById(sig.getChargePerson()); sig.setChargePersonName(userR.getData().getName()); diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java index a5973f1..cd05d7e 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java @@ -38,6 +38,7 @@ public class AreaMonthReportController extends BladeController { @NotNull private final IAreaMonthReportService service; + private final static String load_hydropower_unit_real_key = "hzims:operation:loadhydropowerunit:real:key"; @ApiLog @ApiOperationSupport(order = 1) @@ -113,5 +114,20 @@ public class AreaMonthReportController extends BladeController { WordUtils.exportWord("template/demo2.docx", "F:/", "生成文件.docx", map); return R.success("测试成功"); } + @ApiLog + @ApiOperationSupport(order = 3) + @ApiOperation("导出水电站月报") + @GetMapping("/exportHydropowerStationMonthReport") + public R exportHydropowerStationMonthReport(HttpServletResponse response, @ApiParam(value = "日期-年", required = true) Integer year,@ApiParam(value = "日期-月", required = true) Integer month,@ApiParam(value = "日期-日", required = true) Integer date,@ApiParam(value = "站点Id", required = true) Long stationId) { + + HashMap map = new HashMap<>(4); + +// map.put("personlist", list); + //word模板相对路径、word生成路径、word生成的文件名称、数据源 + WordUtils.exportWord("template/demo2.docx", "F:/", "生成文件.docx", map); + service.exportHydropowerStationMonthReport(response, map,year,month,date,stationId); + + return R.success("测试成功"); + } } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/IAreaMonthReportService.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/IAreaMonthReportService.java index a678d3c..3cf0c3a 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/IAreaMonthReportService.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/IAreaMonthReportService.java @@ -4,6 +4,7 @@ import com.hnac.hzims.operational.main.vo.AreaMonthReportVo; import org.springblade.core.tool.api.R; import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; import java.util.List; /** @@ -16,4 +17,6 @@ public interface IAreaMonthReportService { R> getReport(String date); R export(HttpServletResponse response, String date); + + R exportHydropowerStationMonthReport(HttpServletResponse response, HashMap map, Integer year, Integer month, Integer date,Long stationId); } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/AreaMonthReportServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/AreaMonthReportServiceImpl.java index 0786826..3aeae6a 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/AreaMonthReportServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/AreaMonthReportServiceImpl.java @@ -1,27 +1,45 @@ package com.hnac.hzims.operational.main.service.impl; +import cn.afterturn.easypoi.entity.ImageEntity; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.hnac.hzims.EquipmentConstants; import com.hnac.hzims.equipment.entity.PlanGenerationEntity; import com.hnac.hzims.equipment.feign.IPlanGenertionClient; +import com.hnac.hzims.equipment.vo.EminfoAndEmParamVo; import com.hnac.hzims.message.dto.MailPushDto; import com.hnac.hzims.message.fegin.IPushMsgClient; +import com.hnac.hzims.operational.defect.constants.TreatMethodConstant; +import com.hnac.hzims.operational.defect.entity.OperPhenomenonEntity; import com.hnac.hzims.operational.defect.service.IOperPhenomenonService; import com.hnac.hzims.operational.main.constant.HomePageConstant; import com.hnac.hzims.operational.main.service.IAreaMonthReportService; +import com.hnac.hzims.operational.main.service.IMainSystemMonitoringService; import com.hnac.hzims.operational.main.service.IMainTaskStatisticService; import com.hnac.hzims.operational.main.vo.AreaMonthReportVo; +import com.hnac.hzims.operational.main.vo.HydropowerUnitRealVo; import com.hnac.hzims.operational.main.vo.MaintainVo; import com.hnac.hzims.operational.main.vo.OverhaulVo; +import com.hnac.hzims.operational.report.vo.CheckChartVo; import com.hnac.hzims.operational.report.vo.DutyDefectVO; +import com.hnac.hzims.operational.report.vo.MonPowerPercentageVo; +import com.hnac.hzims.operational.report.vo.TicketChartCell; import com.hnac.hzims.operational.station.entity.StationEntity; import com.hnac.hzims.operational.station.service.IStationService; +import com.hnac.hzims.operational.util.JFreeUtil; +import com.hnac.hzims.operational.util.TimeUtils; import com.hnac.hzims.safeproduct.dto.SafeEquipmentTrialDTO; import com.hnac.hzims.safeproduct.feign.ISafeCheckClient; import com.hnac.hzims.safeproduct.feign.ISafeEquipmentTrialClient; +import com.hnac.hzims.ticket.standardTicket.entity.StandardTicketInfoEntity; +import com.hnac.hzims.ticket.workTicket.entity.WorkTicketInfoEntity; import com.hnac.hzims.ticket.workTicket.feign.ITicketInfoClient; import com.hnac.hzims.ticket.workTicket.vo.TicketMonthVO; +import com.hnac.hzinfo.datasearch.analyse.vo.AnalyseDataTaosVO; import com.hnac.hzinfo.inspect.task.feign.IInspectTaskReportClient; import com.hnac.hzinfo.inspect.task.vo.DutyInspectTaskVO; import lombok.RequiredArgsConstructor; +import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; @@ -67,858 +85,1315 @@ import java.util.stream.Collectors; @RequiredArgsConstructor public class AreaMonthReportServiceImpl implements IAreaMonthReportService { - @NotNull - private final IMainTaskStatisticService mainTaskStatisticService; - @NotNull - private final IOperPhenomenonService operPhenomenonService; - @NotNull - private final IStationService stationService; - @NotNull - private final IPushMsgClient pushMsgClient; - @NotNull - private final IPlanGenertionClient planGenertionClient; - @NotNull - private final ISysClient sysClient; - @NotNull - private final IUserClient userClient; - @NotNull - private final RedisTemplate redisTemplate; - @NotNull - private final ITicketInfoClient ticketInfoClient; - @NotNull - private final ISafeEquipmentTrialClient safeEquipmentTrialClient; - @NotNull - private final IInspectTaskReportClient inspectTaskReportClient; - @NotNull - private final ISafeCheckClient safeCheckClient; - - - @Value("${hzims.operation.area.report}") - private String area_month_report_key; - - private final static String RECENT_YEAR_POWER_DATA = "hzims:operation:key:power:data"; - - // 线程数量 - private final static int POOL_QUANTITY = 4; - // 日期格式化yyyy-mm-dd hh:mm:ss - private final SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.PATTERN_DATETIME); - // 日期格式化yyyy-mm-dd - private final SimpleDateFormat df = new SimpleDateFormat(DateUtil.PATTERN_DATE); - // 日期格式化yyyy-mm - private final SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM"); - // 时间格式yyyy-mm-dd - private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME); - - /** - * 获取区域月报数据 - * - * @param date - * @return - */ - @Override - public R> getReport(String date) { - List areaMonthReportVoList = this.getAreaMonthReport(date,false); - if (CollectionUtil.isEmpty(areaMonthReportVoList)) { - R.fail("选择月份无统计报表数据"); - } - //根据用户权限获取机构 - return R.data(areaMonthReportVoList.stream().sorted(Comparator.comparing(AreaMonthReportVo::getActualPower,Comparator.reverseOrder())).collect(Collectors.toList())); - } - - /** - * 导出区域月报 - * - * @param response - * @param date - */ - @Override - public R export(HttpServletResponse response, String date) { - List monthReportVoList = this.getAreaMonthReport(date,true); - // 创建Excel文件 - HSSFWorkbook hssWB = new HSSFWorkbook(); - // 添加sheet页 - HSSFSheet sheet = hssWB.createSheet("运行月报(" + date + ")"); - // 行高 - sheet.setDefaultRowHeight((short) (20 * 25)); - // 列宽 - sheet.setDefaultColumnWidth(20); - this.setFirstHeader(hssWB, sheet); - // 第二行/三行 表头格式设置 - this.setWorkHeader(hssWB, sheet); - if (!CollectionUtil.isEmpty(monthReportVoList)) { - // 数据填充 - this.setWorkData(hssWB, sheet, monthReportVoList); - } - - // 下载导出 - String filename = "(" + date + ")水电站生产运行月报"; - // 设置头信息 - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/vnd.ms-excel"); - ServletOutputStream outputStream = null; - try { - //设置xlsx格式 - response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8")); - //创建一个输出流 - outputStream = response.getOutputStream(); - //写入数据 - hssWB.write(outputStream); - // 关闭 - outputStream.close(); - hssWB.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return R.data("success"); - } - - /** - * 首行表头样式 - * - * @param hssWB - * @param sheet - */ - private void setFirstHeader(HSSFWorkbook hssWB, HSSFSheet sheet) { - // 第一行 - HSSFRow fisrtRow = sheet.createRow(0); - this.setTitileStyle(hssWB, fisrtRow, 19, true); - // 第一个单元格 - HSSFCell headCell = fisrtRow.getCell(0); - headCell.setCellValue("集团级水电站生产运行月报"); - // 首行合并情况 - CellRangeAddress region1 = new CellRangeAddress(0, 0, (short) 0, (short) 19); - sheet.addMergedRegion(region1); - } - - /** - * 表头格式设置 - * - * @param hssWB - * @param sheet - */ - private void setWorkHeader(HSSFWorkbook hssWB, HSSFSheet sheet) { - // 创建行 - HSSFRow row_1 = sheet.createRow(1); - this.setTitileStyle(hssWB, row_1, 19, true); - // 第一行 - HSSFCell header_row_1_cell_1 = row_1.getCell(0); - header_row_1_cell_1.setCellValue("区域"); - HSSFCell header_row_1_cell_2 = row_1.getCell(1); - header_row_1_cell_2.setCellValue("生产月报"); - HSSFCell header_row_1_cell_3 = row_1.getCell(15); - header_row_1_cell_3.setCellValue("安全月报"); - - // 第二行 - HSSFRow row_2 = sheet.createRow(2); - this.setTitileStyle(hssWB, row_2, 19, true); - HSSFCell header_row_2_cell_1 = row_2.getCell(1); - header_row_2_cell_1.setCellValue("计划发电量"); - HSSFCell header_row_2_cell_2 = row_2.getCell(2); - header_row_2_cell_2.setCellValue("实际发电量"); - HSSFCell header_row_2_cell_3 = row_2.getCell(3); - - header_row_2_cell_3.setCellValue("发电完成率"); - HSSFCell header_row_2_cell_4 = row_2.getCell(4); - header_row_2_cell_4.setCellValue("同比"); - HSSFCell header_row_2_cell_5 = row_2.getCell(5); - header_row_2_cell_5.setCellValue("发电计划预测"); - HSSFCell header_row_2_cell_6 = row_2.getCell(6); - header_row_2_cell_6.setCellValue("操作票"); - - - HSSFCell header_row_2_cell_7 = row_2.getCell(7); - header_row_2_cell_7.setCellValue("操作票合格率"); - HSSFCell header_row_2_cell_8 = row_2.getCell(8); - header_row_2_cell_8.setCellValue("工作票"); - HSSFCell header_row_2_cell_9 = row_2.getCell(9); - header_row_2_cell_9.setCellValue("工作票合格率"); - - HSSFCell header_row_2_cell_10 = row_2.getCell(10); - header_row_2_cell_10.setCellValue("日常维护"); - HSSFCell header_row_2_cell_11 = row_2.getCell(11); - header_row_2_cell_11.setCellValue("巡检任务"); - HSSFCell header_row_2_cell_12 = row_2.getCell(12); - header_row_2_cell_12.setCellValue("缺陷数"); - - - HSSFCell header_row_2_cell_13 = row_2.getCell(13); - header_row_2_cell_13.setCellValue("消缺率"); - HSSFCell header_row_2_cell_14 = row_2.getCell(14); - header_row_2_cell_14.setCellValue("检修任务"); - HSSFCell header_row_2_cell_15 = row_2.getCell(15); - header_row_2_cell_15.setCellValue("安全生产会议次数"); - - HSSFCell header_row_2_cell_16 = row_2.getCell(16); - header_row_2_cell_16.setCellValue("月度自查报告"); - HSSFCell header_row_2_cell_17 = row_2.getCell(17); - header_row_2_cell_17.setCellValue("设备试验"); - HSSFCell header_row_2_cell_18 = row_2.getCell(18); - header_row_2_cell_18.setCellValue("技能培训"); - HSSFCell header_row_2_cell_19 = row_2.getCell(19); - header_row_2_cell_19.setCellValue("安全大检查"); - - // 表头一:合并情况 - CellRangeAddress header_region_1 = new CellRangeAddress((short) 1, (short) 2, (short) 0, (short) 0); - CellRangeAddress header_region_2 = new CellRangeAddress((short) 1, (short) 1, (short) 1, (short) 14); - CellRangeAddress header_region_3 = new CellRangeAddress((short) 1, (short) 1, (short) 15, (short) 19); - sheet.addMergedRegion(header_region_1); - sheet.addMergedRegion(header_region_2); - sheet.addMergedRegion(header_region_3); - - } - - /** - * 表格数据填充 - * - * @param hssWB - * @param sheet - * @param areaMonthReportVoList - */ - private void setWorkData(HSSFWorkbook hssWB, HSSFSheet sheet, List areaMonthReportVoList) { - int size = areaMonthReportVoList.size(); - for (int i = 0; i < size; i++) { - HSSFRow row = sheet.createRow(i + 3); - this.setTitileStyle(hssWB, row, 19, false); - AreaMonthReportVo areaMonthReportVo = areaMonthReportVoList.get(i); - //区域 - HSSFCell header_row_cell_0 = row.getCell(0); - header_row_cell_0.setCellValue(areaMonthReportVo.getAreaName()); - //计划发电量 - HSSFCell header_row_cell_1 = row.getCell(1); - header_row_cell_1.setCellValue(areaMonthReportVo.getPlanPower()); - //实际发电量 - HSSFCell header_row_cell_2 = row.getCell(2); - header_row_cell_2.setCellValue(areaMonthReportVo.getActualPower()); - - //发电完成率 - HSSFCell header_row_cell_3 = row.getCell(3); - header_row_cell_3.setCellValue(areaMonthReportVo.getPowerFinishRate()); - //同比 - HSSFCell header_row_cell_4 = row.getCell(4); - header_row_cell_4.setCellValue(areaMonthReportVo.getComparePowerRate()); - //发电计划预测 - HSSFCell header_row_cell_5 = row.getCell(5); - header_row_cell_5.setCellValue(areaMonthReportVo.getPredictPlanPower()); - - //操作票 - HSSFCell header_row_cell_6 = row.getCell(6); - header_row_cell_6.setCellValue(areaMonthReportVo.getOperate()); - //操作票合格率 - HSSFCell header_row_cell_7 = row.getCell(7); - header_row_cell_7.setCellValue(areaMonthReportVo.getOperaQualifyRate()); - //工作票 - HSSFCell header_row_cell_8 = row.getCell(8); - header_row_cell_8.setCellValue(areaMonthReportVo.getWork()); - //工作票合格率 - HSSFCell header_row_cell_9 = row.getCell(9); - header_row_cell_9.setCellValue(areaMonthReportVo.getWorkQualifyRate()); - - //日常维护 - HSSFCell header_row_cell_10 = row.getCell(10); - header_row_cell_10.setCellValue(areaMonthReportVo.getRoutineMaintenance()); - //巡检任务 - HSSFCell header_row_cell_11 = row.getCell(11); - header_row_cell_11.setCellValue(areaMonthReportVo.getInspect()); - //缺陷数 - HSSFCell header_row_cell_12 = row.getCell(12); - header_row_cell_12.setCellValue(areaMonthReportVo.getDefect()); - - //消缺率 - HSSFCell header_row_cell_13 = row.getCell(13); - header_row_cell_13.setCellValue(areaMonthReportVo.getDefectRate()); - //检修任务 - HSSFCell header_row_cell_14 = row.getCell(14); - header_row_cell_14.setCellValue(areaMonthReportVo.getMaintenanceTasks()); - //安全生产会议次数 - HSSFCell header_row_cell_15 = row.getCell(15); - header_row_cell_15.setCellValue(areaMonthReportVo.getSafetyMeeting()); - - //月度自查报告 - HSSFCell header_row_cell_16 = row.getCell(16); - header_row_cell_16.setCellValue(areaMonthReportVo.getSelfReport()); - //设备试验 - HSSFCell header_row_cell_17 = row.getCell(17); - header_row_cell_17.setCellValue(areaMonthReportVo.getDeviceTry()); - //技能培训 - HSSFCell header_row_cell_18 = row.getCell(18); - header_row_cell_18.setCellValue(areaMonthReportVo.getSkillTrainy()); - //安全大检查 - HSSFCell header_row_cell_19 = row.getCell(19); - header_row_cell_19.setCellValue(areaMonthReportVo.getSecurityCheck()); - } - } - - /** - * 设置Titile单元格样式 - * - * @param hssWB - * @param row - * @param len - */ - private void setTitileStyle(HSSFWorkbook hssWB, HSSFRow row, int len, boolean isHead) { - HSSFCellStyle cellStyle = getHeadStyle(hssWB, isHead); - for (int i = 0; i <= len; i++) { - HSSFCell hssfcell = row.createCell(i); - hssfcell.setCellStyle(cellStyle); - } - } - - /** - * 获取表头样式 - * - * @param hssWB - * @return - */ - private HSSFCellStyle getHeadStyle(HSSFWorkbook hssWB, boolean isHead) { - HSSFCellStyle headStyle = hssWB.createCellStyle(); - //边框 - headStyle.setBorderLeft(BorderStyle.THIN); - headStyle.setBorderRight(BorderStyle.THIN); - headStyle.setBorderTop(BorderStyle.THIN); - headStyle.setBorderBottom(BorderStyle.THIN); - //居中: - headStyle.setAlignment(HorizontalAlignment.CENTER); // 居中 - headStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中 - //字体: - HSSFFont font = hssWB.createFont(); - font.setFontName("黑体"); - if (isHead) { - //设置字体大小 - font.setFontHeightInPoints((short) 12); - //背景颜色 - headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - headStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); - } else { - //设置字体大小 - font.setFontHeightInPoints((short) 8); - //背景颜色 - headStyle.setFillPattern(FillPatternType.NO_FILL); - headStyle.setFillForegroundColor(HSSFColor.WHITE.index); - } - //字体格式 - - headStyle.setFont(font); - return headStyle; - } - - /** - * 获取区域月报数据 - * - * @return - */ - private List getAreaMonthReport(String date,boolean isSendFlag) { - R> D = sysClient.getDeptByCurrentUser(); - if (!D.isSuccess() || CollectionUtil.isEmpty(D.getData())) { - return null; - } - List authList = D.getData().stream().filter(o -> o.getDeptCategory().equals(3)).map(Dept::getId).collect(Collectors.toList()); - if (CollectionUtil.isEmpty(authList)) { - return null; - } - Map> map = (Map>) redisTemplate.opsForValue().get(area_month_report_key); - if (MapUtils.isEmpty(map)) { - return null; - } - if(isSendFlag){ - // 发送邮件 - this.sendMonthReport(map,D.getData()); - } - return map.get(date); - } - - - /** - * 区域-加载月报数据 - * - * @param param - */ - @Override - public void loadMonthReport(String param, int year) { - // 获取所有机构 - R> R = sysClient.getDeptList(); - if (!R.isSuccess() || CollectionUtil.isEmpty(R.getData())) { - return; - } - // 查询所有服务类型——"运维服务"、站点类型——"水电站" - List stationList = stationService.getStationType(HomePageConstant.HYDROPOWER_SERVETYPE, Collections.singletonList(HomePageConstant.HYDROPOWER), null); - if (CollectionUtil.isEmpty(stationList)) { - return; - } - // 站点近年发电数据 - Map> powerMap = (Map>) redisTemplate.opsForValue().get(RECENT_YEAR_POWER_DATA); - // 存储数据节点 key - 月份 value - 区域数据集合 - Map> map = new HashMap<>(); - // 月份集合 - List monthList = getMonthList(year, Calendar.getInstance().get(Calendar.MONTH)); - monthList.forEach(mon -> { - List list = this.getAreaReportByMon(R.getData(), powerMap, stationList, mon); - if (CollectionUtil.isEmpty(list)) { - return; - } - map.put(mon, list); - }); - // 推送当月报表邮件 - this.sendMonthReport(map, R.getData()); - redisTemplate.opsForValue().set(area_month_report_key, map); - } - - /** - * 获取近年月份集合 - * - * @param year - * @return - */ - public static List getMonthList(int year, int endMoth) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM"); - // 开始日期 - Calendar endCal = Calendar.getInstance(); - endCal.setTime(new Date()); - endCal.add(Calendar.MONTH, -endCal.get(Calendar.MONTH) + endMoth); - endCal.add(Calendar.DATE, -endCal.get(Calendar.DATE) + 1); - - // 结束日期 - Calendar startCal = Calendar.getInstance(); - startCal.setTime(new Date()); - startCal.set(Calendar.YEAR, startCal.get(Calendar.YEAR) - year); - startCal.add(Calendar.MONTH, -startCal.get(Calendar.MONTH)); - startCal.add(Calendar.DATE, -startCal.get(Calendar.DATE) + 1); - // 获取日期之间的月份 - List list = new ArrayList<>(); - while (endCal.after(startCal)) { - list.add(format.format(startCal.getTime())); - startCal.add(Calendar.MONTH, 1); - } - list.add(format.format(endCal.getTime())); - return list; - } - - /** - * 区域月报数据加载 - * - * @param deptList - * @param powerMap - * @param stationList - * @param mon - * @return - */ - private List getAreaReportByMon(List deptList, Map> powerMap, List stationList, String mon) { - LocalDateTime startTime = LocalDateTime.parse(mon + "-01 00:00:00", dtf); - LocalDateTime endTime = getEndTime(mon); - // 查询所有站点的计划发电量 - List planList = getPlanPower(stationList, mon); - // 站点实际发电量 - Map actualMap = getActualPower(powerMap, stationList, mon + "-01"); - // 站点去年发电量 - Map oldActualMap = getActualPower(powerMap, stationList, getLastyear(1,mon)); - // 站点前发电量 - Map oldOldActualMap = getActualPower(powerMap, stationList, getLastyear(2,mon)); - // 取机构中区域部分 - List areaList = deptList.stream().filter(o -> o.getDeptCategory().equals(3)).collect(Collectors.toList()); - if (CollectionUtil.isEmpty(areaList)) { - return null; - } - List areaMonthReportVoList = new ArrayList<>(); - areaList.forEach(area -> { - AreaMonthReportVo areaMonthReport = new AreaMonthReportVo(); - areaMonthReport.setAreaId(area.getId()); - areaMonthReport.setAreaName(area.getDeptName()); - // 获取区域下的站点 - List stationIdList = deptList.stream().filter(o -> o.getParentId().equals(area.getId()) && o.getDeptCategory().equals(4)).map(Dept::getId).collect(Collectors.toList()); - List areaStationList = stationList.stream().filter(o -> stationIdList.contains(o.getRefDept())).collect(Collectors.toList()); - if (CollectionUtil.isEmpty(areaStationList)) { - return; - } - // 计划发电量、实际发电量、发电完成率 - this.powerMonth(planList, actualMap, oldActualMap, areaStationList, areaMonthReport); - // 操作票、操作票合格率/ 工作票、工作票合格率 - this.doubleMonth(area, areaMonthReport, mon + "-01 00:00:00", getStrEndTime(mon)); - // 日常维护、巡检任务、缺陷数、消缺率、检修任务 - this.taskMonth(Collections.singletonList(area.getId()), areaMonthReport, mon + "-01 00:00:00", getStrEndTime(mon)); - // 预测 - this.getPredictPlanPower(oldActualMap,oldOldActualMap,areaStationList,areaMonthReport); - // 安全生产会议次数、月度检查报告、技能培训、安全大检查 - this.getSecurityCheck(Collections.singletonList(area.getId()),areaMonthReport,mon + "-01 00:00:00", getStrEndTime(mon)); - // 设备试验 - this.getDeviceTry(mon + "-01 00:00:00", getStrEndTime(mon), Collections.singletonList(area.getId()),areaMonthReport); - areaMonthReportVoList.add(areaMonthReport); - }); - return areaMonthReportVoList; - } - - /** - * 预测发电量 - * @param oldActualMap - * @param oldOldActualMap - * @param areaStationList - * @param areaMonthReport - */ - private void getPredictPlanPower(Map oldActualMap, Map oldOldActualMap, List areaStationList, AreaMonthReportVo areaMonthReport) { - areaMonthReport.setPredictPlanPower(0.0); - // 实际发电量 - List ids = areaStationList.stream().map(StationEntity::getId).collect(Collectors.toList()); - if(CollectionUtil.isEmpty(ids)){ - return; - } - double oldActualPower = oldActualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); - double oldOldActualPower = oldOldActualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); - if(Math.abs(oldActualPower) <= 0 && Math.abs(oldOldActualPower) <= 0 ){ - return; - } - double predictPlanPower = BigDecimal.valueOf((oldActualPower + oldOldActualPower) / 2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - areaMonthReport.setPredictPlanPower(predictPlanPower); - } - - /** - * 推送当月月报 - * - * @param map - * @param list - */ - private void sendMonthReport(Map> map, List list) { - if (MapUtils.isEmpty(map) || CollectionUtil.isEmpty(list)) { - return; - } - // 获取邮件接收人 - Dept dept = list.stream().min(Comparator.comparing(Dept::getDeptCategory)).get(); - if(ObjectUtil.isEmpty(dept)){ - return; - } - R> userR = userClient.userListByDeptAndChildrenWithAuth(dept.getId()); - if(!userR.isSuccess() && CollectionUtil.isEmpty(userR.getData())){ - return; - } - List userList = userR.getData().stream().filter(o->dept.getId().equals(o.getCreateDept())).collect(Collectors.toList()); - if(CollectionUtil.isEmpty(userList)){ - return; - } - List mailList = userList.stream().map(User::getEmail).filter(StringUtil::isNotBlank).collect(Collectors.toList()); - if(CollectionUtil.isEmpty(mailList)){ - return; - } - // 获取月报数据 - List entityList = map.get(ft.format(new Date())); - if (CollectionUtil.isEmpty(entityList)) { - return; - } - // 发送邮件 - MailPushDto pushDto = new MailPushDto(); - pushDto.setBusinessClassify("system"); - pushDto.setBusinessKey("Month_Report"); - pushDto.setSubject("水电站生产运行"); - Map param = new HashMap<>(); - param.put("templatePath", "/data/hzims/message/mail/template/stationRunMonthReport.html"); - Map parameters = new HashMap<>(); - parameters.put("data",entityList); - param.put("parameters", parameters); - pushDto.setExtras(param); - pushDto.setText("水电站生产运行月报内容"); - pushDto.setToAccount(mailList.toArray(new String[0])); - pushDto.setHtml(true); - pushDto.setCreateUser(userR.getData().get(0).getCreateUser()); - pushDto.setTenantId(dept.getTenantId()); - pushDto.setCreateDept(dept.getId()); - pushMsgClient.sendMail(pushDto); - } - - /** - * 获取结束时间 - * - * @param mon - * @return - * @throws ParseException - */ - private LocalDateTime getEndTime(String mon) { - try { - Date date = sdf.parse(mon + "-01 00:00:00"); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.add(Calendar.MONTH, 1); - return calendar.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); - } catch (ParseException e) { - return LocalDateTime.now(); - } - } - - - /** - * 获取结束时间 - * - * @param mon - * @return - * @throws ParseException - */ - private String getStrEndTime(String mon) { - try { - Date date = sdf.parse(mon + "-01 00:00:00"); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.add(Calendar.MONTH, 1); - return sdf.format(calendar.getTime()); - } catch (ParseException e) { - return sdf.format(LocalDateTime.now()); - } - } - - - /** - * 获取站点计划发电量 - * - * @param stationList - * @param mon - * @return - */ - private List getPlanPower(List stationList, String mon) { - List list = stationList.stream().map(StationEntity::getCode).collect(Collectors.toList()); - return planGenertionClient.getPlanGenerationByParam(list, null, mon); - } - - /** - * 获取站点月份实际发电量 - * - * @param stationList - * @return - */ - private Map getActualPower(Map> powerMap, List stationList, String month) { - if (MapUtils.isEmpty(powerMap)) { - return null; - } - // 站点Id集合 - List stationIdList = stationList.stream().map(StationEntity::getId).collect(Collectors.toList()); - // 存储站点实际发电量 - Map actualPowerMap = new HashMap<>(); - stationIdList.forEach(key -> { - Map monthMap = powerMap.get(key); - if (MapUtils.isEmpty(monthMap)) { - return; - } - float actualPower = 0f; - if(ObjectUtil.isNotEmpty(monthMap.get(month))){ - actualPower = monthMap.get(month); - } - actualPowerMap.put(key, actualPower); - }); - return actualPowerMap; - } - - /** - * 区域-月计划发电量、月实际发电量、月发电完成率、同比 - * - * @param planList - * @param actualMap - * @param oldActualMap - * @param areaStationList - * @param areaMonthReport - */ - private void powerMonth(List planList, Map actualMap, Map oldActualMap, List areaStationList, AreaMonthReportVo areaMonthReport) { - // 计划发电量 - List codeList = areaStationList.stream().map(StationEntity::getCode).collect(Collectors.toList()); - double planPower = planList.stream().filter(o -> codeList.contains(o.getStationId())).mapToDouble(PlanGenerationEntity::getPlanGeneration).sum(); - areaMonthReport.setPlanPower(Float.parseFloat(String.valueOf(planPower))); - if (MapUtils.isEmpty(actualMap)) { - areaMonthReport.setActualPower(0f); - areaMonthReport.setPowerFinishRate(0.0); - areaMonthReport.setComparePowerRate(0.0); - return; - } - // 实际发电量 - List ids = areaStationList.stream().map(StationEntity::getId).collect(Collectors.toList()); - double actualPower = actualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); - areaMonthReport.setActualPower(Float.parseFloat(String.valueOf(actualPower))); - if (Math.abs(planPower) <= 0) { - areaMonthReport.setPowerFinishRate(0.0); - } else { - // 发电完成率 - double powerFinishRate = BigDecimal.valueOf(actualPower / planPower * 100).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); - areaMonthReport.setPowerFinishRate(powerFinishRate); - } - // 同比 - double oldActualPower = oldActualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); - if (Math.abs(actualPower) <= 0 || Math.abs(oldActualPower) <= 0) { - areaMonthReport.setComparePowerRate(0.0); - return; - } - double comparePowerRate = BigDecimal.valueOf(actualPower / oldActualPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - areaMonthReport.setComparePowerRate(comparePowerRate); - } - - /** - * 区域-操作票、操作票合格率/ 工作票、工作票合格率 - * - * @param area - * @param areaMonthReport - */ - private void doubleMonth(Dept area, AreaMonthReportVo areaMonthReport, String startTime, String endTime) { - // 站点归属机构集合 - Map map = new HashMap<>(); - map.put("startDate", startTime); - map.put("endDate", endTime); - map.put("deptList", Collections.singletonList(area.getId())); - R R = ticketInfoClient.getOperateWorkStatistic(map); - if (!R.isSuccess() || ObjectUtil.isEmpty(R.getData())) { - areaMonthReport.setOperate(0); - areaMonthReport.setOperaQualifyRate(0.0); - areaMonthReport.setWork(0); - areaMonthReport.setWorkQualifyRate(0.0); - return; - } - TicketMonthVO ticketMonthVO = R.getData(); - // 操作票 - int operate = ticketMonthVO.getOperate(); - int operateQualify = ticketMonthVO.getOperateQualify(); - areaMonthReport.setOperate(operate); - if (operateQualify <= 0) { - areaMonthReport.setOperaQualifyRate(0.0); - } else { - double operateQualifyRate = BigDecimal.valueOf(operateQualify / (double) operate * 100L).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); - areaMonthReport.setOperaQualifyRate(operateQualifyRate); - } - //工作票 - int work = ticketMonthVO.getWork(); - int workQualify = ticketMonthVO.getWorkQualify(); - areaMonthReport.setWork(work); - if (workQualify <= 0) { - areaMonthReport.setWorkQualifyRate(0.0); - } else { - double workQualifyRate = BigDecimal.valueOf(workQualify / (double) work * 100L).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); - areaMonthReport.setWorkQualifyRate(workQualifyRate); - } - } - - /** - * 任务月报-日常维护、巡检任务、缺陷数、消缺率、检修任务 - * - * @param areas - * @param areaMonthReport - */ - private void taskMonth(List areas, AreaMonthReportVo areaMonthReport, String startTime, String endTime) { - //通过线程池异步获取月报各模块内容 主要分为五块内容 - ExecutorService exe = Executors.newFixedThreadPool(POOL_QUANTITY); - //监控线程执行完后返回结果 - CountDownLatch countDownLatch = new CountDownLatch(POOL_QUANTITY); - // 日常维护 - exe.execute(() -> { - MaintainVo maintainVo = mainTaskStatisticService.getMaintain(startTime, endTime, areas); - int maintainSum = maintainVo.getMaintain(); - areaMonthReport.setRoutineMaintenance(maintainSum); - countDownLatch.countDown(); - }); - - // 巡检任务 - exe.execute(() -> { - Map map = new HashMap<>(); - map.put("startDate", startTime); - map.put("endDate", endTime); - map.put("deptList", areas); - R R = inspectTaskReportClient.getDutyInspectTask(map); - if (!R.isSuccess() || ObjectUtil.isEmpty(R.getData())) { - areaMonthReport.setInspect(0); - } else { - int inspect = R.getData().getInspectTaskSum(); - areaMonthReport.setInspect(inspect); - } - countDownLatch.countDown(); - }); - - // 消缺 - exe.execute(() -> { - DutyDefectVO defectVO = operPhenomenonService.getDutyDefect(startTime, endTime, areas); - int defectSum = defectVO.getDefectSum(); - int defect = defectVO.getDefect(); - areaMonthReport.setDefect(defectSum); - if (defectSum <= 0) { - areaMonthReport.setDefectRate(0.0); - } else { - double deletionRate = BigDecimal.valueOf(defect / defectSum * 100L).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); - areaMonthReport.setDefectRate(deletionRate); - } - countDownLatch.countDown(); - }); - - // 检修 - exe.execute(() -> { - OverhaulVo overhaulVo = mainTaskStatisticService.getOverhaul(startTime, endTime, areas); - int overhaul = overhaulVo.getOverhaul(); - areaMonthReport.setMaintenanceTasks(overhaul); - countDownLatch.countDown(); - }); - - //所有模板数据获取完成后释放锁 - try { - countDownLatch.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - Thread.currentThread().interrupt(); - } - exe.shutdown(); - } - - /** - * 安全检查 - * @param areas - * @param areaMonthReport - * @param startTime - * @param endTime - */ - private void getSecurityCheck(List areas, AreaMonthReportVo areaMonthReport,String startTime,String endTime) { - areaMonthReport.setSafetyMeeting(0); - areaMonthReport.setSelfReport(0); - areaMonthReport.setSkillTrainy(0); - areaMonthReport.setSecurityCheck(0); - // 站点归属机构集合 - Map map = new HashMap<>(); - map.put("startDate", startTime); - map.put("endDate", endTime); - map.put("deptList", areas); - // 调用安全大检查fegin接口 - R> R = safeCheckClient.getCount(map); - if(!R.isSuccess() || MapUtils.isEmpty(R.getData())){ - return; - } - // 安全生产会议 - areaMonthReport.setSafetyMeeting((Integer) R.getData().get("safetyMeetingNum")); - // 月度自查报告 - areaMonthReport.setSelfReport((Integer) R.getData().get("monthCheckNum")); - // 技能培训 - areaMonthReport.setSkillTrainy((Integer) R.getData().get("skillsTrainingNum")); - // 安全大检查 - areaMonthReport.setSecurityCheck((Integer) R.getData().get("bigCheckNum")); - } - - /** - * 获取设备试验数据 - * @param startTime - * @param endTime - * @param areas - * @param areaMonthReport - */ - private void getDeviceTry(String startTime,String endTime,List areas,AreaMonthReportVo areaMonthReport) { - areaMonthReport.setDeviceTry(0); - SafeEquipmentTrialDTO request = new SafeEquipmentTrialDTO(); - request.setDeptList(areas); - request.setStartTime(startTime); - request.setEndTime(endTime); - R R = safeEquipmentTrialClient.getCount(request); - if(!R.isSuccess() || ObjectUtil.isEmpty(R.getData())){ - return; - } - areaMonthReport.setDeviceTry(R.getData()); - } - - /** - * 获取去年时间 - * - * @return - */ - private String getLastyear(int year,String mon) { - try { - Date date = sdf.parse(mon + "-01 00:00:00"); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - year); - calendar.add(Calendar.DATE, -calendar.get(Calendar.DATE) + 1); - return df.format(calendar.getTime()); - } catch (ParseException e) { - return mon; - } - } + @NotNull + private final IMainTaskStatisticService mainTaskStatisticService; + @NotNull + private final IOperPhenomenonService operPhenomenonService; + @NotNull + private final IStationService stationService; + @NotNull + private final IPushMsgClient pushMsgClient; + @NotNull + private final IPlanGenertionClient planGenertionClient; + @NotNull + private final SideHustleServiceImpl sideHustleService; + @NotNull + private final AnalyseDataServiceImpl analyseDataService; + @NotNull + private final IMainSystemMonitoringService mainSystemMonitoringService; + @NotNull + private final ISysClient sysClient; + @NotNull + private final IUserClient userClient; + @NotNull + private final RedisTemplate redisTemplate; + @NotNull + private final ITicketInfoClient ticketInfoClient; + @NotNull + private final ISafeEquipmentTrialClient safeEquipmentTrialClient; + @NotNull + private final IInspectTaskReportClient inspectTaskReportClient; + @NotNull + private final ISafeCheckClient safeCheckClient; + + + + + @Value("${hzims.operation.area.report}") + private String area_month_report_key; + + private final static String RECENT_YEAR_POWER_DATA = "hzims:operation:key:power:data"; + private final static String load_hydropower_unit_real_key = "hzims:operation:loadhydropowerunit:real:key"; + private final static String load_hydropower_unit_target_key = "hzims:operation:loadhydropowerunit:target:key"; + private final static String recent_year_power_data = "hzims:operation:key:power:data"; + + // 线程数量 + private final static int POOL_QUANTITY = 4; + // 日期格式化yyyy-mm-dd hh:mm:ss + private final SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.PATTERN_DATETIME); + // 日期格式化yyyy-mm-dd + private final SimpleDateFormat df = new SimpleDateFormat(DateUtil.PATTERN_DATE); + // 日期格式化yyyy-mm + private final SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM"); + // 时间格式yyyy-mm-dd + private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME); + + /** + * 获取区域月报数据 + * + * @param date + * @return + */ + @Override + public R> getReport(String date) { + List areaMonthReportVoList = this.getAreaMonthReport(date, false); + if (CollectionUtil.isEmpty(areaMonthReportVoList)) { + R.fail("选择月份无统计报表数据"); + } + //根据用户权限获取机构 + return R.data(areaMonthReportVoList.stream().sorted(Comparator.comparing(AreaMonthReportVo::getActualPower, Comparator.reverseOrder())).collect(Collectors.toList())); + } + + /** + * 导出区域月报 + * + * @param response + * @param date + */ + @Override + public R export(HttpServletResponse response, String date) { + List monthReportVoList = this.getAreaMonthReport(date, true); + // 创建Excel文件 + HSSFWorkbook hssWB = new HSSFWorkbook(); + // 添加sheet页 + HSSFSheet sheet = hssWB.createSheet("运行月报(" + date + ")"); + // 行高 + sheet.setDefaultRowHeight((short) (20 * 25)); + // 列宽 + sheet.setDefaultColumnWidth(20); + this.setFirstHeader(hssWB, sheet); + // 第二行/三行 表头格式设置 + this.setWorkHeader(hssWB, sheet); + if (!CollectionUtil.isEmpty(monthReportVoList)) { + // 数据填充 + this.setWorkData(hssWB, sheet, monthReportVoList); + } + + // 下载导出 + String filename = "(" + date + ")水电站生产运行月报"; + // 设置头信息 + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/vnd.ms-excel"); + ServletOutputStream outputStream = null; + try { + //设置xlsx格式 + response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8")); + //创建一个输出流 + outputStream = response.getOutputStream(); + //写入数据 + hssWB.write(outputStream); + // 关闭 + outputStream.close(); + hssWB.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return R.data("success"); + } + + @Override + public R exportHydropowerStationMonthReport(HttpServletResponse response, HashMap map, Integer year, Integer month, Integer date, Long deptId) { + R deptNameR = sysClient.getDeptName(deptId); + if (!deptNameR.isSuccess()) { + return R.fail("暂无该机构"); + } + String deptName = deptNameR.getData(); + R> deptR = sysClient.getDeptByType("200000", deptId, 4); + if (!deptR.isSuccess()||deptR.getData()==null) { + return R.fail("该机构不包含水站信息"); + } + List deptList = deptR.getData().stream().filter(s -> s.getStationId() != null).collect(Collectors.toList()); + if (deptList==null) { + return R.fail("该机构不包含水站信息"); + } + List deptIds = deptList.stream().map(s -> s.getId()).collect(Collectors.toList()); + //其它普通数据 + map.put("year", year); + Integer yearBefore = year - 1; + map.put("yearBefore", yearBefore); + map.put("month", month); + Integer monthBefore = month - 1; + map.put("monthBefore", monthBefore); + map.put("date", date); + map.put("commissionTime", "commissionTime"); + map.put("stationName", deptName); + // 今年年度 + String yearStart = TimeUtils.getYear(year); + String yearEnd = TimeUtils.getYearEnd(year); + String yearEndV2 = TimeUtils.getYearEndV2(year); + //去年年度 + String yearBeforeStart = TimeUtils.getYear(yearBefore); + String yearBeforeEnd = TimeUtils.getYearEnd(yearBefore); + // 今年当月 + String monthStart = TimeUtils.getMonthStart(year,month); + String monthEnd = TimeUtils.getMonthEnd(year,month); + String monthEndV2 = TimeUtils.getMonthEndV2(year,month); + // 今年上个月 + String beforeMonthStart = TimeUtils.getMonthStart(year,monthBefore); + String beforeMonthEnd = TimeUtils.getMonthEnd(year,monthBefore); + // 去年当月 + String monthStartBeforeYear = TimeUtils.getMonthStart(yearBefore,month); + String monthEndBeforeYear = TimeUtils.getMonthEnd(yearBefore,month); + // 所有设备信息 + List devices = mainSystemMonitoringService.getEmInfoList(); + + List reals = (List) redisTemplate.opsForValue().get(load_hydropower_unit_real_key); + List realsByDept = reals.stream().filter(s -> deptIds.contains(s.getDeptId())).collect(Collectors.toList()); + // 装机容量占比数据组装 + //总容量 + double sum = Optional.ofNullable(realsByDept) + .orElse(new ArrayList<>()).stream() + .filter(s -> s.getInstalledCapacity() != null) + .mapToDouble(HydropowerUnitRealVo::getInstalledCapacity).sum(); + map.put("installedCapacity", sum); + //各站点分组 + Map> listMap = Optional.ofNullable(realsByDept) + .orElse(new ArrayList<>()).stream() + .filter(s -> s.getInstalledCapacity() != null) + .collect(Collectors.groupingBy(HydropowerUnitRealVo::getDeptId)); + Map capacityProportionMap = new HashMap<>(); + for ( + Map.Entry> longListEntry : listMap.entrySet()) { + BigDecimal bigDecimal = BigDecimal.valueOf(0); + for (HydropowerUnitRealVo hydropowerUnitRealVo : longListEntry.getValue()) { + bigDecimal = BigDecimal.valueOf(hydropowerUnitRealVo.getInstalledCapacity()).add(bigDecimal); + } + for (Dept dept : deptList) { + if (dept.getDeptCode().equals(longListEntry.getKey())) { + capacityProportionMap.put(dept.getDeptName(), bigDecimal.doubleValue()); + } + } + } + //装机容量占比图 + ImageEntity capacityProportionChart = JFreeUtil.pieChartByDouble("水电项目装机容量占比图", capacityProportionMap, 1260, 60600); + map.put("capacityProportionChart", capacityProportionChart); +//各发电站发电量环比图+表格数据组装 + List powerPercentageVoList=new ArrayList<>(); + for (Dept dept : deptList) { + MonPowerPercentageVo powerVo = new MonPowerPercentageVo(); + powerVo.setDeptId(dept.getId()); + powerVo.setDeptName(dept.getDeptName()); + BigDecimal powerYear = new BigDecimal(0); + BigDecimal powerYearBefore = new BigDecimal(0); + BigDecimal powerMonth = new BigDecimal(0); + BigDecimal powerMonthBefore = new BigDecimal(0); + BigDecimal powerMonthYearBefore = new BigDecimal(0); + Float planGeneration=0f; + List planYearData = planGenertionClient.getPlanGenerationByParam(null, Arrays.asList(dept.getId().toString()), year.toString()); + if(CollectionUtils.isNotEmpty(planYearData)){ + planGeneration = planYearData.get(0).getPlanGeneration(); + } + // 站点设备集合 + List stationDevices = devices.stream().filter(device -> device.getCreateDept().equals(dept.getId())).collect(Collectors.toList()); + for (EminfoAndEmParamVo device : stationDevices) { + //今年发电量 + List analyseData = analyseDataService.periodTargetData(yearStart, yearEnd, 3, EquipmentConstants.CycleTypeEnum.YEAR_CYCLE.getType(), device.getEmCode(), HomePageConstant.ELECTRICITY_CONSUMPTION); + if (CollectionUtil.isNotEmpty(analyseData)) { + BigDecimal yearPower = analyseData.stream().filter(ktv -> ktv.getVal() != null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getVal()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerYear = powerYear.add(yearPower); + } + //去年发电量 + List analyseDataYearBefore = analyseDataService.periodTargetData(yearBeforeStart, yearBeforeEnd, 3, EquipmentConstants.CycleTypeEnum.YEAR_CYCLE.getType(), device.getEmCode(), HomePageConstant.ELECTRICITY_CONSUMPTION); + if (CollectionUtil.isNotEmpty(analyseDataYearBefore)) { + BigDecimal powerBefore = analyseDataYearBefore.stream().filter(ktv -> ktv.getVal() != null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getVal()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerYearBefore = powerYearBefore.add(powerBefore); + } + //今年当月发电量 + List analyseDataMonth= analyseDataService.periodTargetData(monthStart, monthEnd, 3, EquipmentConstants.CycleTypeEnum.MONTH_CYCLE.getType(), device.getEmCode(), HomePageConstant.ELECTRICITY_CONSUMPTION); + if (CollectionUtil.isNotEmpty(analyseDataMonth)) { + BigDecimal powerBefore = analyseDataMonth.stream().filter(ktv -> ktv.getVal() != null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getVal()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerMonth = powerMonth.add(powerBefore); + } + //上个月发电量 + List analyseDataMonthBefore = analyseDataService.periodTargetData(beforeMonthStart, beforeMonthEnd, 3, EquipmentConstants.CycleTypeEnum.MONTH_CYCLE.getType(), device.getEmCode(), HomePageConstant.ELECTRICITY_CONSUMPTION); + if (CollectionUtil.isNotEmpty(analyseDataMonthBefore)) { + BigDecimal powerBefore = analyseDataMonthBefore.stream().filter(ktv -> ktv.getVal() != null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getVal()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerMonthBefore = powerMonthBefore.add(powerBefore); + } + //去年当月发电量 + List analyseDataMonthBeforeYear = analyseDataService.periodTargetData(monthStartBeforeYear, monthEndBeforeYear, 3, EquipmentConstants.CycleTypeEnum.MONTH_CYCLE.getType(), device.getEmCode(), HomePageConstant.ELECTRICITY_CONSUMPTION); + if (CollectionUtil.isNotEmpty(analyseDataMonthBeforeYear)) { + BigDecimal powerBefore = analyseDataMonthBeforeYear.stream().filter(ktv -> ktv.getVal() != null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getVal()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerMonthYearBefore = powerMonthYearBefore.add(powerBefore); + } + + } + powerVo.setPowerYear(powerYear.floatValue()); + powerVo.setPowerMonYearBefore(powerYearBefore.floatValue()); + BigDecimal yearPercentage =new BigDecimal(0); + BigDecimal planPercentage =new BigDecimal(0); + if (!powerYearBefore.equals(0)){ + yearPercentage= powerYearBefore.divide(powerYear, 4, BigDecimal.ROUND_UP); + planPercentage= powerYearBefore.divide(BigDecimal.valueOf(planGeneration), 4, BigDecimal.ROUND_UP); + } + powerVo.setPlanPercentage(planPercentage.floatValue()); + powerVo.setPowerYearPercentage(yearPercentage.floatValue()); + powerVo.setPowerMon(powerMonth.floatValue()); + powerVo.setPowerMonBefore(powerMonthBefore.floatValue()); + powerVo.setPowerMonYearBefore(powerMonthYearBefore.floatValue()); + BigDecimal monPercentage =new BigDecimal(0); + if (!powerMonthYearBefore.equals(0)){ + monPercentage= powerMonthYearBefore.divide(powerMonth, 4, BigDecimal.ROUND_UP); + } + powerVo.setPowerMonPercentage(monPercentage.floatValue()); + powerPercentageVoList.add(powerVo); + } +// 各发电站发电量环比图数据组装 + //表格总计 + List planYearAll = planGenertionClient.getPlanGenerationByParam(null,Arrays.asList(deptId.toString()), year.toString()); + List planMonAll = planGenertionClient.getPlanGenerationByParam(null,Arrays.asList(deptId.toString()), year+"-"+month); + getTabelSum(deptId, powerPercentageVoList,planYearAll,planMonAll,map); + //柱状图图数据 +// todo 把柱状重新写一个方法展示 + String[] monthArray = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月"}; + double[] value = {20, 30, 25, 50, 40, 25, 50, 40}; + ImageEntity powerChainHistogram = JFreeUtil.lineChart("测试111", monthArray, value, 300, 200); + map.put("powerChainHistogram", powerChainHistogram); + //发电情况统计表数据 + if(powerPercentageVoList!=null){ + ArrayList> list = new ArrayList<>(powerPercentageVoList.size()); + for (MonPowerPercentageVo monPowerPercentageVo : powerPercentageVoList) { + HashMap temp = new HashMap<>(8); + temp.put("name", monPowerPercentageVo.getDeptName()); + temp.put("powerMonBefore", monPowerPercentageVo.getPowerMonYearBefore().toString()); + temp.put("powerYearBefore", monPowerPercentageVo.getPowerYearBefore().toString()); + temp.put("mon", monPowerPercentageVo.getPowerMon().toString()); + temp.put("year", monPowerPercentageVo.getPowerYear().toString()); + temp.put("monPercentage", monPowerPercentageVo.getPowerMonPercentage().toString()); + temp.put("yearPercentage", monPowerPercentageVo.getPowerYearPercentage().toString()); + temp.put("plan", monPowerPercentageVo.getPlanPercentage().toString()); + list.add(temp); + } + map.put("powerGeneration", list); + } + + + //本月缺陷 + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + wrapper.ge(OperPhenomenonEntity::getCreateTime, monthStart); + wrapper.le(OperPhenomenonEntity::getCreateTime,monthEndV2); + wrapper.eq(OperPhenomenonEntity::getIsDefect, TreatMethodConstant.IS_DEFECT); + wrapper.eq(OperPhenomenonEntity::getDiscriminateStatus, TreatMethodConstant.AUTO_SCREENED); + wrapper.in(OperPhenomenonEntity::getCreateDept, deptIds); + List monPhenomenonList = operPhenomenonService.list(wrapper); + List monConclusionList = monPhenomenonList.stream().filter(s -> s.getConclusionStatus().equals(1)).collect(Collectors.toList()); +// 各电站缺陷处理统计表 + monConclusionList.stream().sorted(Comparator.comparing(OperPhenomenonEntity::getDefectGrading).reversed().thenComparing(OperPhenomenonEntity::getCreateTime)); + ArrayList> checkList = new ArrayList<>(monConclusionList.size()); + for (OperPhenomenonEntity operPhenomenonEntity : monConclusionList) { + Long createDept = operPhenomenonEntity.getCreateDept(); + R createDeptName= sysClient.getDeptName(createDept); + if (!createDeptName.isSuccess()&&createDeptName.getData()!=null){ + continue; + } + //表格数据 + HashMap temp = new HashMap<>(); + temp.put("name", "name1"); + temp.put("name",createDeptName.getData()); + temp.put("level",operPhenomenonEntity.getDefectGrading()); + temp.put("createTime",operPhenomenonEntity.getCreateTime().toString()); + temp.put("findTime",operPhenomenonEntity.getFindTime().toString()); + temp.put("descripiton",operPhenomenonEntity.getDescripiton()); + temp.put("disposeDesc",operPhenomenonEntity.getDisposeDesc()); + checkList.add(temp); + } + map.put("checkList",checkList); +//各电站缺陷统计表 + //本年缺陷 + LambdaQueryWrapper wrapperYear= Wrappers.lambdaQuery(); + wrapper.ge(OperPhenomenonEntity::getCreateTime, yearStart); + wrapper.le(OperPhenomenonEntity::getCreateTime,yearEndV2); + wrapper.eq(OperPhenomenonEntity::getIsDefect, TreatMethodConstant.IS_DEFECT); + wrapper.eq(OperPhenomenonEntity::getDiscriminateStatus, TreatMethodConstant.AUTO_SCREENED); + wrapper.in(OperPhenomenonEntity::getCreateDept, deptIds); + List yearPhenomenonEntities = operPhenomenonService.list(wrapperYear); + List yearConclusionList = yearPhenomenonEntities.stream().filter(s -> s.getConclusionStatus().equals(1)).collect(Collectors.toList()); + + if (CollectionUtil.isEmpty(yearPhenomenonEntities)) { + ArrayList> checkStatistics = new ArrayList<>(1); + //表格数据 + HashMap temp = new HashMap<>(7); + temp.put("deptName", "总计"); + temp.put("checkLevel","0"); + temp.put("findShortagesMon","0"); + temp.put("shortagesMon","0"); + temp.put("findShortagesYear","0"); + temp.put("shortagesYear","0"); + temp.put("shortagesRate","0"); + checkList.add(temp); + map.put("checkStatistics",checkStatistics); + }else { + List checkChartRes=new ArrayList<>(); + Map>> phenomenonMap = yearPhenomenonEntities.stream().collect( + Collectors.groupingBy(OperPhenomenonEntity::getCreateDept, + Collectors.groupingBy(OperPhenomenonEntity::getDefectGrading))); + for (Map.Entry>> deptMapEntry : phenomenonMap.entrySet()) { + R deptName1 = sysClient.getDeptName(deptMapEntry.getKey()); + for (Map.Entry> levelList : deptMapEntry.getValue().entrySet()) { + Integer findShortagesYear = levelList.getValue().size(); + Integer shortagesYear = yearConclusionList.stream().filter(s -> s.getDefectLevel().equals(deptMapEntry)).filter(s -> s.getDefectLevel().equals(deptMapEntry)).collect(Collectors.toList()).size(); + Double shortagesRate=0d; + if (findShortagesYear!=0&&shortagesYear!=0){ + shortagesRate=BigDecimal.valueOf(shortagesYear).divide(BigDecimal.valueOf(findShortagesYear),2,BigDecimal.ROUND_UP).doubleValue(); + } + Integer findShortagesMon=Optional.ofNullable(monPhenomenonList).orElse(new ArrayList<>()) .stream().filter(s -> s.getDefectLevel().equals(deptMapEntry)).filter(s -> s.getDefectLevel().equals(deptMapEntry)).collect(Collectors.toList()).size(); + Integer shortagesMon=Optional.ofNullable(monConclusionList).orElse(new ArrayList<>()).stream().filter(s -> s.getDefectLevel().equals(deptMapEntry)).filter(s -> s.getDefectLevel().equals(deptMapEntry)).collect(Collectors.toList()).size(); + CheckChartVo checkChartVo=new CheckChartVo(deptName1.getData(),levelList.getKey(),findShortagesMon,shortagesMon,findShortagesYear,shortagesYear,shortagesRate); + checkChartRes.add(checkChartVo); + } + } +// 总计 + Map> levelPhenomenonList = yearPhenomenonEntities.stream().collect(Collectors.groupingBy(OperPhenomenonEntity::getDefectGrading)); + for (Map.Entry> levelPhenomenon : levelPhenomenonList.entrySet()) { + Integer findShortagesYear = levelPhenomenon.getValue().size(); + Integer shortagesYear = Optional.ofNullable(yearConclusionList).orElse(new ArrayList<>()).stream().filter(s -> s.getDefectLevel().equals(levelPhenomenon)).collect(Collectors.toList()).size(); + Double shortagesRate=0d; + if (findShortagesYear!=0&&shortagesYear!=0){ + shortagesRate=BigDecimal.valueOf(shortagesYear).divide(BigDecimal.valueOf(findShortagesYear),2,BigDecimal.ROUND_UP).doubleValue(); + } + Integer findShortagesMon= Optional.ofNullable(monPhenomenonList).orElse(new ArrayList<>()).stream().filter(s -> s.getDefectLevel().equals(levelPhenomenon)).collect(Collectors.toList()).size(); + Integer shortagesMon= Optional.ofNullable(monConclusionList).orElse(new ArrayList<>()).stream().filter(s -> s.getDefectLevel().equals(levelPhenomenon)).collect(Collectors.toList()).size(); + CheckChartVo checkChartVo=new CheckChartVo("总计",levelPhenomenon.getKey(),findShortagesMon,shortagesMon,findShortagesYear,shortagesYear,shortagesRate); + checkChartRes.add(checkChartVo); + } + } + +// if (CollectionUtils.isNotEmpty(ticketNumbers)) { +// String percent = PercentCountUtils.getPercent(evaluateEntities.size(), ticketNumbers.size()); +// ticketCount.setPercentPassTicket(percent); +// } +// 两票执行情况 + R> yearTicket = ticketInfoClient.getWorkTicketByTime(yearStart, yearEndV2); + R> yearOperateTicket = ticketInfoClient.getOperateTicketByTime(yearStart, yearEndV2); + R> monthTicket = ticketInfoClient.getWorkTicketByTime(monthStart, monthEndV2); + R> monthOperateTicket = ticketInfoClient.getOperateTicketByTime(monthStart, monthEndV2); + if (!monthTicket.isSuccess()||!yearTicket.isSuccess()){ + return R.fail("两票查询异常,请稍后重试"); + } + + yearPhenomenonEntities.stream().collect(Collectors.groupingBy(OperPhenomenonEntity::getDefectGrading)); + +//年工作票分组统计 + Map>> yearTicketCollect = Optional.ofNullable(yearTicket.getData()).orElse(new ArrayList<>()).stream() + .filter(s->s.getSignageCode()!=null) + .collect(Collectors.groupingBy(WorkTicketInfoEntity::getSignageCode, + Collectors.groupingBy(WorkTicketInfoEntity::getType))); +// 合格率计算 +// Optional.ofNullable(yearTicket.getData()).orElse(new ArrayList<>()).stream() +// .filter(s->s.getSignageCode()!=null) + //年操作票分组统计 + Map>> yearOperateTicketCollect = Optional.ofNullable(yearOperateTicket.getData()).orElse(new ArrayList<>()).stream() + .filter(s->s.getSignageCode()!=null) + .collect(Collectors.groupingBy(StandardTicketInfoEntity::getSignageCode, + Collectors.groupingBy(StandardTicketInfoEntity::getTicketType))); + + for (Map.Entry>> deptTicketCollect : yearTicketCollect.entrySet()) { + List cellList=new ArrayList<>(); + for (Map.Entry> ticketCollect : deptTicketCollect.getValue().entrySet()) { + TicketChartCell ticketChartCell = new TicketChartCell(); + //年合格率和数量 + Integer count = ticketCollect.getValue().size(); + + Long passCount =ticketCollect.getValue().stream().filter(s->s.getStatus()==1).count(); + Double ticketYearPerc=BigDecimal.valueOf(passCount).divide(BigDecimal.valueOf(count),2,BigDecimal.ROUND_UP).doubleValue(); + ticketChartCell.setTicketYear(count); + ticketChartCell.setTicketYeaPercr(ticketYearPerc); + if (monthTicket.getData()!=null){ + ticketChartCell.setTicketMon(0); + ticketChartCell.setTicketMonPerc(0d); + }else { + // 月合格率和数量 + List monthTicketCollect = monthTicket.getData().stream() + .filter(s -> s.getCreateDept().equals(deptTicketCollect.getKey())) + .filter(s -> s.getType().equals(ticketCollect.getKey())).collect(Collectors.toList()); + ticketChartCell.setTicketMon(monthTicketCollect.size()); + Integer passCountMon =(int) monthTicketCollect.stream().filter(s->s.getStatus()==1).count(); + Double ticketMonPerc=BigDecimal.valueOf(passCountMon).divide(BigDecimal.valueOf(monthTicketCollect.size()),2,BigDecimal.ROUND_UP).doubleValue(); + ticketChartCell.setTicketMonPerc(ticketMonPerc); + } + cellList.add(ticketChartCell); + } +// 拿到对应的厂站进行分组展示 + Map> deptOperateTicketCollect = yearOperateTicketCollect.get(deptTicketCollect.getKey()); + if (deptOperateTicketCollect==null){ + TicketChartCell ticketChartCell = new TicketChartCell(); + } + for (Map.Entry> operateTicketCollect : deptOperateTicketCollect.entrySet()) { + + } + + + } + + + + + //模拟表格数据 + ArrayList> list = new ArrayList<>(2); + + HashMap temp = new HashMap<>(3); + temp.put("name", "name1"); +// temp.put("name", "第一个人"); +// temp.put("age", "23"); + list.add(temp); + temp = new HashMap<>(3); + temp.put("name", "2"); +// temp.put("name", "第二个人"); +// temp.put("age", "24"); + list.add(temp); + map.put("safelist", list); + + +// //模拟柱状图图数据 +// String[] monthArray = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月"}; +// double[] value = {20, 30, 25, 50, 40, 25, 50, 40}; +// ImageEntity lineEntity = JFreeUtil.lineChart("测试111", monthArray, value, 300, 200); +// map.put("lineEntity", lineEntity); + return R.success("成功"); + +// //todo + + + } + + private static void getTabelSum(Long deptId, List powerPercentageVoList, List planYearAll, List planMonAll,HashMap map) { + Float planGeneration=0f; + if (CollectionUtil.isNotEmpty(planYearAll)){ + planGeneration = planYearAll.get(0).getPlanGeneration(); + } + Float planMonGeneration=0f; + if (CollectionUtil.isNotEmpty(planYearAll)){ + planMonGeneration = planMonAll.get(0).getPlanGeneration(); + } + MonPowerPercentageVo powerVo = new MonPowerPercentageVo(); + powerVo.setDeptId(deptId); + powerVo.setDeptName("总计"); + BigDecimal powerYear= powerPercentageVoList.stream().filter(s->s.getPowerYear()!=null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getPowerYear()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerVo.setPowerYear(powerYear.floatValue()); + map.put("powerYear",powerYear.toString()); + BigDecimal powerYearBefore= powerPercentageVoList.stream().filter(s->s.getPowerYearBefore()!=null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getPowerYearBefore()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerVo.setPowerMonYearBefore(powerYearBefore.floatValue()); + BigDecimal yearPercentage =new BigDecimal(0); + BigDecimal planPercentage =new BigDecimal(0); + if (!powerYearBefore.equals(0)){ +// 年累计环比 + yearPercentage= powerYearBefore.divide(powerYear, 4, BigDecimal.ROUND_UP); + planPercentage= powerYearBefore.divide(BigDecimal.valueOf(planGeneration), 4, BigDecimal.ROUND_UP); +// 年计划完成率 + map.put("yearCompletionRate",planPercentage.toString()); + } + powerVo.setPowerYearPercentage(yearPercentage.floatValue()); + powerVo.setPlanPercentage(planPercentage.floatValue()); + BigDecimal powerMonth= powerPercentageVoList.stream().filter(s->s.getPowerMon()!=null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getPowerMon()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); +// 项目月发电量 + powerVo.setPowerMon(powerMonth.floatValue()); + map.put("powerMon",powerMonth.toString()); +// 项目月计划完成量 + BigDecimal planMonPercentage =new BigDecimal(0); + if (!powerMonth.equals(0)&&planMonGeneration!=0){ + planMonPercentage= powerMonth.divide(BigDecimal.valueOf(planMonGeneration), 4, BigDecimal.ROUND_UP); + } + map.put("monCompletionRate",planMonPercentage); + BigDecimal powerMonthBefore= powerPercentageVoList.stream().filter(s->s.getPowerMonBefore()!=null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getPowerMonBefore()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerVo.setPowerMonBefore(powerMonthBefore.floatValue()); + BigDecimal powerMonthYearBefore= powerPercentageVoList.stream().filter(s->s.getPowerMonYearBefore()!=null) + .map(ktv -> BigDecimal.valueOf(Float.valueOf(ktv.getPowerMonYearBefore()))) + .reduce(BigDecimal.ZERO, BigDecimal::add); + powerVo.setPowerMonYearBefore(powerMonthYearBefore.floatValue()); + BigDecimal monPercentage =new BigDecimal(0); + if (!powerMonthYearBefore.equals(0)){ + monPercentage= powerMonthYearBefore.divide(powerMonth, 4, BigDecimal.ROUND_UP); + } + //发电量环比增加 + BigDecimal monAdd=powerMonth.subtract(powerMonthBefore); + if (monAdd.equals(0)){ + map.put("percentageAdd",0); + }else { + map.put("percentageAdd", monAdd.divide(powerMonth, 4, BigDecimal.ROUND_UP).toString()); + } + powerVo.setPowerMonPercentage(monPercentage.floatValue()); + powerPercentageVoList.add(powerVo); + } + + + /** + * 首行表头样式 + * + * @param hssWB + * @param sheet + */ + private void setFirstHeader(HSSFWorkbook hssWB, HSSFSheet sheet) { + // 第一行 + HSSFRow fisrtRow = sheet.createRow(0); + this.setTitileStyle(hssWB, fisrtRow, 19, true); + // 第一个单元格 + HSSFCell headCell = fisrtRow.getCell(0); + headCell.setCellValue("集团级水电站生产运行月报"); + // 首行合并情况 + CellRangeAddress region1 = new CellRangeAddress(0, 0, (short) 0, (short) 19); + sheet.addMergedRegion(region1); + } + + /** + * 表头格式设置 + * + * @param hssWB + * @param sheet + */ + private void setWorkHeader(HSSFWorkbook hssWB, HSSFSheet sheet) { + // 创建行 + HSSFRow row_1 = sheet.createRow(1); + this.setTitileStyle(hssWB, row_1, 19, true); + // 第一行 + HSSFCell header_row_1_cell_1 = row_1.getCell(0); + header_row_1_cell_1.setCellValue("区域"); + HSSFCell header_row_1_cell_2 = row_1.getCell(1); + header_row_1_cell_2.setCellValue("生产月报"); + HSSFCell header_row_1_cell_3 = row_1.getCell(15); + header_row_1_cell_3.setCellValue("安全月报"); + + // 第二行 + HSSFRow row_2 = sheet.createRow(2); + this.setTitileStyle(hssWB, row_2, 19, true); + HSSFCell header_row_2_cell_1 = row_2.getCell(1); + header_row_2_cell_1.setCellValue("计划发电量"); + HSSFCell header_row_2_cell_2 = row_2.getCell(2); + header_row_2_cell_2.setCellValue("实际发电量"); + HSSFCell header_row_2_cell_3 = row_2.getCell(3); + + header_row_2_cell_3.setCellValue("发电完成率"); + HSSFCell header_row_2_cell_4 = row_2.getCell(4); + header_row_2_cell_4.setCellValue("同比"); + HSSFCell header_row_2_cell_5 = row_2.getCell(5); + header_row_2_cell_5.setCellValue("发电计划预测"); + HSSFCell header_row_2_cell_6 = row_2.getCell(6); + header_row_2_cell_6.setCellValue("操作票"); + + + HSSFCell header_row_2_cell_7 = row_2.getCell(7); + header_row_2_cell_7.setCellValue("操作票合格率"); + HSSFCell header_row_2_cell_8 = row_2.getCell(8); + header_row_2_cell_8.setCellValue("工作票"); + HSSFCell header_row_2_cell_9 = row_2.getCell(9); + header_row_2_cell_9.setCellValue("工作票合格率"); + + HSSFCell header_row_2_cell_10 = row_2.getCell(10); + header_row_2_cell_10.setCellValue("日常维护"); + HSSFCell header_row_2_cell_11 = row_2.getCell(11); + header_row_2_cell_11.setCellValue("巡检任务"); + HSSFCell header_row_2_cell_12 = row_2.getCell(12); + header_row_2_cell_12.setCellValue("缺陷数"); + + + HSSFCell header_row_2_cell_13 = row_2.getCell(13); + header_row_2_cell_13.setCellValue("消缺率"); + HSSFCell header_row_2_cell_14 = row_2.getCell(14); + header_row_2_cell_14.setCellValue("检修任务"); + HSSFCell header_row_2_cell_15 = row_2.getCell(15); + header_row_2_cell_15.setCellValue("安全生产会议次数"); + + HSSFCell header_row_2_cell_16 = row_2.getCell(16); + header_row_2_cell_16.setCellValue("月度自查报告"); + HSSFCell header_row_2_cell_17 = row_2.getCell(17); + header_row_2_cell_17.setCellValue("设备试验"); + HSSFCell header_row_2_cell_18 = row_2.getCell(18); + header_row_2_cell_18.setCellValue("技能培训"); + HSSFCell header_row_2_cell_19 = row_2.getCell(19); + header_row_2_cell_19.setCellValue("安全大检查"); + + // 表头一:合并情况 + CellRangeAddress header_region_1 = new CellRangeAddress((short) 1, (short) 2, (short) 0, (short) 0); + CellRangeAddress header_region_2 = new CellRangeAddress((short) 1, (short) 1, (short) 1, (short) 14); + CellRangeAddress header_region_3 = new CellRangeAddress((short) 1, (short) 1, (short) 15, (short) 19); + sheet.addMergedRegion(header_region_1); + sheet.addMergedRegion(header_region_2); + sheet.addMergedRegion(header_region_3); + + } + + /** + * 表格数据填充 + * + * @param hssWB + * @param sheet + * @param areaMonthReportVoList + */ + private void setWorkData(HSSFWorkbook hssWB, HSSFSheet sheet, List areaMonthReportVoList) { + int size = areaMonthReportVoList.size(); + for (int i = 0; i < size; i++) { + HSSFRow row = sheet.createRow(i + 3); + this.setTitileStyle(hssWB, row, 19, false); + AreaMonthReportVo areaMonthReportVo = areaMonthReportVoList.get(i); + //区域 + HSSFCell header_row_cell_0 = row.getCell(0); + header_row_cell_0.setCellValue(areaMonthReportVo.getAreaName()); + //计划发电量 + HSSFCell header_row_cell_1 = row.getCell(1); + header_row_cell_1.setCellValue(areaMonthReportVo.getPlanPower()); + //实际发电量 + HSSFCell header_row_cell_2 = row.getCell(2); + header_row_cell_2.setCellValue(areaMonthReportVo.getActualPower()); + + //发电完成率 + HSSFCell header_row_cell_3 = row.getCell(3); + header_row_cell_3.setCellValue(areaMonthReportVo.getPowerFinishRate()); + //同比 + HSSFCell header_row_cell_4 = row.getCell(4); + header_row_cell_4.setCellValue(areaMonthReportVo.getComparePowerRate()); + //发电计划预测 + HSSFCell header_row_cell_5 = row.getCell(5); + header_row_cell_5.setCellValue(areaMonthReportVo.getPredictPlanPower()); + + //操作票 + HSSFCell header_row_cell_6 = row.getCell(6); + header_row_cell_6.setCellValue(areaMonthReportVo.getOperate()); + //操作票合格率 + HSSFCell header_row_cell_7 = row.getCell(7); + header_row_cell_7.setCellValue(areaMonthReportVo.getOperaQualifyRate()); + //工作票 + HSSFCell header_row_cell_8 = row.getCell(8); + header_row_cell_8.setCellValue(areaMonthReportVo.getWork()); + //工作票合格率 + HSSFCell header_row_cell_9 = row.getCell(9); + header_row_cell_9.setCellValue(areaMonthReportVo.getWorkQualifyRate()); + + //日常维护 + HSSFCell header_row_cell_10 = row.getCell(10); + header_row_cell_10.setCellValue(areaMonthReportVo.getRoutineMaintenance()); + //巡检任务 + HSSFCell header_row_cell_11 = row.getCell(11); + header_row_cell_11.setCellValue(areaMonthReportVo.getInspect()); + //缺陷数 + HSSFCell header_row_cell_12 = row.getCell(12); + header_row_cell_12.setCellValue(areaMonthReportVo.getDefect()); + + //消缺率 + HSSFCell header_row_cell_13 = row.getCell(13); + header_row_cell_13.setCellValue(areaMonthReportVo.getDefectRate()); + //检修任务 + HSSFCell header_row_cell_14 = row.getCell(14); + header_row_cell_14.setCellValue(areaMonthReportVo.getMaintenanceTasks()); + //安全生产会议次数 + HSSFCell header_row_cell_15 = row.getCell(15); + header_row_cell_15.setCellValue(areaMonthReportVo.getSafetyMeeting()); + + //月度自查报告 + HSSFCell header_row_cell_16 = row.getCell(16); + header_row_cell_16.setCellValue(areaMonthReportVo.getSelfReport()); + //设备试验 + HSSFCell header_row_cell_17 = row.getCell(17); + header_row_cell_17.setCellValue(areaMonthReportVo.getDeviceTry()); + //技能培训 + HSSFCell header_row_cell_18 = row.getCell(18); + header_row_cell_18.setCellValue(areaMonthReportVo.getSkillTrainy()); + //安全大检查 + HSSFCell header_row_cell_19 = row.getCell(19); + header_row_cell_19.setCellValue(areaMonthReportVo.getSecurityCheck()); + } + } + + /** + * 设置Titile单元格样式 + * + * @param hssWB + * @param row + * @param len + */ + private void setTitileStyle(HSSFWorkbook hssWB, HSSFRow row, int len, boolean isHead) { + HSSFCellStyle cellStyle = getHeadStyle(hssWB, isHead); + for (int i = 0; i <= len; i++) { + HSSFCell hssfcell = row.createCell(i); + hssfcell.setCellStyle(cellStyle); + } + } + + /** + * 获取表头样式 + * + * @param hssWB + * @return + */ + private HSSFCellStyle getHeadStyle(HSSFWorkbook hssWB, boolean isHead) { + HSSFCellStyle headStyle = hssWB.createCellStyle(); + //边框 + headStyle.setBorderLeft(BorderStyle.THIN); + headStyle.setBorderRight(BorderStyle.THIN); + headStyle.setBorderTop(BorderStyle.THIN); + headStyle.setBorderBottom(BorderStyle.THIN); + //居中: + headStyle.setAlignment(HorizontalAlignment.CENTER); // 居中 + headStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中 + //字体: + HSSFFont font = hssWB.createFont(); + font.setFontName("黑体"); + if (isHead) { + //设置字体大小 + font.setFontHeightInPoints((short) 12); + //背景颜色 + headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + headStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); + } else { + //设置字体大小 + font.setFontHeightInPoints((short) 8); + //背景颜色 + headStyle.setFillPattern(FillPatternType.NO_FILL); + headStyle.setFillForegroundColor(HSSFColor.WHITE.index); + } + //字体格式 + + headStyle.setFont(font); + return headStyle; + } + + /** + * 获取区域月报数据 + * + * @return + */ + private List getAreaMonthReport(String date, boolean isSendFlag) { + R> D = sysClient.getDeptByCurrentUser(); + if (!D.isSuccess() || CollectionUtil.isEmpty(D.getData())) { + return null; + } + List authList = D.getData().stream().filter(o -> o.getDeptCategory().equals(3)).map(Dept::getId).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(authList)) { + return null; + } + Map> map = (Map>) redisTemplate.opsForValue().get(area_month_report_key); + if (MapUtils.isEmpty(map)) { + return null; + } + if (isSendFlag) { + // 发送邮件 + this.sendMonthReport(map, D.getData()); + } + return map.get(date); + } + + + /** + * 区域-加载月报数据 + * + * @param param + */ + @Override + public void loadMonthReport(String param, int year) { + // 获取所有机构 + R> R = sysClient.getDeptList(); + if (!R.isSuccess() || CollectionUtil.isEmpty(R.getData())) { + return; + } + // 查询所有服务类型——"运维服务"、站点类型——"水电站" + List stationList = stationService.getStationType(HomePageConstant.HYDROPOWER_SERVETYPE, Collections.singletonList(HomePageConstant.HYDROPOWER), null); + if (CollectionUtil.isEmpty(stationList)) { + return; + } + // 站点近年发电数据 + Map> powerMap = (Map>) redisTemplate.opsForValue().get(RECENT_YEAR_POWER_DATA); + // 存储数据节点 key - 月份 value - 区域数据集合 + Map> map = new HashMap<>(); + // 月份集合 + List monthList = getMonthList(year, Calendar.getInstance().get(Calendar.MONTH)); + monthList.forEach(mon -> { + List list = this.getAreaReportByMon(R.getData(), powerMap, stationList, mon); + if (CollectionUtil.isEmpty(list)) { + return; + } + map.put(mon, list); + }); + // 推送当月报表邮件 + this.sendMonthReport(map, R.getData()); + redisTemplate.opsForValue().set(area_month_report_key, map); + } + + /** + * 获取近年月份集合 + * + * @param year + * @return + */ + public static List getMonthList(int year, int endMoth) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM"); + // 开始日期 + Calendar endCal = Calendar.getInstance(); + endCal.setTime(new Date()); + endCal.add(Calendar.MONTH, -endCal.get(Calendar.MONTH) + endMoth); + endCal.add(Calendar.DATE, -endCal.get(Calendar.DATE) + 1); + + // 结束日期 + Calendar startCal = Calendar.getInstance(); + startCal.setTime(new Date()); + startCal.set(Calendar.YEAR, startCal.get(Calendar.YEAR) - year); + startCal.add(Calendar.MONTH, -startCal.get(Calendar.MONTH)); + startCal.add(Calendar.DATE, -startCal.get(Calendar.DATE) + 1); + // 获取日期之间的月份 + List list = new ArrayList<>(); + while (endCal.after(startCal)) { + list.add(format.format(startCal.getTime())); + startCal.add(Calendar.MONTH, 1); + } + list.add(format.format(endCal.getTime())); + return list; + } + + /** + * 区域月报数据加载 + * + * @param deptList + * @param powerMap + * @param stationList + * @param mon + * @return + */ + private List getAreaReportByMon(List deptList, Map> powerMap, List stationList, String mon) { + LocalDateTime startTime = LocalDateTime.parse(mon + "-01 00:00:00", dtf); + LocalDateTime endTime = getEndTime(mon); + // 查询所有站点的计划发电量 + List planList = getPlanPower(stationList, mon); + // 站点实际发电量 + Map actualMap = getActualPower(powerMap, stationList, mon + "-01"); + // 站点去年发电量 + Map oldActualMap = getActualPower(powerMap, stationList, getLastyear(1, mon)); + // 站点前发电量 + Map oldOldActualMap = getActualPower(powerMap, stationList, getLastyear(2, mon)); + // 取机构中区域部分 + List areaList = deptList.stream().filter(o -> o.getDeptCategory().equals(3)).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(areaList)) { + return null; + } + List areaMonthReportVoList = new ArrayList<>(); + areaList.forEach(area -> { + AreaMonthReportVo areaMonthReport = new AreaMonthReportVo(); + areaMonthReport.setAreaId(area.getId()); + areaMonthReport.setAreaName(area.getDeptName()); + // 获取区域下的站点 + List stationIdList = deptList.stream().filter(o -> o.getParentId().equals(area.getId()) && o.getDeptCategory().equals(4)).map(Dept::getId).collect(Collectors.toList()); + List areaStationList = stationList.stream().filter(o -> stationIdList.contains(o.getRefDept())).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(areaStationList)) { + return; + } + // 计划发电量、实际发电量、发电完成率 + this.powerMonth(planList, actualMap, oldActualMap, areaStationList, areaMonthReport); + // 操作票、操作票合格率/ 工作票、工作票合格率 + this.doubleMonth(area, areaMonthReport, mon + "-01 00:00:00", getStrEndTime(mon)); + // 日常维护、巡检任务、缺陷数、消缺率、检修任务 + this.taskMonth(Collections.singletonList(area.getId()), areaMonthReport, mon + "-01 00:00:00", getStrEndTime(mon)); + // 预测 + this.getPredictPlanPower(oldActualMap, oldOldActualMap, areaStationList, areaMonthReport); + // 安全生产会议次数、月度检查报告、技能培训、安全大检查 + this.getSecurityCheck(Collections.singletonList(area.getId()), areaMonthReport, mon + "-01 00:00:00", getStrEndTime(mon)); + // 设备试验 + this.getDeviceTry(mon + "-01 00:00:00", getStrEndTime(mon), Collections.singletonList(area.getId()), areaMonthReport); + areaMonthReportVoList.add(areaMonthReport); + }); + return areaMonthReportVoList; + } + + /** + * 预测发电量 + * + * @param oldActualMap + * @param oldOldActualMap + * @param areaStationList + * @param areaMonthReport + */ + private void getPredictPlanPower(Map oldActualMap, Map oldOldActualMap, List areaStationList, AreaMonthReportVo areaMonthReport) { + areaMonthReport.setPredictPlanPower(0.0); + // 实际发电量 + List ids = areaStationList.stream().map(StationEntity::getId).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(ids)) { + return; + } + double oldActualPower = oldActualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); + double oldOldActualPower = oldOldActualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); + if (Math.abs(oldActualPower) <= 0 && Math.abs(oldOldActualPower) <= 0) { + return; + } + double predictPlanPower = BigDecimal.valueOf((oldActualPower + oldOldActualPower) / 2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + areaMonthReport.setPredictPlanPower(predictPlanPower); + } + + /** + * 推送当月月报 + * + * @param map + * @param list + */ + private void sendMonthReport(Map> map, List list) { + if (MapUtils.isEmpty(map) || CollectionUtil.isEmpty(list)) { + return; + } + // 获取邮件接收人 + Dept dept = list.stream().min(Comparator.comparing(Dept::getDeptCategory)).get(); + if (ObjectUtil.isEmpty(dept)) { + return; + } + R> userR = userClient.userListByDeptAndChildrenWithAuth(dept.getId()); + if (!userR.isSuccess() && CollectionUtil.isEmpty(userR.getData())) { + return; + } + List userList = userR.getData().stream().filter(o -> dept.getId().equals(o.getCreateDept())).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(userList)) { + return; + } + List mailList = userList.stream().map(User::getEmail).filter(StringUtil::isNotBlank).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(mailList)) { + return; + } + // 获取月报数据 + List entityList = map.get(ft.format(new Date())); + if (CollectionUtil.isEmpty(entityList)) { + return; + } + // 发送邮件 + MailPushDto pushDto = new MailPushDto(); + pushDto.setBusinessClassify("system"); + pushDto.setBusinessKey("Month_Report"); + pushDto.setSubject("水电站生产运行"); + Map param = new HashMap<>(); + param.put("templatePath", "/data/hzims/message/mail/template/stationRunMonthReport.html"); + Map parameters = new HashMap<>(); + parameters.put("data", entityList); + param.put("parameters", parameters); + pushDto.setExtras(param); + pushDto.setText("水电站生产运行月报内容"); + pushDto.setToAccount(mailList.toArray(new String[0])); + pushDto.setHtml(true); + pushDto.setCreateUser(userR.getData().get(0).getCreateUser()); + pushDto.setTenantId(dept.getTenantId()); + pushDto.setCreateDept(dept.getId()); + pushMsgClient.sendMail(pushDto); + } + + /** + * 获取结束时间 + * + * @param mon + * @return + * @throws ParseException + */ + private LocalDateTime getEndTime(String mon) { + try { + Date date = sdf.parse(mon + "-01 00:00:00"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.MONTH, 1); + return calendar.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); + } catch (ParseException e) { + return LocalDateTime.now(); + } + } + + + /** + * 获取结束时间 + * + * @param mon + * @return + * @throws ParseException + */ + private String getStrEndTime(String mon) { + try { + Date date = sdf.parse(mon + "-01 00:00:00"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.MONTH, 1); + return sdf.format(calendar.getTime()); + } catch (ParseException e) { + return sdf.format(LocalDateTime.now()); + } + } + + + /** + * 获取站点计划发电量 + * + * @param stationList + * @param mon + * @return + */ + private List getPlanPower(List stationList, String mon) { + List list = stationList.stream().map(StationEntity::getCode).collect(Collectors.toList()); + return planGenertionClient.getPlanGenerationByParam(list, null, mon); + } + + /** + * 获取站点月份实际发电量 + * + * @param stationList + * @return + */ + private Map getActualPower(Map> powerMap, List stationList, String month) { + if (MapUtils.isEmpty(powerMap)) { + return null; + } + // 站点Id集合 + List stationIdList = stationList.stream().map(StationEntity::getId).collect(Collectors.toList()); + // 存储站点实际发电量 + Map actualPowerMap = new HashMap<>(); + stationIdList.forEach(key -> { + Map monthMap = powerMap.get(key); + if (MapUtils.isEmpty(monthMap)) { + return; + } + float actualPower = 0f; + if (ObjectUtil.isNotEmpty(monthMap.get(month))) { + actualPower = monthMap.get(month); + } + actualPowerMap.put(key, actualPower); + }); + return actualPowerMap; + } + + /** + * 区域-月计划发电量、月实际发电量、月发电完成率、同比 + * + * @param planList + * @param actualMap + * @param oldActualMap + * @param areaStationList + * @param areaMonthReport + */ + private void powerMonth(List planList, Map actualMap, Map oldActualMap, List areaStationList, AreaMonthReportVo areaMonthReport) { + // 计划发电量 + List codeList = areaStationList.stream().map(StationEntity::getCode).collect(Collectors.toList()); + double planPower = planList.stream().filter(o -> codeList.contains(o.getStationId())).mapToDouble(PlanGenerationEntity::getPlanGeneration).sum(); + areaMonthReport.setPlanPower(Float.parseFloat(String.valueOf(planPower))); + if (MapUtils.isEmpty(actualMap)) { + areaMonthReport.setActualPower(0f); + areaMonthReport.setPowerFinishRate(0.0); + areaMonthReport.setComparePowerRate(0.0); + return; + } + // 实际发电量 + List ids = areaStationList.stream().map(StationEntity::getId).collect(Collectors.toList()); + double actualPower = actualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); + areaMonthReport.setActualPower(Float.parseFloat(String.valueOf(actualPower))); + if (Math.abs(planPower) <= 0) { + areaMonthReport.setPowerFinishRate(0.0); + } else { + // 发电完成率 + double powerFinishRate = BigDecimal.valueOf(actualPower / planPower * 100).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + areaMonthReport.setPowerFinishRate(powerFinishRate); + } + // 同比 + double oldActualPower = oldActualMap.entrySet().stream().filter(e -> ids.contains(e.getKey())).mapToDouble(Map.Entry::getValue).sum(); + if (Math.abs(actualPower) <= 0 || Math.abs(oldActualPower) <= 0) { + areaMonthReport.setComparePowerRate(0.0); + return; + } + double comparePowerRate = BigDecimal.valueOf(actualPower / oldActualPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + areaMonthReport.setComparePowerRate(comparePowerRate); + } + + /** + * 区域-操作票、操作票合格率/ 工作票、工作票合格率 + * + * @param area + * @param areaMonthReport + */ + private void doubleMonth(Dept area, AreaMonthReportVo areaMonthReport, String startTime, String endTime) { + // 站点归属机构集合 + Map map = new HashMap<>(); + map.put("startDate", startTime); + map.put("endDate", endTime); + map.put("deptList", Collections.singletonList(area.getId())); + R R = ticketInfoClient.getOperateWorkStatistic(map); + if (!R.isSuccess() || ObjectUtil.isEmpty(R.getData())) { + areaMonthReport.setOperate(0); + areaMonthReport.setOperaQualifyRate(0.0); + areaMonthReport.setWork(0); + areaMonthReport.setWorkQualifyRate(0.0); + return; + } + TicketMonthVO ticketMonthVO = R.getData(); + // 操作票 + int operate = ticketMonthVO.getOperate(); + int operateQualify = ticketMonthVO.getOperateQualify(); + areaMonthReport.setOperate(operate); + if (operateQualify <= 0) { + areaMonthReport.setOperaQualifyRate(0.0); + } else { + double operateQualifyRate = BigDecimal.valueOf(operateQualify / (double) operate * 100L).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + areaMonthReport.setOperaQualifyRate(operateQualifyRate); + } + //工作票 + int work = ticketMonthVO.getWork(); + int workQualify = ticketMonthVO.getWorkQualify(); + areaMonthReport.setWork(work); + if (workQualify <= 0) { + areaMonthReport.setWorkQualifyRate(0.0); + } else { + double workQualifyRate = BigDecimal.valueOf(workQualify / (double) work * 100L).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + areaMonthReport.setWorkQualifyRate(workQualifyRate); + } + } + + /** + * 任务月报-日常维护、巡检任务、缺陷数、消缺率、检修任务 + * + * @param areas + * @param areaMonthReport + */ + private void taskMonth(List areas, AreaMonthReportVo areaMonthReport, String startTime, String endTime) { + //通过线程池异步获取月报各模块内容 主要分为五块内容 + ExecutorService exe = Executors.newFixedThreadPool(POOL_QUANTITY); + //监控线程执行完后返回结果 + CountDownLatch countDownLatch = new CountDownLatch(POOL_QUANTITY); + // 日常维护 + exe.execute(() -> { + MaintainVo maintainVo = mainTaskStatisticService.getMaintain(startTime, endTime, areas); + int maintainSum = maintainVo.getMaintain(); + areaMonthReport.setRoutineMaintenance(maintainSum); + countDownLatch.countDown(); + }); + + // 巡检任务 + exe.execute(() -> { + Map map = new HashMap<>(); + map.put("startDate", startTime); + map.put("endDate", endTime); + map.put("deptList", areas); + R R = inspectTaskReportClient.getDutyInspectTask(map); + if (!R.isSuccess() || ObjectUtil.isEmpty(R.getData())) { + areaMonthReport.setInspect(0); + } else { + int inspect = R.getData().getInspectTaskSum(); + areaMonthReport.setInspect(inspect); + } + countDownLatch.countDown(); + }); + + // 消缺 + exe.execute(() -> { + DutyDefectVO defectVO = operPhenomenonService.getDutyDefect(startTime, endTime, areas); + int defectSum = defectVO.getDefectSum(); + int defect = defectVO.getDefect(); + areaMonthReport.setDefect(defectSum); + if (defectSum <= 0) { + areaMonthReport.setDefectRate(0.0); + } else { + double deletionRate = BigDecimal.valueOf(defect / defectSum * 100L).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + areaMonthReport.setDefectRate(deletionRate); + } + countDownLatch.countDown(); + }); + + // 检修 + exe.execute(() -> { + OverhaulVo overhaulVo = mainTaskStatisticService.getOverhaul(startTime, endTime, areas); + int overhaul = overhaulVo.getOverhaul(); + areaMonthReport.setMaintenanceTasks(overhaul); + countDownLatch.countDown(); + }); + + //所有模板数据获取完成后释放锁 + try { + countDownLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + Thread.currentThread().interrupt(); + } + exe.shutdown(); + } + + /** + * 安全检查 + * + * @param areas + * @param areaMonthReport + * @param startTime + * @param endTime + */ + private void getSecurityCheck(List areas, AreaMonthReportVo areaMonthReport, String startTime, String endTime) { + areaMonthReport.setSafetyMeeting(0); + areaMonthReport.setSelfReport(0); + areaMonthReport.setSkillTrainy(0); + areaMonthReport.setSecurityCheck(0); + // 站点归属机构集合 + Map map = new HashMap<>(); + map.put("startDate", startTime); + map.put("endDate", endTime); + map.put("deptList", areas); + // 调用安全大检查fegin接口 + R> R = safeCheckClient.getCount(map); + if (!R.isSuccess() || MapUtils.isEmpty(R.getData())) { + return; + } + // 安全生产会议 + areaMonthReport.setSafetyMeeting((Integer) R.getData().get("safetyMeetingNum")); + // 月度自查报告 + areaMonthReport.setSelfReport((Integer) R.getData().get("monthCheckNum")); + // 技能培训 + areaMonthReport.setSkillTrainy((Integer) R.getData().get("skillsTrainingNum")); + // 安全大检查 + areaMonthReport.setSecurityCheck((Integer) R.getData().get("bigCheckNum")); + } + + /** + * 获取设备试验数据 + * + * @param startTime + * @param endTime + * @param areas + * @param areaMonthReport + */ + private void getDeviceTry(String startTime, String endTime, List areas, AreaMonthReportVo areaMonthReport) { + areaMonthReport.setDeviceTry(0); + SafeEquipmentTrialDTO request = new SafeEquipmentTrialDTO(); + request.setDeptList(areas); + request.setStartTime(startTime); + request.setEndTime(endTime); + R R = safeEquipmentTrialClient.getCount(request); + if (!R.isSuccess() || ObjectUtil.isEmpty(R.getData())) { + return; + } + areaMonthReport.setDeviceTry(R.getData()); + } + + /** + * 获取去年时间 + * + * @return + */ + private String getLastyear(int year, String mon) { + try { + Date date = sdf.parse(mon + "-01 00:00:00"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - year); + calendar.add(Calendar.DATE, -calendar.get(Calendar.DATE) + 1); + return df.format(calendar.getTime()); + } catch (ParseException e) { + return mon; + } + } } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java index a6b7fa9..b5de466 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java @@ -3,6 +3,7 @@ package com.hnac.hzims.operational.util; import cn.afterturn.easypoi.entity.ImageEntity; import cn.hutool.core.lang.Assert; import lombok.extern.slf4j.Slf4j; +import org.apache.poi.xwpf.usermodel.XWPFTable; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtils; import org.jfree.chart.JFreeChart; @@ -17,6 +18,8 @@ import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge; import java.awt.*; import java.io.ByteArrayOutputStream; @@ -57,7 +60,85 @@ public class JFreeUtil { file.delete(); return buffer; } + public static ImageEntity pieChartByDouble(String title, Map datas, int width, int height) { + //创建主题样式 + StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); + //设置标题字体 + standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 20)); + //设置图例的字体 + standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15)); + //设置轴向的字体 + standardChartTheme.setLargeFont(new Font("宋体", Font.PLAIN, 15)); + //设置主题样式 + ChartFactory.setChartTheme(standardChartTheme); + + //根据jfree生成一个本地饼状图 + DefaultPieDataset pds = new DefaultPieDataset(); + datas.forEach(pds::setValue); + //图标标题、数据集合、是否显示图例标识、是否显示tooltips、是否支持超链接 + JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, false); + //设置抗锯齿 + chart.setTextAntiAlias(false); + PiePlot plot = (PiePlot) chart.getPlot(); + plot.setNoDataMessage("暂无数据"); + //忽略无值的分类 + plot.setIgnoreNullValues(true); + plot.setBackgroundAlpha(0f); + //设置标签阴影颜色 + plot.setShadowPaint(new Color(255, 255, 255)); + //设置标签生成器(默认{0}) + plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}")); + try { + ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, width, height); + } catch (IOException e1) { + log.error("生成饼状图失败!"); + } + ImageEntity imageEntity = new ImageEntity(imgToByte(tempImgPath), width, height); + Assert.notNull(imageEntity.getData(), "生成饼状图对象失败!"); + return imageEntity; + } + public static ImageEntity lineChartV2( String title,String[] monthArray,double[] value,int width, int height) { + // 创建数据 + DefaultCategoryDataset dataset = new DefaultCategoryDataset(); + dataset.addValue(1.0, "A", "Ⅰ"); + dataset.addValue(3.0, "A", "Ⅱ"); + dataset.addValue(5.0, "A", "Ⅲ"); + dataset.addValue(5.0, "A", "Ⅳ"); + dataset.addValue(5.0, "B", "Ⅰ"); + dataset.addValue(6.0, "B", "Ⅱ"); + dataset.addValue(10.0, "B", "Ⅲ"); + dataset.addValue(4.0, "B", "Ⅳ"); + + // 创建CategoryPlot对象 + CategoryPlot plot = new CategoryPlot(); + + // 添加第一个数据集并渲染为line + CategoryItemRenderer lineRenderer = new LineAndShapeRenderer(); + plot.setDataset(0, dataset); + plot.setRenderer(0, lineRenderer); + + // 添加第二个数据集并渲染为线条bar + CategoryItemRenderer baRenderer = new BarRenderer(); + plot.setDataset(1, dataset); + plot.setRenderer(1, baRenderer); + + // 设置坐标轴 + plot.setDomainAxis(new CategoryAxis("Time")); + plot.setRangeAxis(new NumberAxis("Value")); + + // 创建JFreeChart对象 + JFreeChart chart = new JFreeChart(plot); + + try { + ChartUtils.saveChartAsJPEG(new File(tempImgPath2), chart, width, height); + } catch (IOException e) { + e.printStackTrace(); + } + ImageEntity imageEntity = new ImageEntity(imgToByte(tempImgPath2), width, height); + Assert.notNull(imageEntity.getData(),"生成饼状图对象失败!"); + return imageEntity; + } public static ImageEntity pieChart(String title, Map datas, int width, int height) { //创建主题样式 @@ -179,534 +260,20 @@ public class JFreeUtil { Assert.notNull(imageEntity.getData(),"生成饼状图对象失败!"); return imageEntity; } -// public static ImageEntity lineChart( String title,String[] monthArray,double[] value,int width, int height) { -// //如果不使用Font,中文将显示不出来 -// Font font = new Font("新宋体", Font.BOLD, 15); -// // 创建数据 -// Map> datas = new HashMap>(); -// for (int i = 0; i < monthArray.length; i++) { -// Map map = new HashMap(); -// map.put("故障数量", value[i]); -// datas.put(monthArray[i], map); -// } -// JFreeChart chart = createLineChart(title, datas, "月份", "故障次数(次)", font); -// try { -// ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, 800, 600); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// ImageEntity imageEntity = new ImageEntity(imgToByte(), 800, 600); -// Assert.notNull(imageEntity.getData(),"生成饼状图对象失败!"); -// return imageEntity; -// } -// -// public static JFreeChart createLineChart(String title, Map> data, String type, String unit, Font font) { -// try { -// DefaultCategoryDataset ds = new DefaultCategoryDataset(); -// Set>> set1 = data.entrySet(); -// Iterator iterator1 = set1.iterator(); -// Iterator iterator2; -// HashMap map; -// Set> set2; -// Map.Entry entry1; -// Map.Entry entry2; -// while (iterator1.hasNext()) { -// entry1 = (Map.Entry) iterator1.next(); -// map = (HashMap) entry1.getValue(); -// set2 = map.entrySet(); -// iterator2 = set2.iterator(); -// while (iterator2.hasNext()) { -// entry2 = (Map.Entry) iterator2.next(); -// ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString()); -// } -// } -// -// //创建折线图,折线图分水平显示和垂直显示两种 -// // //2D折线图 -// JFreeChart chart = ChartFactory.createLineChart(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, true); -// // //3D折线图 -//// JFreeChart chart2 = ChartFactory.createLineChart3D(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, false); -// -// //设置整个图片的标题字体 -// chart.getTitle().setFont(font); -// -// //设置提示条字体 -// font = new Font("宋体", Font.BOLD, 15); -// chart.getLegend().setItemFont(font); -// -// //得到绘图区 -// CategoryPlot plot = (CategoryPlot) chart.getPlot(); -// //得到绘图区的域轴(横轴),设置标签的字体 -// plot.getDomainAxis().setLabelFont(font); -// -// // 设置背景透明度 -// plot.setBackgroundAlpha(0.1f); -// // 设置网格横线颜色 -// plot.setRangeGridlinePaint(Color.gray); -// // 设置网格横线大小 -// plot.setDomainGridlineStroke(new BasicStroke(0.2F)); -// plot.setRangeGridlineStroke(new BasicStroke(0.2F)); -// -// //设置横轴标签项字体 -// plot.getDomainAxis().setTickLabelFont(font); -// -// // 生成折线图上的数字 -// //绘图区域(红色矩形框的部分) -// LineAndShapeRenderer lineAndShapeRenderer = (LineAndShapeRenderer) plot.getRenderer(); -// lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); -// //设置图表上的数字可见 -// lineAndShapeRenderer.setBaseItemLabelsVisible(true); -// //设置图表上的数字字体 -// lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体", Font.BOLD, 15)); -// -// //设置折线图拐角上的正方形 -// //创建一个正方形 -// Rectangle shape = new Rectangle(4, 4); -// lineAndShapeRenderer.setSeriesShape(0, shape); -// //设置拐角上图形可见 -// lineAndShapeRenderer.setSeriesShapesVisible(0, true); -// -// /*// 获取显示线条的对象 -// LineAndShapeRenderer lasp = (LineAndShapeRenderer) plot.getRenderer(); -// // 设置拐点是否可见/是否显示拐点 -// lasp.setBaseShapesVisible(true); -// // 设置拐点不同用不同的形状 -// lasp.setDrawOutlines(true); -// // 设置线条是否被显示填充颜色 -// lasp.setUseFillPaint(true); -// // 设置拐点颜色 -// lasp.setBaseFillPaint(Color.blue);//蓝色*/ -// //设置范围轴(纵轴)字体 -// font = new Font("宋体", Font.BOLD, 18); -// plot.getRangeAxis().setLabelFont(font); -//// plot.setForegroundAlpha(1.0f); -// return chart; -// } catch (Exception e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 生成折线图 -// * 1.解析数据
-// * 2.迭代数据,产出图片数据流,并添加到List
-// * -// * @throws IOException -// */ -// public ArrayList createLineAndShapeChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { -// ArrayList list = new ArrayList(); -// byte[] bytes = new byte[]{}; -// // 解析数据 -// Map map = this.parseDataForBarPage(data, rowKeys, columnKeys); -// int pageNum = Integer.parseInt("" + map.get("pageNum")); -// // 迭代,产生图片数据流 -// for (int i = 0; i < pageNum; i++) { -// bytes = createSingleLineAndShapeChart((double[][]) (map.get("data" + i)), (String[]) (map.get("rowKeys" + i)), -// (String[]) (map.get("columnKeys" + i)), entity); -// list.add(bytes); -// } -// return list; -// } -// -// /** -// * 生成单个折线图数据流 -// * -// * @param data -// * @param rowKeys -// * @param columnKeys -// * @param entity -// * @return -// * @throws IOException -// */ -// public byte[] createSingleLineAndShapeChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { -// CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); -// JFreeChart chart = createTimeXYChar(dataset, entity); -// byte[] bytes = this.createImage(chart, entity); -// return bytes; -// } -// -// -// /** -// * 生成柱状图
-// * 1.解析数据
-// * 2.迭代数据,产出图片数据流,并添加到List
-// * -// * @param data 数据 -// * @param rowKeys 行 -// * @param columnKeys 列 -// * @param entity 图片配置对象 -// * @return 包含多个图片数据流的List -// * @throws IOException -// */ -// public ArrayList createStackedBarChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { -// // 解析数据 -// ArrayList list = new ArrayList(); -// byte[] bytes = new byte[]{}; -// Map map = this.parseDataForBarPage(data, rowKeys, columnKeys); -// int pageNum = Integer.parseInt("" + map.get("pageNum")); -// // 迭代数据,产出图片数据流,并添加到List -// for (int i = 0; i < pageNum; i++) { -// bytes = createSingleStackedBarChart((double[][]) (map.get("data" + i)), (String[]) (map.get("rowKeys" + i)), -// (String[]) (map.get("columnKeys" + i)), entity); -// list.add(bytes); -// } -// return list; -// } -// -// /** -// * 解析生成柱状图分页数据 -// * -// * @param data -// * @param rowKeys -// * @param columnKeys -// * @return -// */ -// private Map parseDataForBarPage(double[][] data, String[] rowKeys, String[] columnKeys) { -// Map map = new HashMap(); -// -// double[][] pageData = null; -// String[] pageColumn = null; -// -// int sumColumnNum = columnKeys.length; // 总列数 -// int indexNum = Config.getInt("image.export.pagesize", 10);// 分页的列数 -// int pageNum = sumColumnNum % indexNum == 0 ? sumColumnNum / indexNum : sumColumnNum / indexNum + 1; // 分页数 -// int rowNum = rowKeys.length; -// -// // log.debug("data.length="+data.length+"sumColumnNum="+sumColumnNum+" indexNum="+indexNum+" pageNum="+pageNum+" rowNum="+rowNum+" "); -// -// // 解析传递过来的数据 -// for (int i = 0; i < pageNum; i++) { -// int columnNum = (sumColumnNum - i * indexNum) / indexNum > 0 ? indexNum : (sumColumnNum - i * indexNum) % indexNum;//当前页列数 -// pageData = new double[rowNum][columnNum]; -// // 取数据值 -// for (int j = 0; j < rowNum; j++) { -// pageColumn = new String[columnNum]; -// for (int k = 0; k < columnNum; k++) { -// pageData[j][k] = data[j][k + i * indexNum]; // 数据 -// } -// } -// // 取列值 -// for (int j = 0; j < columnNum; j++) { -// pageColumn[j] = columnKeys[j + i * indexNum]; // 列 -// } -// // 保存数据并返回 -// map.put("data" + i, pageData); -// map.put("rowKeys" + i, rowKeys); -// map.put("columnKeys" + i, pageColumn); -// } -// // 保存分页数 -// map.put("pageNum", pageNum); -// return map; -// } -// -// /** -// * 解析生成折线图分页数据 -// * -// * @param data -// * @param rowKeys -// * @param columnKeys -// * @return -// */ -// private Map parseDataForLinePage(double[][] data, String[] rowKeys, String[] columnKeys) { -// Map map = new HashMap(); -// -// double[][] pageData = null; -// String[] pageColumn = null; -// -// int sumColumnNum = columnKeys.length; // 总列数 -// int indexNum = Config.getInt("image.export.pagesize", 10);// 分页的列数 -// int pageNum = sumColumnNum % indexNum == 0 ? sumColumnNum / indexNum : sumColumnNum / indexNum + 1; // 分页数 -// int rowNum = rowKeys.length; -// -// // log.debug("data.length="+data.length+"sumColumnNum="+sumColumnNum+" indexNum="+indexNum+" pageNum="+pageNum+" rowNum="+rowNum+" "); -// -// // 解析传递过来的数据 -// for (int i = 0; i < pageNum; i++) { -// int columnNum = (sumColumnNum - i * indexNum) / indexNum > 0 ? indexNum : (sumColumnNum - i * indexNum) % indexNum;//当前页列数 -// pageData = new double[rowNum][columnNum]; -// // 取数据值 -// for (int j = 0; j < rowNum; j++) { -// pageColumn = new String[columnNum]; -// for (int k = 0; k < columnNum; k++) { -// pageData[j][k] = data[j][k + i * indexNum]; // 数据 -// } -// } -// // 取列值 -// for (int j = 0; j < columnNum; j++) { -// pageColumn[j] = columnKeys[j + i * indexNum]; // 列 -// } -// // 保存数据并返回 -// map.put("data" + i, pageData); -// map.put("rowKeys" + i, rowKeys); -// map.put("columnKeys" + i, pageColumn); -// } -// // 保存分页数 -// map.put("pageNum", pageNum); -// return map; -// } -// -// /** -// * 生成单个堆栈柱状图 -// * -// * @return 图片数据流 -// * @throws IOException -// */ -// public byte[] createSingleStackedBarChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { -// CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); -// JFreeChart chart = createStackedBarChart(dataset, entity); -// byte[] bytes = this.createImage(chart, entity); -// return bytes; -// } -// -// // 柱状图,折线图 数据集 -// private CategoryDataset getBarData(double[][] data, String[] rowKeys, -// String[] columnKeys) { -// return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); -// -// } -// -// /** -// * 判断文件夹是否存在,如果不存在则新建 -// * -// * @param chartPath -// */ -// private void isChartPathExist(String chartPath) { -// File file = new File(chartPath); -// if (!file.exists()) { -// file.mkdirs(); -// } -// } -// -// /** -// * 折线图 -// */ -// private JFreeChart createTimeXYChar(CategoryDataset xyDataset, ChartEntity entity) { -// -// JFreeChart chart = ChartFactory.createLineChart( -// entity.getTitle(), -// entity.getXname(), -// entity.getYname(), -// xyDataset, -// PlotOrientation.VERTICAL, -// true, -// true, -// false); -// -// chart.setTextAntiAlias(false); -// chart.setBackgroundPaint(Color.WHITE); -// -// CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); -// // 没有数据时显示 -// this.configNoData(chart, "没有查询到数据 !"); -// -// // x轴 // 分类轴网格是否可见 -// categoryplot.setDomainGridlinesVisible(true); -// // y轴 //数据轴网格是否可见 -// categoryplot.setRangeGridlinesVisible(true); -// -// categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩 -// -// categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩 -// -// categoryplot.setBackgroundPaint(Color.lightGray); -// -// -// // 配置字体 -// this.configFont(chart); -// -// // x轴设置 -// CategoryAxis domainAxis = categoryplot.getDomainAxis(); -// -// // 设置距离图片左端距离 -// domainAxis.setLowerMargin(0.0); -// // 设置距离图片右端距离 -// domainAxis.setUpperMargin(0.0); -// domainAxis.setTickLabelPaint(Color.BLUE); -// domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的label斜显示 -// -// NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); -// numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); -// numberaxis.setAutoRangeIncludesZero(true); -// -// // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!! -// LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer(); -// lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见 -// lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见 -// -// // 显示折点数据 -// lineandshaperenderer.setBaseItemLabelGenerator(new -// StandardCategoryItemLabelGenerator()); -// lineandshaperenderer.setBaseItemLabelsVisible(true); -// -// return chart; -// } -// -// /** -// * 堆栈柱状图 -// */ -// private JFreeChart createStackedBarChart(CategoryDataset dataset, ChartEntity entity) { -// -// JFreeChart chart = ChartFactory.createStackedBarChart3D( -// entity.getTitle(), -// entity.getXname(), -// entity.getYname(), -// dataset, -// PlotOrientation.VERTICAL, -// true, -// false, -// false); -// -// // 没有数据配置 -// this.configNoData(chart, "没有查询到数据 !"); -// -// // 配置字体 -// this.configFont(chart); -// -// // 配置 Renderer -// this.configBarRenderer(chart); -// -// // 其他配置 -// this.configOtherForBar(chart); -// -// return chart; -// } -// -// /** -// * 配置字体 -// * -// * @param chart JFreeChart 对象 -// */ -// private void configFont(JFreeChart chart) { -// // 配置字体 -// Font xfont = new Font("宋体", Font.PLAIN, 12);// X轴 -// Font yfont = new Font("宋体", Font.PLAIN, 12);// Y轴 -// Font kfont = new Font("宋体", Font.PLAIN, 12);// 底部 -// Font titleFont = new Font("隶书", Font.BOLD, 25); // 图片标题 -// CategoryPlot plot = chart.getCategoryPlot();// 图形的绘制结构对象 -// -// // 图片标题 -// chart.setTitle(new TextTitle(chart.getTitle().getText(), titleFont)); -// -// // 底部 -// chart.getLegend().setItemFont(kfont); -// -// // X 轴 -// CategoryAxis domainAxis = plot.getDomainAxis(); -// domainAxis.setLabelFont(xfont);// 轴标题 -// domainAxis.setTickLabelFont(xfont);// 轴数值 -// domainAxis.setTickLabelPaint(Color.BLUE); // 字体颜色 -// domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的label斜显示 -// -// // Y 轴 -// ValueAxis rangeAxis = plot.getRangeAxis(); -// rangeAxis.setLabelFont(yfont); -// rangeAxis.setLabelPaint(Color.BLUE); // 字体颜色 -// rangeAxis.setTickLabelFont(yfont); -// -// } -// -// /** -// * 配置柱状图 -// * -// * @param chart -// */ -// private void configBarRenderer(JFreeChart chart) { -// -// CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); -// // 自定义显示柱子上的总值 -// ExtendedStackedBarRenderer extendedstackedbarrenderer = new ExtendedStackedBarRenderer(); -// extendedstackedbarrenderer.setBaseItemLabelsVisible(true); -// extendedstackedbarrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); -// extendedstackedbarrenderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); -// categoryplot.setRenderer(extendedstackedbarrenderer); -// -// BarRenderer barrenderer = (BarRenderer) categoryplot.getRenderer(); -// barrenderer.setDrawBarOutline(false); -// barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); -// barrenderer.setBaseItemLabelsVisible(true); -// barrenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER)); -// barrenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER)); -// -// // 柱子显示数值 -// // barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",new DecimalFormat("0.0%"))); -// // barrenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator()); -// barrenderer.setItemLabelFont(new Font("Arial Unicode MS", Font.PLAIN, 9)); -// barrenderer.setItemLabelsVisible(true); -// -// // 如果数值没有显示空间,设置显示格式 -// // ItemLabelPosition itemLabelPositionFallback=new ItemLabelPosition( -// // ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT, -// // TextAnchor.HALF_ASCENT_LEFT,0D); -// // barrenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback); -// // barrenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback); -// -// categoryplot.setRenderer(barrenderer); -// } -// -// /** -// * 配置没有数据时的显示信息 -// * -// * @param chart -// */ -// private void configNoData(JFreeChart chart, String message) { -// CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); -// // 没有数据时的显示 -// categoryplot.setNoDataMessage(message); -// categoryplot.setNoDataMessageFont(new Font("黑体", Font.BOLD, 25)); -// } -// -// /** -// * 其他配置 -// * -// * @param chart -// */ -// private void configOtherForBar(JFreeChart chart) { -// -// chart.setTextAntiAlias(false); // 图例字体清晰 -// -// chart.setBackgroundPaint(Color.WHITE); // 背景颜色 -// -// CategoryPlot plot = chart.getCategoryPlot();// 图形的绘制结构对象 -// NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis(); -// numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); -// numberaxis.setAutoRangeIncludesZero(true); -// } -// -// /** -// * 创建图片的数据流 -// * -// * @param chart -// * @param entity 图片配置对象 -// * @return 图片数据流 -// * @throws IOException -// */ -// private byte[] createImage(JFreeChart chart, ChartEntity entity) throws IOException { -// return ChartUtilities.encodeAsPNG(chart.createBufferedImage(entity.getWidth(), entity.getHeight())); -// } -// -// /** -// * 创建图片文件到硬盘 -// * -// * @param chart -// * @param entity -// * @throws IOException -// */ -// private void createImageFile(JFreeChart chart, ChartEntity entity) throws IOException { -// FileOutputStream fos_jpg = null; -// try { -// isChartPathExist(tempImgPath); -// String chartName = tempImgPath + entity.getFileName(); -// fos_jpg = new FileOutputStream(chartName); -// ChartUtilities.writeChartAsJPEG(fos_jpg, chart, entity.getWidth(), entity.getHeight()); -// } catch (Exception e) { -// e.printStackTrace(); -// } finally { -// try { -// fos_jpg.close(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } + + public static void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) { + if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) { + return; + } + //合并行单元格的第一个单元格 + CTVMerge startMerge = CTVMerge.Factory.newInstance(); + startMerge.setVal(STMerge.RESTART); + //合并行单元格的第一个单元格之后的单元格 + CTVMerge endMerge = CTVMerge.Factory.newInstance(); + endMerge.setVal(STMerge.CONTINUE); + table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge); + for (int i = beginRowIndex + 1; i <= endRowIndex; i++) { + table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge); + } + } } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/TimeUtils.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/TimeUtils.java index 74323ac..cd2ef2f 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/TimeUtils.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/TimeUtils.java @@ -1,26 +1,111 @@ package com.hnac.hzims.operational.util; +import org.springblade.core.tool.utils.DateUtil; + +import java.util.Calendar; import java.util.Date; public class TimeUtils { - private static int sheet1NowRow, sheet2NowRow; - - - /** - * 相差时数 - * @author ty - * @param endDate - * @param nowDate - * @return - */ - public static Long getDifferTime(Date nowDate,Date endDate ) { - long nh = 1000 * 60 * 60L; - // 获得两个时间的毫秒时间差异 - long diff = endDate.getTime() - nowDate.getTime(); - // 计算差多少小时 - long hour = diff/ nh; - return hour; - } + private static int sheet1NowRow, sheet2NowRow; + + + /** + * 相差时数 + * + * @param endDate + * @param nowDate + * @return + * @author ty + */ + public static Long getDifferTime(Date nowDate, Date endDate) { + long nh = 1000 * 60 * 60L; + // 获得两个时间的毫秒时间差异 + long diff = endDate.getTime() - nowDate.getTime(); + // 计算差多少小时 + long hour = diff / nh; + return hour; + } + + public static String getYear(Integer year) { + // 创建一个Calendar对象 + Calendar calendar = Calendar.getInstance(); + // 设置年份 + calendar.set(Calendar.YEAR, year); + // 设置月份为1(即一月) + calendar.set(Calendar.MONTH, Calendar.JANUARY); + // 设置日期为1 + calendar.set(Calendar.DATE, 1); + // 设置时间为0点0分0秒 + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String start = DateUtil.format(calendar.getTime(), DateUtil.PATTERN_DATE) + " 00:00:00"; + return start; + } + + public static String getYearEnd(Integer year) { + // 创建一个Calendar对象 + Calendar calendar = Calendar.getInstance(); + // 设置年份 + calendar.set(Calendar.YEAR, year); + // 设置月份为12(即十二月) + calendar.set(Calendar.MONTH, Calendar.DECEMBER); + // 设置日期为31 + calendar.set(Calendar.DATE, 31); + String end = DateUtil.format(calendar.getTime(), DateUtil.PATTERN_DATE) + " 00:00:00"; + return end; + } + public static String getYearEndV2(Integer year) { + // 创建一个Calendar对象 + Calendar calendar = Calendar.getInstance(); + // 设置年份 + calendar.set(Calendar.YEAR, year); + // 设置月份为12(即十二月) + calendar.set(Calendar.MONTH, Calendar.DECEMBER); + // 设置日期为31 + calendar.set(Calendar.DATE, 31); + String end = DateUtil.format(calendar.getTime(), DateUtil.PATTERN_DATE) + " 23:59:59"; + return end; + } + + public static String getMonthStart(Integer year, Integer mon) { + // 创建一个Calendar对象 + Calendar calendar = Calendar.getInstance(); + // 设置年份 + calendar.set(Calendar.YEAR, year); + // 设置月份 + calendar.set(Calendar.MONTH,mon); + // 设置日期为1 + calendar.set(Calendar.DATE, 1); + String start = DateUtil.format(calendar.getTime(), DateUtil.PATTERN_DATE) + " 00:00:00"; + return start; + } + public static String getMonthEnd(Integer year, Integer mon) { + // 创建一个Calendar对象 + Calendar calendar = Calendar.getInstance(); + // 设置年份 + calendar.set(Calendar.YEAR, Integer.valueOf(year)); + // 设置月份为1(即一月) + calendar.set(Calendar.MONTH, mon+1); + calendar.set(Calendar.DAY_OF_MONTH, 1); + // 将日期对象减去一天,即为当月的最后一天 + calendar.add(Calendar.DAY_OF_MONTH, -1); + String end = DateUtil.format(calendar.getTime(), DateUtil.PATTERN_DATE) + " 00:00:00"; + return end; + } + public static String getMonthEndV2(Integer year, Integer mon) { + // 创建一个Calendar对象 + Calendar calendar = Calendar.getInstance(); + // 设置年份 + calendar.set(Calendar.YEAR, Integer.valueOf(year)); + // 设置月份为1(即一月) + calendar.set(Calendar.MONTH, mon+1); + calendar.set(Calendar.DAY_OF_MONTH, 1); + // 将日期对象减去一天,即为当月的最后一天 + calendar.add(Calendar.DAY_OF_MONTH, -1); + String end = DateUtil.format(calendar.getTime(), DateUtil.PATTERN_DATE) + " 23:59:59"; + return end; + } }