diff --git a/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpSubmitResultDTO.java b/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpSubmitResultDTO.java new file mode 100644 index 0000000..d951045 --- /dev/null +++ b/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpSubmitResultDTO.java @@ -0,0 +1,43 @@ +package com.hnac.hzims.fdp.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * 模型DTO + * + * @author xiashandong + * @created 2021-05-25 17:38 + **/ +@Data +public class FdpSubmitResultDTO { + + private static final long serialVersionUID = 1L; + + /** + * 站点ID + */ + @ApiModelProperty(value = "站点ID", required = true) + private String stationId; + /** + * 开始诊断的故障ID + */ + @ApiModelProperty(value = "开始诊断的故障ID", required = true) + private String faultId; + /** + * 本次诊断是否成功 + */ + @ApiModelProperty(value = "本次诊断是否成功 1:成功,0:失败", required = true) + private Integer success; + /** + * 本次诊断出的根因 + */ + @ApiModelProperty(value = "本次诊断出的根因;诊断失败可为空字符串", required = true) + private String rootCause; + /** + *诊断的补充说明 + */ + @ApiModelProperty(value = "诊断的补充说明", required = true) + private String comment; + +} diff --git a/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpTaskDTO.java b/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpTaskDTO.java index 00c236b..e157e21 100644 --- a/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpTaskDTO.java +++ b/hzims-service-api/equipment-api/src/main/java/com/hnac/hzims/fdp/dto/FdpTaskDTO.java @@ -1,6 +1,7 @@ package com.hnac.hzims.fdp.dto; import com.hnac.hzims.fdp.entity.FdpTaskEntity; +import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; @@ -15,5 +16,7 @@ import lombok.EqualsAndHashCode; public class FdpTaskDTO extends FdpTaskEntity { private static final long serialVersionUID = 1L; + @ApiModelProperty(value = "站点Id ") + private String station; } diff --git a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindScoreVo.java b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindScoreVo.java index d245f36..8493839 100644 --- a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindScoreVo.java +++ b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindScoreVo.java @@ -15,12 +15,6 @@ import java.util.List; @ApiModel(value = "风电集团/区域指标对象") public class WindScoreVo { - @ApiModelProperty(value = "机构Id") - private Long departId; - - @ApiModelProperty(value = "机构名称") - private String departName; - @ApiModelProperty(value = "站点数量") private Integer stationCount; diff --git a/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindSubordinateVo.java b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindSubordinateVo.java new file mode 100644 index 0000000..68de51f --- /dev/null +++ b/hzims-service-api/hzims-operational-api/src/main/java/com/hnac/hzims/operational/main/vo/WindSubordinateVo.java @@ -0,0 +1,59 @@ +package com.hnac.hzims.operational.main.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.NullSerializer; +import com.hnac.hzims.hzimsweather.response.weather.Daily; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author ysj + */ +@Data +@ApiModel(value = "风电集团/区域占比") +public class WindSubordinateVo { + + @ApiModelProperty(value = "机构Id") + private Long departId; + + @ApiModelProperty(value = "机构名称") + private String departName; + + @ApiModelProperty(value = "地市编码") + private String areaCode; + + @ApiModelProperty(value = "地市名称") + private String areaName; + @ApiModelProperty(value = "经度(东经)") + + @JsonSerialize(nullsUsing = NullSerializer.class) + private Float lgtd; + + @ApiModelProperty(value = "纬度(北纬)") + @JsonSerialize(nullsUsing = NullSerializer.class) + private Float lttd; + + @ApiModelProperty(value = "温度") + private String temp; + + @ApiModelProperty(value = "天气") + private List weather; + + @ApiModelProperty(value = "发电量") + private Double generation; + + @ApiModelProperty(value = "集团/区域发电占比") + private Double generationRate; + + @ApiModelProperty(value = "发电完成率") + private Double generationComplete; + + @ApiModelProperty(value = "风机利用率") + private Double fanUse; + + @ApiModelProperty(value = "厂用电率") + private Double factoryUse; +} diff --git a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpMonitorController.java b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpMonitorController.java index c43348a..4657f33 100644 --- a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpMonitorController.java +++ b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpMonitorController.java @@ -258,10 +258,11 @@ public class FdpMonitorController extends BladeController { return service.getMonitorFault(realId,stationId); } + //仅集中推送告警中诊断接口使用 @PostMapping("/updateFaultStateAll") @ApiOperationSupport(order = 170) public R updateFaultStateAll(@RequestBody FdpTaskDTO fdpTaskDTO) { - return service.updateFaultStateAll(fdpTaskDTO); + return service.updateFaultStateAllV2(fdpTaskDTO); } @PostMapping("/updateFaultState") diff --git a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpTaskController.java b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpTaskController.java index 2dd18d7..8a4dbde 100644 --- a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpTaskController.java +++ b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/controller/FdpTaskController.java @@ -71,7 +71,7 @@ public class FdpTaskController extends BladeController { @ApiOperationSupport(order = 30) @ApiOperation(value = "修改") public R update(@Valid @RequestBody FdpTaskDTO req) { - return R.status(service.updateById(req)); + return service.submitResult(req); } /** diff --git a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpMonitorService.java b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpMonitorService.java index d8f16cf..6dda785 100644 --- a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpMonitorService.java +++ b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpMonitorService.java @@ -144,6 +144,7 @@ public interface IFdpMonitorService extends BaseService { List getFdpMonitorList(List stationIdList,List fdpDeviceCodeList); R updateFaultStateAll(FdpTaskDTO taskDTO); + R updateFaultStateAllV2(FdpTaskDTO taskDTO); R updateFaultState(@RequestBody DiagnoseFaultReq diagnoseFaultReq); diff --git a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpTaskService.java b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpTaskService.java index 6282543..73ba3d9 100644 --- a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpTaskService.java +++ b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/IFdpTaskService.java @@ -32,4 +32,6 @@ public interface IFdpTaskService extends BaseService { R getTaskStatistics(TaskStatisticsVo statisticsVo); R getTaskData(TaskStatisticsVo statisticsVo,Query query); + + R submitResult(FdpTaskDTO req); } diff --git a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpMonitorServiceImpl.java b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpMonitorServiceImpl.java index b97663e..2073ff6 100644 --- a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpMonitorServiceImpl.java +++ b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpMonitorServiceImpl.java @@ -12,6 +12,7 @@ import com.google.common.collect.Lists; import com.hnac.hzims.EquipmentConstants; import com.hnac.hzims.equipment.entity.EmInfoEntity; import com.hnac.hzims.equipment.service.IEmInfoService; +import com.hnac.hzims.equipment.vo.DiagnoseStatusVo; import com.hnac.hzims.fdp.constants.DeviceInstanceTypeConstant; import com.hnac.hzims.fdp.dto.FdpFaultRealDataDTO; import com.hnac.hzims.fdp.dto.FdpMonitorDTO; @@ -385,7 +386,70 @@ public class FdpMonitorServiceImpl extends BaseServiceImpl fdpMonitorEntityRealTimeList = this.baseMapper.getFdpMonitorEntityRealTimeList(null, null, null, stationIdList, fdpDeviceCodeList); return fdpMonitorEntityRealTimeList; } - + @Override + public R updateFaultStateAllV2(FdpTaskDTO taskDTO) { + if (StringUtil.isEmpty(taskDTO.getFaultId())) { + return R.fail("未传入faultId参数"); + } + /**获取故障对象**/ + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(FdpFaultEntity::getFdpId, taskDTO.getFaultId()).last("limit 1"); + FdpFaultEntity fdpFaultEntity = fdpFaultService.getOne(wrapper); + if (ObjectUtil.isEmpty(fdpFaultEntity)) { + throw new ServiceException("获取对应故障对象失败"); + } + //拿到最近一次未完成的任务 + FdpTaskEntity fdpTaskEntity = fdpTaskService.getOne(new LambdaQueryWrapper() {{ + eq(FdpTaskEntity::getFaultId, taskDTO.getFaultId()); + eq(FdpTaskEntity::getIsDeleted, 0); + in(FdpTaskEntity::getStatus, 1, 2);//未开始或者未完成 + orderByDesc(FdpTaskEntity::getCreateTime); + last("limit 1"); + }}); + String key; + if (Func.isNotEmpty(fdpTaskEntity)) { + Boolean hasKey = redisTemplate.hasKey(KEY_FOR_FDP_TASK_ID + "_" + fdpTaskEntity.getId().toString()); + //Redis中存在,该任务没过期。用该任务Id + if (hasKey) { + key = fdpTaskEntity.getId().toString(); + } else { + //该任务过期,更改状态为过期,新增一个任务 + fdpTaskEntity.setStatus(4); + fdpTaskService.updateById(fdpTaskEntity); + boolean flag = fdpTaskService.save(taskDTO); + if (!flag) { + return R.fail("诊断任务保存失败"); + } + key = taskDTO.getId().toString(); + redisTemplate.opsForValue().set(KEY_FOR_FDP_TASK_ID + "_" + key, key); + Boolean expire = redisTemplate.expire(KEY_FOR_FDP_TASK_ID + "_" + key,3, TimeUnit.DAYS); + System.out.println(expire); + } + } else { + //没有未完成的任务,新增一个任务 + boolean flag = fdpTaskService.save(taskDTO); + if (!flag) { + return R.fail("诊断任务保存失败"); + } + key = taskDTO.getId().toString(); + redisTemplate.opsForValue().set(KEY_FOR_FDP_TASK_ID + "_" + key, key); + redisTemplate.expire(KEY_FOR_FDP_TASK_ID + "_" + key, 3, TimeUnit.DAYS); + } + R r2 = new R(); + r2.setCode(200); + r2.setSuccess(true); + r2.setMsg("获取信息成功"); + DiagnoseStatusVo diagnoseStatusVo = new DiagnoseStatusVo(); + R nextstep = fdpFaultService.getNextStepWithTree(fdpFaultEntity.getFdpId(), fdpFaultEntity.getStationId()); + diagnoseStatusVo.setStatus(4); + diagnoseStatusVo.setMessage("诊断成功"); + diagnoseStatusVo.setData(nextstep.getData()); + r2.setData(diagnoseStatusVo); + key = taskDTO.getId().toString(); + redisTemplate.opsForValue().set(fdpReturnValuePath + "_" + key, JSONObject.toJSONString(r2)); + redisTemplate.expire(fdpReturnValuePath + "_" + key, 30, TimeUnit.MINUTES); + return nextstep; + } @Override public R updateFaultStateAll(FdpTaskDTO taskDTO) { if (StringUtil.isEmpty(taskDTO.getFaultId())) { diff --git a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpTaskServiceImpl.java b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpTaskServiceImpl.java index ca9e8c3..d589915 100644 --- a/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpTaskServiceImpl.java +++ b/hzims-service/equipment/src/main/java/com/hnac/hzims/fdp/service/impl/FdpTaskServiceImpl.java @@ -1,9 +1,11 @@ package com.hnac.hzims.fdp.service.impl; +import com.alibaba.fastjson.JSONObject; import com.aliyun.oss.ServiceException; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; +import com.hnac.hzims.fdp.dto.FdpSubmitResultDTO; import com.hnac.hzims.fdp.dto.FdpTaskDTO; import com.hnac.hzims.fdp.entity.FdpTaskEntity; import com.hnac.hzims.fdp.mapper.FdpTaskMapper; @@ -16,6 +18,8 @@ import com.hnac.hzims.fdp.wrapper.FdpTaskWrapper; import com.hnac.hzims.operational.defect.entity.OperPhenomenonEntity; import com.hnac.hzims.operational.defect.feign.IOperPhenomenonClient; import com.hnac.hzims.operational.defect.vo.OperPhenomenonVO; +import com.hnac.hzims.util.HttpClientUtils; +import com.hnac.hzims.util.pojo.HttpResponse; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springblade.core.mp.base.BaseServiceImpl; @@ -27,6 +31,7 @@ import org.springblade.core.tool.utils.Func; import org.springblade.core.tool.utils.ObjectUtil; import org.springblade.core.tool.utils.StringUtil; import org.springblade.system.feign.ISysClient; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.math.BigDecimal; @@ -43,224 +48,267 @@ import java.util.stream.Collectors; @AllArgsConstructor @Slf4j public class FdpTaskServiceImpl extends BaseServiceImpl implements IFdpTaskService { - private final IOperPhenomenonClient operPhenomenonClient; - private final ISysClient sysClient; - private IDiagnoseProxy diagnoseProxy; + private final IOperPhenomenonClient operPhenomenonClient; + private final ISysClient sysClient; + private IDiagnoseProxy diagnoseProxy; - @Override - public R doSave(FdpTaskDTO req) { - boolean flag = super.save(req); - if(flag){ - DiagnoseFaultReq diagnoseFaultReq = new DiagnoseFaultReq(); - diagnoseFaultReq.setTaskId(req.getId().toString()); - log.info("存入taskId为:{}",req.getId().toString()); - diagnoseFaultReq.setFaultId(req.getFaultId()); - diagnoseFaultReq.setConfidence(1.0); - diagnoseFaultReq.setLifeTime(1); - diagnoseFaultReq.setPriority(2); - diagnoseProxy.updateFaultState(diagnoseFaultReq); - } - return flag ? R.data(req.getId()) : R.fail("FAIL"); - } + @Value("${url.submitResult}") + public String submitResult; - @Override - public R detail(Long id) { - FdpTaskEntity detail = super.getById(id); - return R.data(FdpTaskWrapper.build().entityVO(detail)); - } + @Override + public R doSave(FdpTaskDTO req) { + boolean flag = super.save(req); + if (flag) { + DiagnoseFaultReq diagnoseFaultReq = new DiagnoseFaultReq(); + diagnoseFaultReq.setTaskId(req.getId().toString()); + log.info("存入taskId为:{}", req.getId().toString()); + diagnoseFaultReq.setFaultId(req.getFaultId()); + diagnoseFaultReq.setConfidence(1.0); + diagnoseFaultReq.setLifeTime(1); + diagnoseFaultReq.setPriority(2); + diagnoseProxy.updateFaultState(diagnoseFaultReq); + } + return flag ? R.data(req.getId()) : R.fail("FAIL"); + } - @Override - public boolean updateTaskStatus(Long id) { - FdpTaskEntity detail = super.getById(id); - try{ - detail.setStatus(1); - boolean flag = super.saveOrUpdate(detail); - return flag; - } - catch (NullPointerException e){ - throw new ServiceException("该id无法获取到智能诊断任务记录!"); - } - } + @Override + public R detail(Long id) { + FdpTaskEntity detail = super.getById(id); + return R.data(FdpTaskWrapper.build().entityVO(detail)); + } - @Override - public R> list(FdpTaskDTO req, Query query) { - Wrapper queryWrapper = new LambdaQueryWrapper() {{ - orderByDesc(FdpTaskEntity::getId); - //name,emId,faultId,reasonId,satisfaction - if (StringUtil.isNotBlank(req.getName())) { - like(FdpTaskEntity::getName, req.getName()); - } - if (req.getEmCode() != null) { - eq(FdpTaskEntity::getEmCode, req.getEmCode()); - } - if (StringUtil.isNotBlank(req.getFaultId())) { - eq(FdpTaskEntity::getFaultId, req.getFaultId()); - } - if (StringUtil.isNotBlank(req.getReasonId())) { - eq(FdpTaskEntity::getReasonId, req.getReasonId()); - } - if (req.getSatisfaction() != null) { - eq(FdpTaskEntity::getSatisfaction, req.getSatisfaction()); - } - if(ObjectUtil.isNotEmpty(req.getStatus())){ - eq(FdpTaskEntity::getStatus, req.getStatus()); - } - if(StringUtil.isNotBlank(req.getFdpDeviceName())){ - like(FdpTaskEntity::getFdpDeviceName,req.getFdpDeviceName()); - } - }}; + @Override + public boolean updateTaskStatus(Long id) { + FdpTaskEntity detail = super.getById(id); + try { + detail.setStatus(1); + boolean flag = super.saveOrUpdate(detail); + return flag; + } catch (NullPointerException e) { + throw new ServiceException("该id无法获取到智能诊断任务记录!"); + } + } - IPage pages = super.page(Condition.getPage(query), queryWrapper); - pages.setRecords(FdpTaskWrapper.build().listVO(pages.getRecords())); - return R.data(pages); - } + @Override + public R> list(FdpTaskDTO req, Query query) { + Wrapper queryWrapper = new LambdaQueryWrapper() {{ + orderByDesc(FdpTaskEntity::getId); + //name,emId,faultId,reasonId,satisfaction + if (StringUtil.isNotBlank(req.getName())) { + like(FdpTaskEntity::getName, req.getName()); + } + if (req.getEmCode() != null) { + eq(FdpTaskEntity::getEmCode, req.getEmCode()); + } + if (StringUtil.isNotBlank(req.getFaultId())) { + eq(FdpTaskEntity::getFaultId, req.getFaultId()); + } + if (StringUtil.isNotBlank(req.getReasonId())) { + eq(FdpTaskEntity::getReasonId, req.getReasonId()); + } + if (req.getSatisfaction() != null) { + eq(FdpTaskEntity::getSatisfaction, req.getSatisfaction()); + } + if (ObjectUtil.isNotEmpty(req.getStatus())) { + eq(FdpTaskEntity::getStatus, req.getStatus()); + } + if (StringUtil.isNotBlank(req.getFdpDeviceName())) { + like(FdpTaskEntity::getFdpDeviceName, req.getFdpDeviceName()); + } + }}; - @Override - public R getOperPhenomenon(OperPhenomenonEntity phenomenon) { - return operPhenomenonClient.detail(phenomenon); - } + IPage pages = super.page(Condition.getPage(query), queryWrapper); + pages.setRecords(FdpTaskWrapper.build().listVO(pages.getRecords())); + return R.data(pages); + } - @Override - public R getTaskStatistics(TaskStatisticsVo statisticsVo) { - Wrapper queryWrapper = getFdpTaskEntityWrapper(statisticsVo); - List fdpTaskEntities = super.baseMapper.selectList(queryWrapper); - if (CollectionUtil.isEmpty(fdpTaskEntities)){ - return R.success("暂无数据,请稍后重试"); - } - ArrayList res = new ArrayList<>(); - int size = fdpTaskEntities.size(); - //在第一层去掉为null值数据 - fdpTaskEntities=fdpTaskEntities.stream().filter(s->s.getFdpDeviceName()!=null).collect(Collectors.toList()); - extracted( res,0,"总计",size,size); - Map> collectByFdpDeviceName = fdpTaskEntities.stream().collect(Collectors.groupingBy(FdpTaskEntity::getFdpDeviceName)); - getCount("",collectByFdpDeviceName, fdpTaskEntities, res, 1); - if (Func.isEmpty(statisticsVo.getName())) { - collectByFdpDeviceName.entrySet().forEach(s->{ - List list=s.getValue().stream().filter(sig->sig.getName()!=null).collect(Collectors.toList()); - Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getName)); - getCount(s.getKey(),collectByName, s.getValue(), res, 2); - if (list.size()!=s.getValue().size()) { - //值为空单独加进来 - extracted( res,1,s.getKey()+"-空",s.getValue().size()-list.size(),s.getValue().size()); - } + @Override + public R getOperPhenomenon(OperPhenomenonEntity phenomenon) { + return operPhenomenonClient.detail(phenomenon); + } - }); - } else if (Func.isEmpty(statisticsVo.getCreateDept())){ - collectByFdpDeviceName.entrySet().forEach(s->{ - List list=s.getValue().stream().filter(sig->sig.getCreateDept()!=null).collect(Collectors.toList()); - Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getCreateDept)); - getCount2(s.getKey(),collectByName, s.getValue(), res, 2); - if (list.size()!=s.getValue().size()) { - //值为空单独加进来 - extracted( res,1,s.getKey()+"-空",s.getValue().size()-list.size(),s.getValue().size()); - } - }); - }else if (Func.isEmpty(statisticsVo.getFdpOrd())){ - collectByFdpDeviceName.entrySet().forEach(s->{ - List list=s.getValue().stream().filter(sig->sig.getFdpOrd()!=null).collect(Collectors.toList()); - Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getFdpOrd)); - getCount(s.getKey(),collectByName, s.getValue(), res, 2); - if (list.size()!=s.getValue().size()) { - //值为空单独加进来 - extracted( res,1,s.getKey()+"-空",s.getValue().size()-list.size(),s.getValue().size()); - } - }); - }else if (Func.isEmpty(statisticsVo.getType())){ - collectByFdpDeviceName.entrySet().forEach(s->{ - List list=s.getValue().stream().filter(sig->sig.getFdpOrd()!=null).collect(Collectors.toList()); - Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getType)); - getCount(s.getKey(),collectByName, s.getValue(), res, 2); - if (list.size()!=s.getValue().size()) { - //值为空单独加进来 - extracted( res,1,s.getKey()+"-空",s.getValue().size()-list.size(),s.getValue().size()); - } - }); - } - return R.data(res); - } + @Override + public R getTaskStatistics(TaskStatisticsVo statisticsVo) { + Wrapper queryWrapper = getFdpTaskEntityWrapper(statisticsVo); + List fdpTaskEntities = super.baseMapper.selectList(queryWrapper); + if (CollectionUtil.isEmpty(fdpTaskEntities)) { + return R.success("暂无数据,请稍后重试"); + } + ArrayList res = new ArrayList<>(); + int size = fdpTaskEntities.size(); + //在第一层去掉为null值数据 + fdpTaskEntities = fdpTaskEntities.stream().filter(s -> s.getFdpDeviceName() != null).collect(Collectors.toList()); + extracted(res, 0, "总计", size, size); + Map> collectByFdpDeviceName = fdpTaskEntities.stream().collect(Collectors.groupingBy(FdpTaskEntity::getFdpDeviceName)); + getCount("", collectByFdpDeviceName, fdpTaskEntities, res, 1); + if (Func.isEmpty(statisticsVo.getName())) { + collectByFdpDeviceName.entrySet().forEach(s -> { + List list = s.getValue().stream().filter(sig -> sig.getName() != null).collect(Collectors.toList()); + Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getName)); + getCount(s.getKey(), collectByName, s.getValue(), res, 2); + if (list.size() != s.getValue().size()) { + //值为空单独加进来 + extracted(res, 1, s.getKey() + "-空", s.getValue().size() - list.size(), s.getValue().size()); + } - private static void extracted( ArrayList res,Integer level,String name,Integer size,Integer all) { - TaskStatisticsVo taskStatisticsByDeviceName = new TaskStatisticsVo(); - taskStatisticsByDeviceName.setCount(size); - BigDecimal bigDecimal=BigDecimal.valueOf(all).divide(BigDecimal.valueOf(size),2,BigDecimal.ROUND_UP); - taskStatisticsByDeviceName.setPercentage(bigDecimal.toString()); - taskStatisticsByDeviceName.setLevel(level); - taskStatisticsByDeviceName.setMemuName(name); - res.add(taskStatisticsByDeviceName); - } + }); + } else if (Func.isEmpty(statisticsVo.getCreateDept())) { + collectByFdpDeviceName.entrySet().forEach(s -> { + List list = s.getValue().stream().filter(sig -> sig.getCreateDept() != null).collect(Collectors.toList()); + Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getCreateDept)); + getCount2(s.getKey(), collectByName, s.getValue(), res, 2); + if (list.size() != s.getValue().size()) { + //值为空单独加进来 + extracted(res, 1, s.getKey() + "-空", s.getValue().size() - list.size(), s.getValue().size()); + } + }); + } else if (Func.isEmpty(statisticsVo.getFdpOrd())) { + collectByFdpDeviceName.entrySet().forEach(s -> { + List list = s.getValue().stream().filter(sig -> sig.getFdpOrd() != null).collect(Collectors.toList()); + Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getFdpOrd)); + getCount(s.getKey(), collectByName, s.getValue(), res, 2); + if (list.size() != s.getValue().size()) { + //值为空单独加进来 + extracted(res, 1, s.getKey() + "-空", s.getValue().size() - list.size(), s.getValue().size()); + } + }); + } else if (Func.isEmpty(statisticsVo.getType())) { + collectByFdpDeviceName.entrySet().forEach(s -> { + List list = s.getValue().stream().filter(sig -> sig.getFdpOrd() != null).collect(Collectors.toList()); + Map> collectByName = list.stream().collect(Collectors.groupingBy(FdpTaskEntity::getType)); + getCount(s.getKey(), collectByName, s.getValue(), res, 2); + if (list.size() != s.getValue().size()) { + //值为空单独加进来 + extracted(res, 1, s.getKey() + "-空", s.getValue().size() - list.size(), s.getValue().size()); + } + }); + } + return R.data(res); + } - @Override - public R getTaskData(TaskStatisticsVo statisticsVo,Query query) { - Wrapper queryWrapper = getFdpTaskEntityWrapper(statisticsVo); - IPage pages = super.baseMapper.selectPage(Condition.getPage(query),queryWrapper); - if (CollectionUtil.isEmpty(pages.getRecords())){ - return R.success("暂无数据,请稍后重试"); - } - return R.data(pages); - } + private static void extracted(ArrayList res, Integer level, String name, Integer size, Integer all) { + TaskStatisticsVo taskStatisticsByDeviceName = new TaskStatisticsVo(); + taskStatisticsByDeviceName.setCount(size); + BigDecimal bigDecimal = BigDecimal.valueOf(all).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_UP); + taskStatisticsByDeviceName.setPercentage(bigDecimal.toString()); + taskStatisticsByDeviceName.setLevel(level); + taskStatisticsByDeviceName.setMemuName(name); + res.add(taskStatisticsByDeviceName); + } - private static Wrapper getFdpTaskEntityWrapper(TaskStatisticsVo statisticsVo) { - Wrapper queryWrapper = new LambdaQueryWrapper() {{ - if (Func.isNotEmpty(statisticsVo.getStartTime())) { - ge(FdpTaskEntity::getCreateTime, statisticsVo.getStartTime()); - } - if (Func.isNotEmpty(statisticsVo.getEndTime())) { - le(FdpTaskEntity::getCreateTime, statisticsVo.getEndTime()); - } - if (Func.isNotEmpty(statisticsVo.getCreateDept())) { - eq(FdpTaskEntity::getCreateDept, statisticsVo.getCreateDept()); - } - if (Func.isNotEmpty(statisticsVo.getName())) { - like(FdpTaskEntity::getName, statisticsVo.getName()); - } - if (Func.isNotEmpty(statisticsVo.getFdpDeviceName())) { - like(FdpTaskEntity::getFdpDeviceName, statisticsVo.getFdpDeviceName()); - } - if (Func.isNotEmpty(statisticsVo.getFdpOrd())) { - like(FdpTaskEntity::getFdpOrd, statisticsVo.getFdpOrd()); - } - if (Func.isNotEmpty(statisticsVo.getType())) { - eq(FdpTaskEntity::getType, statisticsVo.getType()); - } - if (Func.isNotEmpty(statisticsVo.getStatus())) { - eq(FdpTaskEntity::getStatus, statisticsVo.getStatus()); - } - eq(FdpTaskEntity::getIsDeleted,0); - orderByDesc(FdpTaskEntity::getCreateTime); - }}; - return queryWrapper; - } + @Override + public R getTaskData(TaskStatisticsVo statisticsVo, Query query) { + Wrapper queryWrapper = getFdpTaskEntityWrapper(statisticsVo); + IPage pages = super.baseMapper.selectPage(Condition.getPage(query), queryWrapper); + if (CollectionUtil.isEmpty(pages.getRecords())) { + return R.success("暂无数据,请稍后重试"); + } + return R.data(pages); + } - //获取对应层级占比和数量 - private static void getCount(String key,Map> collectByCreateDept, List fdpTaskEntities, ArrayList res,Integer level) { - collectByCreateDept.entrySet().forEach(s->{ - TaskStatisticsVo taskStatisticsVo = new TaskStatisticsVo(); - taskStatisticsVo.setCount(s.getValue().size()); - BigDecimal bigDecimal=BigDecimal.valueOf(s.getValue().size()).divide(BigDecimal.valueOf(fdpTaskEntities.size()),2,BigDecimal.ROUND_UP); - taskStatisticsVo.setPercentage(bigDecimal.toString()); - taskStatisticsVo.setLevel(level); - taskStatisticsVo.setMemuName(key+"-"+s.getKey().toString()); - res.add(taskStatisticsVo); - }); - } - //获取对应层级占比和数量 - //机构类型需要转换ID为名称 - private void getCount2(String key,Map> collectByCreateDept, List fdpTaskEntities, ArrayList res,Integer level) { - collectByCreateDept.entrySet().forEach(s->{ - TaskStatisticsVo taskStatisticsVo = new TaskStatisticsVo(); - taskStatisticsVo.setCount(s.getValue().size()); - BigDecimal bigDecimal=BigDecimal.valueOf(s.getValue().size()).divide(BigDecimal.valueOf(fdpTaskEntities.size())); - taskStatisticsVo.setPercentage(bigDecimal.toString()); - taskStatisticsVo.setLevel(level); - R deptNameCode = sysClient.getDeptName(s.getKey()); - String deptName; - if (deptNameCode.isSuccess()){ - deptName=deptNameCode.getData(); - }else { - deptName=""; - } - taskStatisticsVo.setMemuName(key+"-"+deptName); - res.add(taskStatisticsVo); - }); - } + @Override + public R submitResult(FdpTaskDTO req) { + FdpSubmitResultDTO fdpSubmitResultDTO = new FdpSubmitResultDTO(); + if (4 == req.getStatus()) { + fdpSubmitResultDTO.setSuccess(0); + } + //诊断成功 + if (3 == req.getStatus()) { + fdpSubmitResultDTO.setSuccess(1); + } else if (Func.isNotEmpty(req.getReasonId())) { + fdpSubmitResultDTO.setRootCause(req.getReasonId()); + } else { + return R.fail("诊断传送状态异常"); + } + if (Func.isNotEmpty(req.getReasonId())) { + fdpSubmitResultDTO.setRootCause(req.getReasonId()); + } + if (Func.isNotEmpty(req.getFaultId())) { + fdpSubmitResultDTO.setFaultId(req.getFaultId()); + } else { + return R.fail("数据异常"); + } + if (Func.isNotEmpty(req.getComment())) { + fdpSubmitResultDTO.setComment(req.getComment()); + } + if (Func.isNotEmpty(req.getStation())) { + fdpSubmitResultDTO.setStationId(req.getStation()); + } + HttpResponse r = HttpClientUtils.post(submitResult, JSONObject.toJSONString(fdpSubmitResultDTO)); + if (200 != r.getCode()) { + throw new ServiceException("智能诊断回传失败"); + } + boolean b = this.updateById(req); + if (b) { + return R.success("保存成功"); + } else { + return R.fail("保存失败,请稍后重试"); + } + } + + private static Wrapper getFdpTaskEntityWrapper(TaskStatisticsVo statisticsVo) { + Wrapper queryWrapper = new LambdaQueryWrapper() {{ + if (Func.isNotEmpty(statisticsVo.getStartTime())) { + ge(FdpTaskEntity::getCreateTime, statisticsVo.getStartTime()); + } + if (Func.isNotEmpty(statisticsVo.getEndTime())) { + le(FdpTaskEntity::getCreateTime, statisticsVo.getEndTime()); + } + if (Func.isNotEmpty(statisticsVo.getCreateDept())) { + eq(FdpTaskEntity::getCreateDept, statisticsVo.getCreateDept()); + } + if (Func.isNotEmpty(statisticsVo.getName())) { + like(FdpTaskEntity::getName, statisticsVo.getName()); + } + if (Func.isNotEmpty(statisticsVo.getFdpDeviceName())) { + like(FdpTaskEntity::getFdpDeviceName, statisticsVo.getFdpDeviceName()); + } + if (Func.isNotEmpty(statisticsVo.getFdpOrd())) { + like(FdpTaskEntity::getFdpOrd, statisticsVo.getFdpOrd()); + } + if (Func.isNotEmpty(statisticsVo.getType())) { + eq(FdpTaskEntity::getType, statisticsVo.getType()); + } + if (Func.isNotEmpty(statisticsVo.getStatus())) { + eq(FdpTaskEntity::getStatus, statisticsVo.getStatus()); + } + eq(FdpTaskEntity::getIsDeleted, 0); + orderByDesc(FdpTaskEntity::getCreateTime); + }}; + return queryWrapper; + } + + //获取对应层级占比和数量 + private static void getCount(String key, Map> collectByCreateDept, List fdpTaskEntities, ArrayList res, Integer level) { + collectByCreateDept.entrySet().forEach(s -> { + TaskStatisticsVo taskStatisticsVo = new TaskStatisticsVo(); + taskStatisticsVo.setCount(s.getValue().size()); + BigDecimal bigDecimal = BigDecimal.valueOf(s.getValue().size()).divide(BigDecimal.valueOf(fdpTaskEntities.size()), 2, BigDecimal.ROUND_UP); + taskStatisticsVo.setPercentage(bigDecimal.toString()); + taskStatisticsVo.setLevel(level); + taskStatisticsVo.setMemuName(key + "-" + s.getKey().toString()); + res.add(taskStatisticsVo); + }); + } + + //获取对应层级占比和数量 + //机构类型需要转换ID为名称 + private void getCount2(String key, Map> collectByCreateDept, List fdpTaskEntities, ArrayList res, Integer level) { + collectByCreateDept.entrySet().forEach(s -> { + TaskStatisticsVo taskStatisticsVo = new TaskStatisticsVo(); + taskStatisticsVo.setCount(s.getValue().size()); + BigDecimal bigDecimal = BigDecimal.valueOf(s.getValue().size()).divide(BigDecimal.valueOf(fdpTaskEntities.size())); + taskStatisticsVo.setPercentage(bigDecimal.toString()); + taskStatisticsVo.setLevel(level); + R deptNameCode = sysClient.getDeptName(s.getKey()); + String deptName; + if (deptNameCode.isSuccess()) { + deptName = deptNameCode.getData(); + } else { + deptName = ""; + } + taskStatisticsVo.setMemuName(key + "-" + deptName); + res.add(taskStatisticsVo); + }); + } } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/config/ThreadConfig.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/config/ThreadConfig.java new file mode 100644 index 0000000..a9877fe --- /dev/null +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/config/ThreadConfig.java @@ -0,0 +1,36 @@ +package com.hnac.hzims.operational.config; + +import com.hnac.hzims.operational.propperties.ThreadPoolConfigProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @Author WL + * @Version v1.0 + * @Serial 1.0 + * @Date 2023/5/10 12:49 + */ +@Configuration +public class ThreadConfig { + + @Autowired + private ThreadPoolConfigProperties threadPoolConfigProperties; + + @Bean + public ThreadPoolExecutor threadPoolExecutor() { + return new ThreadPoolExecutor(threadPoolConfigProperties.getCorePoolSize(), + threadPoolConfigProperties.getMaxSize(), + threadPoolConfigProperties.getKeepAliveTime(), + TimeUnit.SECONDS, + new LinkedBlockingDeque<>(threadPoolConfigProperties.getCapacity()), + Executors.defaultThreadFactory(), + new ThreadPoolExecutor.AbortPolicy()); + } + +} diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyMainServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyMainServiceImpl.java index 3e66a8a..3901698 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyMainServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/duty/service/impl/ImsDutyMainServiceImpl.java @@ -1765,12 +1765,16 @@ public class ImsDutyMainServiceImpl extends BaseServiceImpl> subordinate(@ApiParam(value = "站点机构ID") Long deptId) { + return R.data(service.subordinate(deptId)); + } + @ApiLog @ApiOperation("风电站点指标数据") @GetMapping("/station") - @ApiOperationSupport(order = 2) + @ApiOperationSupport(order = 3) public R station(@ApiParam(value = "站点机构ID") Long deptId) { return R.data(service.station(deptId)); } @@ -46,7 +54,7 @@ public class WindHomeController extends BladeController { @ApiLog @ApiOperation("风电站点发电量") @GetMapping("/generation") - @ApiOperationSupport(order = 3) + @ApiOperationSupport(order = 4) public R> generation(@ApiParam(value = "站点机构ID") Long deptId) { return R.data(service.generation(deptId)); } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/WindHomeService.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/WindHomeService.java index 1c53ea3..cc73703 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/WindHomeService.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/WindHomeService.java @@ -1,9 +1,6 @@ package com.hnac.hzims.operational.main.service; -import com.hnac.hzims.operational.main.vo.WindGenerationVo; -import com.hnac.hzims.operational.main.vo.WindScoreVo; -import com.hnac.hzims.operational.main.vo.WindStationVo; -import com.hnac.hzims.operational.main.vo.WindTargetCurveVo; +import com.hnac.hzims.operational.main.vo.*; import java.util.List; @@ -20,4 +17,6 @@ public interface WindHomeService { List generation(Long deptId); List target_curve(Long deptId); + + List subordinate(Long deptId); } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/WindHomeServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/WindHomeServiceImpl.java index 90c0786..f98e394 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/WindHomeServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/service/impl/WindHomeServiceImpl.java @@ -7,9 +7,11 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.hnac.hzims.equipment.vo.EminfoAndEmParamVo; import com.hnac.hzims.hzimsweather.response.weather.Daily; import com.hnac.hzims.hzimsweather.response.weather.HeWeatherWeatherDailyResponse; +import com.hnac.hzims.hzimsweather.response.weather.HeWeatherWeatherNowResponse; import com.hnac.hzims.operational.fill.entity.WindEntity; import com.hnac.hzims.operational.fill.service.WindService; import com.hnac.hzims.operational.main.constant.HomePageConstant; +import com.hnac.hzims.operational.main.service.AreaService; import com.hnac.hzims.operational.main.service.IWeatherService; import com.hnac.hzims.operational.main.service.WindHomeService; import com.hnac.hzims.operational.main.vo.*; @@ -18,10 +20,14 @@ import com.hnac.hzims.operational.station.service.IStationService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; +import org.springblade.core.tool.api.R; import org.springblade.core.tool.utils.CollectionUtil; import org.springblade.core.tool.utils.DateUtil; import org.springblade.core.tool.utils.ObjectUtil; -import org.springblade.server.domain.Sys; +import org.springblade.core.tool.utils.StringUtil; +import org.springblade.system.entity.Dept; +import org.springblade.system.entity.Region; +import org.springblade.system.feign.ISysClient; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -43,12 +49,16 @@ public class WindHomeServiceImpl implements WindHomeService { private final WindService windService; + private final AreaService areaService; + private final IWeatherService weatherService; private final IStationService stationService; private final RedisTemplate redisTemplate; + private final ISysClient sysClient; + public final static String device_cache_final = "hzims:equipment:emInfo:deviceCode.emInfoList"; /** @@ -63,32 +73,198 @@ public class WindHomeServiceImpl implements WindHomeService { eq(StationEntity::getServeType, HomePageConstant.HYDROPOWER_SERVETYPE); eq(StationEntity::getType,HomePageConstant.WIND_POWER); }}); - if(CollectionUtil.isNotEmpty(stations)){ + if(CollectionUtil.isEmpty(stations)){ return new WindScoreVo(); } - // 查询站点年填报数据 - List years = windService.list(new LambdaQueryWrapper() {{ - like(WindEntity::getFillDate, DateUtil.format(new Date(),"yyyy")); - in(WindEntity::getStationCode,stations.stream().map(StationEntity::getCode).collect(Collectors.toList())); - }}); - // 查询站点月填报数据 - List mons = windService.list(new LambdaQueryWrapper() {{ - like(WindEntity::getFillDate, DateUtil.format(new Date(),"yyyy-MM")); - in(WindEntity::getStationCode,stations.stream().map(StationEntity::getCode).collect(Collectors.toList())); - }}); - // 查询站点日填报数据 - List days = windService.list(new LambdaQueryWrapper() {{ - like(WindEntity::getFillDate, DateUtil.format(new Date(), DateUtil.format(new Date(),DateUtil.PATTERN_DATE))); + // 查询站点填报数据 + List winds = windService.list(new LambdaQueryWrapper() {{ in(WindEntity::getStationCode,stations.stream().map(StationEntity::getCode).collect(Collectors.toList())); }}); WindScoreVo score = new WindScoreVo(); + // 站点数量 score.setStationCount(stations.size()); - this.year(years,score); - this.mon(mons,score); - this.days(days,score); + if(CollectionUtil.isEmpty(winds)){ + return score; + } + // 装机容量 + List devices = JSONObject.parseObject(redisTemplate.opsForValue().get(device_cache_final).toString(), new TypeReference>() {}); + if(CollectionUtil.isNotEmpty(devices)){ + score.setInstalledCapacity(devices.stream().filter(o->stations.stream().map(StationEntity::getRefDept).collect(Collectors.toList()).contains(o.getCreateDept())).mapToDouble(EminfoAndEmParamVo::getInstalledCapacity).sum()); + } + // 年发电量 + score.setGenerateYear(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),"yyyy"))).mapToDouble(WindEntity::getPower).sum()); + // 年计划发电量 + score.setPlanYear(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),"yyyy"))).mapToDouble(WindEntity::getPlan).sum()); + // 年发电完成率 + if(Math.abs(score.getGenerateYear()) > 0 && Math.abs(score.getPlanYear()) > 0){ + score.setCompleteRate(BigDecimal.valueOf(score.getGenerateYear() / score.getPlanYear() * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); + } + // 月发电量 + score.setGenerateMon(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),"yyyy-MM"))).mapToDouble(WindEntity::getPower).sum()); + // 月平均风速 + score.setSpeedRate(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),"yyyy-MM"))).mapToDouble(WindEntity::getSpeed).average().getAsDouble()); + // 月短期准确率 + score.setAccuracy(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),"yyyy-MM"))).mapToDouble(WindEntity::getAccuracy).average().getAsDouble()); + // 月超短期准确率 + score.setUltraShortAccuracyRate(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),"yyyy-MM"))).mapToDouble(WindEntity::getUltraShortAccuracy).average().getAsDouble()); + // 日发电量 + score.setGenerateDay(winds.stream().filter(o->o.getFillDate().contains(DateUtil.format(new Date(),DateUtil.PATTERN_DATE))).mapToDouble(WindEntity::getPower).sum()); + // 近年发电量 + score.setPowerYearVoList(this.threeGenerateYear(winds)); + // 计划发电完成率 + score.setPowerMonthVoList(this.currentGenerateCurve(winds)); return score; } + /** + * 近3年发电量 + * @param winds + * @return + */ + private List threeGenerateYear(List winds) { + List mons = this.mons(2,12,false); + // 月份发电量赋值 + List list = mons.stream().map(mon->{ + PowerMonthVo power = new PowerMonthVo(); + LocalDate localDate = LocalDate.parse(DateUtil.format(new Date(), mon), DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE)); + power.setYear(localDate.getYear()); + power.setStrMonth(localDate.getMonthValue() > 9 ? String.valueOf(localDate.getMonthValue()) : "0" + localDate.getMonthValue()); + power.setPower((float) winds.stream().filter(o->o.getFillDate().contains(localDate.getYear() + "-" + power.getStrMonth())).mapToDouble(WindEntity::getPower).sum()); + return power; + }).collect(Collectors.toList()); + if(CollectionUtil.isEmpty(list)){ + return new ArrayList<>(); + } + // 转换年份分组 + return list.stream().collect(Collectors.groupingBy(PowerMonthVo::getYear)).entrySet().stream().map(entry->{ + PowerYearVo year = new PowerYearVo(); + year.setYear(entry.getKey()); + year.setPowerMonthVoList(entry.getValue()); + return year; + }).collect(Collectors.toList()); + } + + /** + * 年发电量趋势 + * @param winds + * @return + */ + private List currentGenerateCurve(List winds) { + List mons = this.mons(0,12,false); + return mons.stream().map(mon->{ + PowerMonthVo power = new PowerMonthVo(); + LocalDate localDate = LocalDate.parse(DateUtil.format(new Date(), mon), DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE)); + power.setYear(localDate.getYear()); + power.setStrMonth(localDate.getMonthValue() > 9 ? String.valueOf(localDate.getMonthValue()) : "0" + localDate.getMonthValue()); + power.setPlanPower((float) winds.stream().filter(o->o.getFillDate().contains(localDate.getYear() + "-" + power.getStrMonth())).mapToDouble(WindEntity::getPlan).sum()); + power.setPower((float) winds.stream().filter(o->o.getFillDate().contains(localDate.getYear() + "-" + power.getStrMonth())).mapToDouble(WindEntity::getPower).sum()); + return power; + }).collect(Collectors.toList()); + } + + /** + * 风电站集团/区域占比 + * @param deptId + * @return + */ + @Override + public List subordinate(Long deptId) { + Map> areas = areaService.areaOrStaion(deptId, Collections.singletonList(HomePageConstant.WIND_POWER)); + if (MapUtils.isEmpty(areas)) { + return new ArrayList<>(); + } + // 风电站填报数据查询 + List codes = new ArrayList<>(); + areas.forEach((key,value)-> codes.addAll(value.stream().map(StationEntity::getCode).collect(Collectors.toList()))); + List winds = windService.list(new LambdaQueryWrapper() {{ + in(WindEntity::getStationCode,codes) + .like(WindEntity::getFillDate,DateUtil.format(new Date(),"yyyy")); + }}); + // 获取站点编码集合 + List stations = areas.values().stream().map(values -> values.get(0).getCode()).collect(Collectors.toList()); + // 获取站点实时天气 + Map nowWeather = this.weatherService.getNowWeather(stations); + // 获取站点7日天气 + Map weekWeather = this.weatherService.getWeekWeather(stations); + return areas.entrySet().stream().map(entry -> { + WindSubordinateVo subordinate = new WindSubordinateVo(); + // 获取第一个站点经纬度、行政编码信息 + StationEntity station = entry.getValue().get(0); + subordinate.setLttd(station.getLttd()); + subordinate.setLgtd(station.getLgtd()); + // 省市编码 + String areaCode = station.getAreaCode(); + subordinate.setAreaCode(areaCode); + if (!StringUtil.isEmpty(areaCode)) { + String[] arrCode = areaCode.split(","); + R R = sysClient.getRegion(arrCode[1]); + if (R.isSuccess() && ObjectUtil.isNotEmpty(R.getData())) { + subordinate.setAreaName(R.getData().getName()); + } + } + // 机构Id + subordinate.setDepartId(entry.getKey().getId()); + // 机构名称 + subordinate.setDepartName(entry.getKey().getDeptName()); + // 天气 + this.getAreaWearther(subordinate, nowWeather, weekWeather, entry.getValue().get(0).getCode()); + if(CollectionUtil.isNotEmpty(winds)){ + List piece = winds.stream().filter(o->entry.getValue().stream().map(StationEntity::getCode).collect(Collectors.toList()).contains(o.getStationCode())).collect(Collectors.toList()); + if(CollectionUtil.isEmpty(piece)){ + return subordinate; + } + // 发电量 + subordinate.setGeneration(piece.stream().mapToDouble(WindEntity::getPower).sum()); + // 集团发电占比 + if(Math.abs(subordinate.getGeneration()) > 0 && Math.abs(winds.stream().mapToDouble(WindEntity::getPower).sum()) > 0){ + subordinate.setGenerationRate(BigDecimal.valueOf(subordinate.getGeneration() / winds.stream().mapToDouble(WindEntity::getPower).sum() * 100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()); + } + // 发电完成率 + double plan = piece.stream().mapToDouble(WindEntity::getPlan).sum(); + if(Math.abs(subordinate.getGeneration()) > 0 && Math.abs(plan) > 0){ + subordinate.setGenerationComplete(BigDecimal.valueOf(subordinate.getGeneration() / plan * 100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()); + } + // 风机利用率 : (总时间 - 故障时间) / 总时间 + double fault = piece.stream().mapToDouble(WindEntity::getFaultHours).sum(); + if(Math.abs(fault) > 0 ){ + subordinate.setFanUse(BigDecimal.valueOf(fault / (30 * 24) * 100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()); + } + // 厂用电率 : (发电量-上网电量+下网电量)/发电量 + double surf = piece.stream().mapToDouble(WindEntity::getSurfPower).sum(); + double below = piece.stream().mapToDouble(WindEntity::getBelowPower).sum(); + if(Math.abs(subordinate.getGeneration()) > 0 && Math.abs(surf + below) > 0){ + subordinate.setFactoryUse(BigDecimal.valueOf(subordinate.getGeneration() - surf + below / subordinate.getGeneration() * 100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()); + } + } + return subordinate; + }).filter(o-> Math.abs(o.getGeneration()) > 0 || Math.abs(o.getGenerationRate()) > 0 || Math.abs(o.getGenerationComplete()) > 0 + || Math.abs(o.getFactoryUse()) > 0 || Math.abs(o.getFanUse()) > 0 ).sorted(Comparator.comparing(WindSubordinateVo::getGeneration).reversed()).collect(Collectors.toList()); + } + + /** + * 区域天气 + * @param scale + * @param nowWeather + * @param weekWeather + * @param code + */ + private void getAreaWearther(WindSubordinateVo scale,Map nowWeather, Map weekWeather, String code) { + // 实时天气 + if(MapUtils.isNotEmpty(nowWeather) && nowWeather.containsKey(code)){ + HeWeatherWeatherNowResponse nowData = nowWeather.get(code); + if(ObjectUtil.isNotEmpty(nowData.getNow())){ + scale.setTemp(nowData.getNow().getTemp()); + } + } + // 站点七日内天气 + if(MapUtils.isNotEmpty(weekWeather) && weekWeather.containsKey(code)){ + HeWeatherWeatherDailyResponse weekData = weekWeather.get(code); + List dailyList = weekData.getDaily(); + if (CollectionUtil.isNotEmpty(dailyList)) { + scale.setWeather(dailyList); + } + } + } /** * 站点指标数据 @@ -109,7 +285,10 @@ public class WindHomeServiceImpl implements WindHomeService { // 机构名称 wind.setDepartName(station.getName()); // 站点行政区域编码 - wind.setAreaCode(station.getAreaCode()); + if(!StringUtil.isEmpty(station.getAreaCode())){ + String[] code = station.getAreaCode().split(","); + wind.setAreaCode(code[code.length - 1]); + } // 站点七天天气 Map weekWeather = weatherService.getWeekWeather(Collections.singletonList(station.getCode())); wind.setWeather(this.getDailyList(weekWeather,station.getCode())); @@ -243,51 +422,6 @@ public class WindHomeServiceImpl implements WindHomeService { } /** - * 风电数据 - 年 - * @param years - * @param score - */ - private void year(List years, WindScoreVo score) { - if(CollectionUtil.isNotEmpty(years)){ - return; - } - // 年发电量 - score.setGenerateYear(years.stream().mapToDouble(WindEntity::getPower).sum()); - // 年计划发电量 - score.setPlanYear(years.stream().mapToDouble(WindEntity::getPlan).sum()); - // 年发电完成率 - if(Math.abs(score.getGenerateYear()) > 0 && Math.abs(score.getPlanYear()) > 0){ - score.setSpeedRate(BigDecimal.valueOf(score.getGenerateYear() / score.getPlanYear() * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); - } - } - - /** - * 风电数据 - 月 - * @param mons - * @param score - */ - private void mon(List mons, WindScoreVo score) { - // 月发电量 - score.setGenerateMon(mons.stream().mapToDouble(WindEntity::getPower).sum()); - // 月平均风速 - score.setSpeedRate(mons.stream().mapToDouble(WindEntity::getSpeed).average().getAsDouble()); - // 月短期准确率 - score.setAccuracy(mons.stream().mapToDouble(WindEntity::getAccuracy).average().getAsDouble()); - // 月超短期准确率 - score.setUltraShortAccuracyRate(mons.stream().mapToDouble(WindEntity::getUltraShortAccuracy).average().getAsDouble()); - } - - /** - * 风电数据 - 日 - * @param days - * @param score - */ - private void days(List days, WindScoreVo score) { - // 日发电量 - score.setGenerateDay(days.stream().mapToDouble(WindEntity::getPower).sum()); - } - - /** * 获取近年月份集合 * @param year * @return diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/MaintenanceServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/MaintenanceServiceImpl.java index ffcd825..2031df8 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/MaintenanceServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/MaintenanceServiceImpl.java @@ -37,8 +37,12 @@ import org.springblade.system.feign.ISysClient; import org.springblade.system.user.cache.UserCache; import org.springblade.system.user.entity.User; import org.springframework.beans.BeanUtils; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.DefaultTransactionDefinition; import java.time.Instant; import java.time.LocalDate; @@ -46,6 +50,9 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadPoolExecutor; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -71,6 +78,11 @@ public class MaintenanceServiceImpl implements MaintenanceService { private final IFlowClient flowClient; private final ISysClient sysClient; + private final ThreadPoolExecutor executor; + + + private final DataSourceTransactionManager dataSourceTransactionManager; + /** * 日常维护生成任务 * @@ -79,33 +91,31 @@ public class MaintenanceServiceImpl implements MaintenanceService { @Override @Transactional(rollbackFor = Exception.class) public void createTask(List ids) { - //获取日常维护计划 - LambdaQueryWrapper planEntityLambdaQueryWrapper = new LambdaQueryWrapper<>(); - planEntityLambdaQueryWrapper.in(BaseEntity::getId, ids); - List planEntities = maintenancePlanService - .list(planEntityLambdaQueryWrapper); - //筛选当月没生成任务的计划 - List finalPlanEntities = planEntities.stream().filter(planEntity -> - ObjectUtil.isEmpty(planEntity.getCreateTaskTime()) - || !DateUtil.judgeSameDay( - DateUtil.DateToLocalDateTime(planEntity.getCreateTaskTime()), LocalDate.now()) - ).collect(Collectors.toList()); - if (CollectionUtil.isEmpty(finalPlanEntities)) { - throw new ServiceException("所选计划当天已生成任务"); - } - for (OperMaintenancePlanEntity finalPlanEntity : finalPlanEntities) { - // 通过计划生成任务 - this.createTaskByPlan(finalPlanEntity); - //更新任务派发时间 - LambdaUpdateWrapper planEntityLambdaUpdateWrapper = - new LambdaUpdateWrapper<>(); - planEntityLambdaUpdateWrapper.set(OperMaintenancePlanEntity::getCreateTaskTime, new Date()); - planEntityLambdaUpdateWrapper.eq(OperMaintenancePlanEntity::getId, finalPlanEntity.getId()); - boolean update = maintenancePlanService.update(planEntityLambdaUpdateWrapper); - if (!update) { - log.error("maintenance:generateTask 更新任务派发失败"); - throw new ServiceException("更新任务派发失败"); + try { + //获取日常维护计划 + LambdaQueryWrapper planEntityLambdaQueryWrapper = new LambdaQueryWrapper<>(); + planEntityLambdaQueryWrapper.in(BaseEntity::getId, ids); + List planEntities = maintenancePlanService.list(planEntityLambdaQueryWrapper); + //筛选当月没生成任务的计划 + List finalPlanEntities = planEntities.stream().filter(planEntity -> ObjectUtil.isEmpty(planEntity.getCreateTaskTime()) || !DateUtil.judgeSameDay(DateUtil.DateToLocalDateTime(planEntity.getCreateTaskTime()), LocalDate.now())).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(finalPlanEntities)) { + throw new ServiceException("所选计划当天已生成任务"); } + for (OperMaintenancePlanEntity finalPlanEntity : finalPlanEntities) { + // 通过计划生成任务 + this.createTaskByPlan(finalPlanEntity); + //更新任务派发时间 + LambdaUpdateWrapper planEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); + planEntityLambdaUpdateWrapper.set(OperMaintenancePlanEntity::getCreateTaskTime, new Date()); + planEntityLambdaUpdateWrapper.eq(OperMaintenancePlanEntity::getId, finalPlanEntity.getId()); + boolean update = maintenancePlanService.update(planEntityLambdaUpdateWrapper); + if (!update) { + log.error("maintenance:generateTask 更新任务派发失败"); + throw new ServiceException("更新任务派发失败"); + } + } + } catch (Exception e) { + e.printStackTrace(); } } @@ -117,107 +127,108 @@ public class MaintenanceServiceImpl implements MaintenanceService { @Override @Transactional(rollbackFor = RuntimeException.class) public void findPending(ProcessWorkFlowResponse response) { - log.info("获取businessKey: {}", response.getBusinessKey()); - log.info("获取taskId: {} ", response.getTaskId()); - log.info("获取下一个审批人是: {} ", response.getNextStepOperator()); - log.info("获取下一个用户Id是: {} ", response.getUserId()); - log.info("获取当前任务名称是: {} ", response.getTaskName()); - log.info("获取根据handleType区分是用户还是候选组角色: {}", response.getHandleType()); - //json转换表单 - String formData = JSON.toJSONString(response.getVariables()); - log.info("获取表单的数据:{}", formData); - OperMaintenanceTaskEntityVo standardTicketInfoVo = null; try { - JSONObject jsonObject = JSONObject.parseObject(formData); - standardTicketInfoVo = JSONObject.parseObject(jsonObject.getString("operMaintenanceTaskEntityVo"), - new TypeReference(){}); - // standardTicketInfoVo = (OperMaintenanceTaskEntityVo) jsonObject.get("operMaintenanceTaskEntityVo"); - // standardTicketInfoVo = JSONObject.toJavaObject(jsonObject, OperMaintenanceTaskEntityVo.class); - } catch (Exception e) { - log.error("获取表单出现异常了~~~~"); - throw new IllegalArgumentException(e.getMessage()); - } - //1.查询日常维护信息 - Long id = NumberUtils.toLong(response.getBusinessKey()); - OperMaintenanceTaskEntity dbOperMaintenanceTaskEntity = taskService.getById(id); - if (ObjectUtils.isEmpty(dbOperMaintenanceTaskEntity)) { - log.error("获取日常维护数据不存在"); - return; - } - OperMaintenanceTaskEntity entity = new OperMaintenanceTaskEntity(); - BeanUtils.copyProperties(standardTicketInfoVo, entity); - entity.setId(id); - //填充日常维护信息 - saveOperMaintenanceTaskEntity(entity, response); - entity.setProcessInstanceId(response.getProcessInstanceId()); - taskService.updateById(entity); - - //推送消息 - if (response.getTaskId() != null) { - // MessagePushRecordDto message = new MessagePushRecordDto(); - // message.setBusinessClassify("business"); - // message.setBusinessKey(MessageConstants.BusinessClassifyEnum.OPERATIONTICKETMESSAGE.getKey()); - // message.setSubject(MessageConstants.BusinessClassifyEnum.OPERATIONTICKETMESSAGE.getDescription()); - // message.setTaskId(entity.getId()); - // message.setTenantId("200000"); - // message.setTypes(Arrays.asList(MessageConstants.APP_PUSH, MessageConstants.WS_PUSH)); - // message.setPushType(MessageConstants.IMMEDIATELY); - // //您有一张工作票待审批,工作内容:*****,审批环节:*****; - // String countent = - // "您有一条日常维护任务待审批,工作内容:".concat(entity.getTitle()) - // .concat(",审批环节:") - // .concat(response.getTaskName()); - // message.setContent(countent); - // message.setDeptId(entity.getCreateDept()); - // R deptName = sysClient.getDeptName(entity.getCreateDept()); - // if (deptName.isSuccess()) { - // message.setDeptName(deptName.getData()); - // } - // String userIds = response.getUserId(); - // if (com.hnac.hzims.common.logs.utils.StringUtils.isBlank(userIds)) { - // log.error("推送的消息不能为空哦,{}", userIds); - // return; - // } - // String[] split = userIds.split(","); - // for (String userId : split) { - // message.setPusher(userId); - // User user = UserCache.getUser(NumberUtils.toLong(userId)); - // if (ObjectUtils.isNotEmpty(user)) { - // message.setPusherName(user.getName()); - // } - // message.setAccount(userId); - // message.setCreateUser(NumberUtils.toLong(userId)); - // messageClient.sendMessage(message); - // } - BusinessMessageDTO businessMessageDTO = new BusinessMessageDTO(); - businessMessageDTO.setBusinessClassify("business"); - businessMessageDTO.setBusinessKey(MessageConstants.BusinessClassifyEnum.ROUTINEMAINTENANCE.getKey()); - businessMessageDTO.setSubject(MessageConstants.BusinessClassifyEnum.ROUTINEMAINTENANCE.getDescription()); - businessMessageDTO.setTaskId(dbOperMaintenanceTaskEntity.getId()); - businessMessageDTO.setTenantId("200000"); - //您有一张工作票待审批,工作内容:*****,审批环节:*****; - String countent = - "您有一条日常维护任务待审批,工作内容:".concat(dbOperMaintenanceTaskEntity.getTitle()) - .concat(",审批环节:") - .concat(response.getTaskName()); - businessMessageDTO.setContent(countent); - businessMessageDTO.setDeptId(dbOperMaintenanceTaskEntity.getCreateDept()); - R deptName = sysClient.getDeptName(dbOperMaintenanceTaskEntity.getCreateDept()); - if (deptName.isSuccess()) { - businessMessageDTO.setDeptName(deptName.getData()); + log.info("获取businessKey: {}", response.getBusinessKey()); + log.info("获取taskId: {} ", response.getTaskId()); + log.info("获取下一个审批人是: {} ", response.getNextStepOperator()); + log.info("获取下一个用户Id是: {} ", response.getUserId()); + log.info("获取当前任务名称是: {} ", response.getTaskName()); + log.info("获取根据handleType区分是用户还是候选组角色: {}", response.getHandleType()); + //json转换表单 + String formData = JSON.toJSONString(response.getVariables()); + log.info("获取表单的数据:{}", formData); + OperMaintenanceTaskEntityVo standardTicketInfoVo = null; + try { + JSONObject jsonObject = JSONObject.parseObject(formData); + standardTicketInfoVo = JSONObject.parseObject(jsonObject.getString("operMaintenanceTaskEntityVo"), new TypeReference() { + }); + // standardTicketInfoVo = (OperMaintenanceTaskEntityVo) jsonObject.get("operMaintenanceTaskEntityVo"); + // standardTicketInfoVo = JSONObject.toJavaObject(jsonObject, OperMaintenanceTaskEntityVo.class); + } catch (Exception e) { + log.error("获取表单出现异常了~~~~"); + throw new IllegalArgumentException(e.getMessage()); } - String userIds = response.getUserId(); - businessMessageDTO.setUserIds(userIds); - businessMessageDTO.setCreateUser(dbOperMaintenanceTaskEntity.getCreateUser()); + //1.查询日常维护信息 + Long id = NumberUtils.toLong(response.getBusinessKey()); + OperMaintenanceTaskEntity dbOperMaintenanceTaskEntity = taskService.getById(id); + if (ObjectUtils.isEmpty(dbOperMaintenanceTaskEntity)) { + log.error("获取日常维护数据不存在"); + return; + } + OperMaintenanceTaskEntity entity = new OperMaintenanceTaskEntity(); + BeanUtils.copyProperties(standardTicketInfoVo, entity); + entity.setId(id); + //填充日常维护信息 + saveOperMaintenanceTaskEntity(entity, response); + entity.setProcessInstanceId(response.getProcessInstanceId()); + taskService.updateById(entity); + + //推送消息 + if (response.getTaskId() != null) { + // MessagePushRecordDto message = new MessagePushRecordDto(); + // message.setBusinessClassify("business"); + // message.setBusinessKey(MessageConstants.BusinessClassifyEnum.OPERATIONTICKETMESSAGE.getKey()); + // message.setSubject(MessageConstants.BusinessClassifyEnum.OPERATIONTICKETMESSAGE.getDescription()); + // message.setTaskId(entity.getId()); + // message.setTenantId("200000"); + // message.setTypes(Arrays.asList(MessageConstants.APP_PUSH, MessageConstants.WS_PUSH)); + // message.setPushType(MessageConstants.IMMEDIATELY); + // //您有一张工作票待审批,工作内容:*****,审批环节:*****; + // String countent = + // "您有一条日常维护任务待审批,工作内容:".concat(entity.getTitle()) + // .concat(",审批环节:") + // .concat(response.getTaskName()); + // message.setContent(countent); + // message.setDeptId(entity.getCreateDept()); + // R deptName = sysClient.getDeptName(entity.getCreateDept()); + // if (deptName.isSuccess()) { + // message.setDeptName(deptName.getData()); + // } + // String userIds = response.getUserId(); + // if (com.hnac.hzims.common.logs.utils.StringUtils.isBlank(userIds)) { + // log.error("推送的消息不能为空哦,{}", userIds); + // return; + // } + // String[] split = userIds.split(","); + // for (String userId : split) { + // message.setPusher(userId); + // User user = UserCache.getUser(NumberUtils.toLong(userId)); + // if (ObjectUtils.isNotEmpty(user)) { + // message.setPusherName(user.getName()); + // } + // message.setAccount(userId); + // message.setCreateUser(NumberUtils.toLong(userId)); + // messageClient.sendMessage(message); + // } + BusinessMessageDTO businessMessageDTO = new BusinessMessageDTO(); + businessMessageDTO.setBusinessClassify("business"); + businessMessageDTO.setBusinessKey(MessageConstants.BusinessClassifyEnum.ROUTINEMAINTENANCE.getKey()); + businessMessageDTO.setSubject(MessageConstants.BusinessClassifyEnum.ROUTINEMAINTENANCE.getDescription()); + businessMessageDTO.setTaskId(dbOperMaintenanceTaskEntity.getId()); + businessMessageDTO.setTenantId("200000"); + //您有一张工作票待审批,工作内容:*****,审批环节:*****; + String countent = "您有一条日常维护任务待审批,工作内容:".concat(dbOperMaintenanceTaskEntity.getTitle()).concat(",审批环节:").concat(response.getTaskName()); + businessMessageDTO.setContent(countent); + businessMessageDTO.setDeptId(dbOperMaintenanceTaskEntity.getCreateDept()); + R deptName = sysClient.getDeptName(dbOperMaintenanceTaskEntity.getCreateDept()); + if (deptName.isSuccess()) { + businessMessageDTO.setDeptName(deptName.getData()); + } + String userIds = response.getUserId(); + businessMessageDTO.setUserIds(userIds); + businessMessageDTO.setCreateUser(dbOperMaintenanceTaskEntity.getCreateUser()); - log.info("================================================"); - log.info("businessMessageDTO = " + businessMessageDTO); - log.info("================================================"); - R booleanR = messageClient.sendAppAndWsMsgByUsers(businessMessageDTO); - if (!booleanR.isSuccess()) { - throw new ServiceException("消息推送失败"); + log.info("================================================"); + log.info("businessMessageDTO = " + businessMessageDTO); + log.info("================================================"); + R booleanR = messageClient.sendAppAndWsMsgByUsers(businessMessageDTO); + if (!booleanR.isSuccess()) { + throw new ServiceException("消息推送失败"); + } + log.info("推送成功~"); } - log.info("推送成功~"); + } catch (Exception e) { + e.printStackTrace(); } } @@ -281,6 +292,9 @@ public class MaintenanceServiceImpl implements MaintenanceService { * @param finalPlanEntity */ private void fillTask(OperMaintenanceTaskEntity taskEntity, OperMaintenancePlanEntity finalPlanEntity) { + DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition(); + defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + TransactionStatus transaction = dataSourceTransactionManager.getTransaction(defaultTransactionDefinition); taskEntity.setId(null); taskEntity.setCreateTime(new Date()); taskEntity.setUpdateTime(new Date()); @@ -299,8 +313,7 @@ public class MaintenanceServiceImpl implements MaintenanceService { if (ObjectUtil.isNotEmpty(finalPlanEntity.getMaintenanceModel()) && finalPlanEntity.getMaintenanceModel() == 2) { //查询值班信息 LambdaQueryWrapper entityLambdaQueryWrapper = new LambdaQueryWrapper<>(); - entityLambdaQueryWrapper.eq(ImsDutyMainEntity::getDutyDate, - DateTimeFormatter.ofPattern(PATTERN_DATE).format(disposeTime)); + entityLambdaQueryWrapper.eq(ImsDutyMainEntity::getDutyDate, DateTimeFormatter.ofPattern(PATTERN_DATE).format(disposeTime)); entityLambdaQueryWrapper.eq(ImsDutyMainEntity::getClassId, finalPlanEntity.getImsDutyClassId()); ImsDutyMainEntity entity = mainService.getOne(entityLambdaQueryWrapper); if (ObjectUtil.isNotEmpty(entity) && StringUtils.isNotEmpty(entity.getDutyPersonIds())) { @@ -312,16 +325,26 @@ public class MaintenanceServiceImpl implements MaintenanceService { } } taskService.save(taskEntity); - //生成工作流实例 + dataSourceTransactionManager.commit(transaction); + //启动流程 String processInstanceId = this.startProcess(finalPlanEntity.getProcDefId(), taskEntity); - taskEntity.setProcessInstanceId(processInstanceId); - taskService.updateById(taskEntity); - finalPlanEntity.setCreateTaskTime(new Date()); - maintenancePlanService.updateById(finalPlanEntity); - - taskEntity = taskService.getById(taskEntity.getId()); //推送消息 - this.pushTaskMessage(taskEntity); + CompletableFuture operMaintenanceTaskEntityCompletableFuture = + CompletableFuture.runAsync(() -> { + taskEntity.setProcessInstanceId(processInstanceId); + taskService.updateById(taskEntity); + finalPlanEntity.setCreateTaskTime(new Date()); + maintenancePlanService.updateById(finalPlanEntity); + OperMaintenanceTaskEntity maintenanceTask = taskService.getById(taskEntity.getId()); + //推送消息 + this.pushTaskMessage(maintenanceTask); + }, executor); + //启动队列 + try { + CompletableFuture.allOf(operMaintenanceTaskEntityCompletableFuture).get(); + } catch (Exception e) { + e.printStackTrace(); + } } @@ -343,10 +366,7 @@ public class MaintenanceServiceImpl implements MaintenanceService { params.put("initUserIds", taskUsers); params.put("operMaintenanceTaskEntityVo", operMaintenanceTaskEntityVo); - return flowClient.startProcessInstanceContainNameByKey(processDefinitionKey, - String.valueOf(taskEntity.getId()), taskEntity.getTitle(), params) - .getData() - .getProcessInstanceId(); + return flowClient.startProcessInstanceContainNameByKey(processDefinitionKey, String.valueOf(taskEntity.getId()), taskEntity.getTitle(), params).getData().getProcessInstanceId(); } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/OperMaintenanceTaskServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/OperMaintenanceTaskServiceImpl.java index f744297..87178e9 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/OperMaintenanceTaskServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/maintenance/service/impl/OperMaintenanceTaskServiceImpl.java @@ -124,6 +124,10 @@ public class OperMaintenanceTaskServiceImpl extends BaseServiceImpl + */ + @XxlJob("getTicketCount") + public ReturnT getTicketCount(String param) { + Instant start = Instant.now(); + if (Func.isBlank(param)) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM"); + YearMonth yearMonth = YearMonth.now(); + YearMonth newYearMonth = yearMonth.minusMonths(1); + param = newYearMonth.format(dateTimeFormatter); + } + ticketCountService.allLoadMonthReport(param); + + Duration between = Duration.between(start, Instant.now()); + log.info("================================================================"); + log.info("耗时: " + (between.getSeconds()) + "秒"); + log.info("耗时: " + (between.toMillis()) + "毫秒"); + log.info("================================================================"); + log.info("两票生成月报统计成功"); + return new ReturnT<>("SUCCESS"); + } +} diff --git a/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/TicketCountService.java b/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/TicketCountService.java index 02f9562..8d10883 100644 --- a/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/TicketCountService.java +++ b/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/TicketCountService.java @@ -36,4 +36,11 @@ public interface TicketCountService extends BaseService { * @param response */ void exportTicketCount(String dateTime, HttpServletResponse response); + + + + /** + * 定时任务两票生成月报统计 + */ + void allLoadMonthReport(String dateTime); } diff --git a/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/impl/TicketCountServiceImpl.java b/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/impl/TicketCountServiceImpl.java index 06e48ed..950a486 100644 --- a/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/impl/TicketCountServiceImpl.java +++ b/hzims-service/ticket/src/main/java/com/hnac/hzims/ticket/twoTicket/service/impl/TicketCountServiceImpl.java @@ -20,6 +20,7 @@ import com.hnac.hzims.ticket.twoTicket.vo.ticket.TicketCountResponseVo; import com.hnac.hzims.ticket.twoTicket.vo.ticket.TicketCountVo; import com.hnac.hzims.ticket.workTicket.entity.WorkTicketInfoEntity; import com.hnac.hzims.ticket.workTicket.service.IWorkTicketInfoService; +import io.micrometer.core.instrument.binder.BaseUnits; import jodd.util.ObjectUtil; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @@ -35,7 +36,9 @@ import org.springblade.core.secure.BladeUser; import org.springblade.core.secure.utils.AuthUtil; import org.springblade.core.tool.api.R; import org.springblade.system.feign.ISysClient; +import org.springblade.system.user.entity.User; import org.springblade.system.user.feign.IUserClient; +import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; @@ -76,6 +79,7 @@ public class TicketCountServiceImpl extends BaseServiceImpl> allUserList = userClient.getAllUserList("200000"); + if (!allUserList.isSuccess()) { + log.error("获取不到数据"); + return; + } + List userList = allUserList.getData(); + + for (User user : userList) { + BladeUser bladeUser = new BladeUser(); + BeanUtils.copyProperties(user, bladeUser); + bladeUser.setUserId(user.getId()); + List createDept = userClient.getDataScope(bladeUser.getUserId()); + //根据月份查询统计的数据 + CompletableFuture> ticketCountsCompletableFuture = CompletableFuture.supplyAsync(() -> { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(TicketCount::getDateTime, dateTime); + List ticketCounts = baseMapper.selectList(queryWrapper); + return ticketCounts; + }, executor); + + //第一种工作票 + CompletableFuture oneTicketCompletableFuture = ticketCountsCompletableFuture.thenAcceptAsync((items) -> { + //查询第一种工作票 + List ticketCountList = getTicketCountList(createDept, items, "6", dateTime, bladeUser); + if (CollectionUtils.isNotEmpty(ticketCountList)) { + this.saveBatch(ticketCountList); + } + }, executor); + //第二种工作票 + CompletableFuture twoTicketCompletableFuture = ticketCountsCompletableFuture.thenAcceptAsync((items) -> { + //查询第一种工作票 + List ticketCountList = getTicketCountList(createDept, items, "7", dateTime, bladeUser); + if (CollectionUtils.isNotEmpty(ticketCountList)) { + this.saveBatch(ticketCountList); + } + }, executor); + //水力机械工作票 + CompletableFuture threeTicketCompletableFuture = ticketCountsCompletableFuture.thenAcceptAsync((items) -> { + //查询第一种工作票 + List ticketCountList = getTicketCountList(createDept, items, "8", dateTime, bladeUser); + if (CollectionUtils.isNotEmpty(ticketCountList)) { + this.saveBatch(ticketCountList); + } + }, executor); + //操作票 + CompletableFuture standardCompletableFuture = ticketCountsCompletableFuture.thenAcceptAsync((items) -> { + //操作票 + List ticketCountList = getStandardTicketCountList(createDept, items, "3", dateTime, bladeUser); + if (CollectionUtils.isNotEmpty(ticketCountList)) { + this.saveBatch(ticketCountList); + } + + }, executor); + //执行线程操作 + CompletableFuture.allOf(ticketCountsCompletableFuture, oneTicketCompletableFuture, twoTicketCompletableFuture + , threeTicketCompletableFuture, standardCompletableFuture).get(); + } + } + /** * 列表封装 diff --git a/hzims-service/ticket/src/main/resources/application.yml b/hzims-service/ticket/src/main/resources/application.yml index 1de0a34..2af9d8e 100644 --- a/hzims-service/ticket/src/main/resources/application.yml +++ b/hzims-service/ticket/src/main/resources/application.yml @@ -57,5 +57,15 @@ swagger: # segment: 工作票延期 - +xxl: + job: + accessToken: '' + admin: + addresses: http://192.168.1.20:7009/xxl-job-admin + executor: + appname: hzims-ticket + ip: 192.168.1.3 + logpath: /data/applogs/xxl-job/jobhandler + logretentiondays: -1 + port: 28601