Jay
2025-02-06 e9506a872eb087da15a3ad317836c26bd8f0356c
iailab-module-model/iailab-module-model-biz/src/main/java/com/iailab/module/model/api/McsApiImpl.java
@@ -1,5 +1,6 @@
package com.iailab.module.model.api;
import com.iailab.framework.common.pojo.PageResult;
import com.iailab.framework.common.util.date.DateUtils;
import com.iailab.framework.common.util.object.ConvertUtils;
import com.iailab.module.data.api.plan.PlanItemApi;
@@ -11,18 +12,28 @@
import com.iailab.module.data.common.ApiDataQueryDTO;
import com.iailab.module.model.api.mcs.McsApi;
import com.iailab.module.model.api.mcs.dto.*;
import com.iailab.module.model.common.enums.CommonConstant;
import com.iailab.module.model.api.mdk.dto.StScheduleRecordVO;
import com.iailab.module.model.common.enums.DataTypeEnum;
import com.iailab.module.model.common.enums.PreLineTypeEnum;
import com.iailab.module.model.enums.CommonConstant;
import com.iailab.module.model.influxdb.pojo.InfluxModelResultByOutPutIdsPOJO;
import com.iailab.module.model.influxdb.service.InfluxDBService;
import com.iailab.module.model.influxdb.vo.InfluxModelResultVO;
import com.iailab.module.model.mcs.pre.entity.DmModuleEntity;
import com.iailab.module.model.mcs.pre.entity.MmItemOutputEntity;
import com.iailab.module.model.mcs.pre.entity.MmPredictAlarmMessageEntity;
import com.iailab.module.model.mcs.pre.service.*;
import com.iailab.module.model.mcs.pre.vo.MmItemOutputRespVO;
import com.iailab.module.model.mcs.pre.vo.MmPredictAlarmMessageSaveReqVO;
import com.iailab.module.model.mcs.pre.vo.MmPredictItemRespVO;
import com.iailab.module.model.mcs.sche.entity.StScheduleModelEntity;
import com.iailab.module.model.mcs.sche.entity.StScheduleSuggestEntity;
import com.iailab.module.model.mcs.sche.service.StScheduleSchemeService;
import com.iailab.module.model.mcs.sche.service.StScheduleSuggestService;
import com.iailab.module.model.mcs.sche.service.*;
import com.iailab.module.model.mcs.sche.vo.StScheduleSuggestSaveReqVO;
import com.iailab.module.model.mdk.vo.ItemVO;
import com.iailab.module.model.mpk.service.ChartParamService;
import com.iailab.module.model.mpk.service.ChartService;
import com.iailab.module.model.mpk.service.ElectricityPriceSegmentedService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -45,6 +56,9 @@
public class McsApiImpl implements McsApi {
    @Autowired
    private DataPointApi dataPointApi;
    @Autowired
    private DmModuleService dmModuleService;
    @Autowired
@@ -58,9 +72,6 @@
    @Autowired
    private MmItemResultLastPointService mmItemResultLastPointService;
    @Autowired
    private DataPointApi dataPointApi;
    @Autowired
    private MmItemResultJsonService mmItemResultJsonService;
@@ -82,6 +93,25 @@
    @Autowired
    private StScheduleSchemeService stScheduleSchemeService;
    @Autowired
    private StScheduleRecordService stScheduleRecordService;
    @Autowired
    private ChartParamService chartParamService;
    @Autowired
    private InfluxDBService influxDBService;
    @Autowired
    private ElectricityPriceSegmentedService electricityPriceSegmentedService;
    @Autowired
    private StScheduleModelService stScheduleModelService;
    @Autowired
    private StScheduleModelSettingService stScheduleModelSettingService;
    private int HOUR_MINS = 60;
@@ -133,8 +163,14 @@
        }
        Date predictTime = reqVO.getPredictTime();
        if (predictTime == null) {
            MmItemOutputEntity output = mmItemOutputService.getOutPutById(reqVO.getOutIds().get(0));
            ItemVO predictItem = mmPredictItemService.getItemById(output.getItemid());
            MmItemOutputEntity output = null;
            for (String outId : outIds) {
                output = mmItemOutputService.getOutPutById(outId);
                if (output != null) {
                    break;
                }
            }
            ItemVO predictItem = mmPredictItemService.getItemByIdFromCache(output.getItemid());
            if (predictItem.getLastTime() != null) {
                predictTime = predictItem.getLastTime();
            } else {
@@ -247,20 +283,20 @@
        if (startTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(predictItem.getLastTime());
            calendar.add(Calendar.MINUTE, -1 * predictItem.getPredictLength());
            calendar.add(Calendar.SECOND, -1 * predictItem.getPredictLength() * predictItem.getGranularity());
            startTime = calendar.getTime();
        }
        Date endTime = reqVO.getEndTime();
        if (endTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(predictItem.getLastTime());
            calendar.add(Calendar.MINUTE, predictItem.getPredictLength());
            calendar.add(Calendar.SECOND, predictItem.getPredictLength() * predictItem.getGranularity());
            endTime = calendar.getTime();
        }
        if (endTime.getTime() <= startTime.getTime()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            calendar.add(Calendar.MINUTE, predictItem.getPredictLength());
            calendar.add(Calendar.SECOND, predictItem.getPredictLength() * predictItem.getGranularity());
            endTime = calendar.getTime();
        }
@@ -274,7 +310,9 @@
        for (MmItemOutputEntity out : outs) {
            legend.add(out.getResultName());
            PreDataSampleViewRespDTO viewDto = new PreDataSampleViewRespDTO();
            viewDto.setRealData(getHisData(out.getPointid(), startTime, endTime));
            if (StringUtils.isNotBlank(out.getPointid())) {
                viewDto.setRealData(getHisData(out.getPointid(), startTime, endTime));
            }
            viewDto.setPreDataN(mmItemResultService.getData(out.getId(), startTime, endTime, DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
            viewMap.put(out.getResultName(), viewDto);
        }
@@ -302,16 +340,18 @@
        if (resultStr == null) {
            return result;
        }
        String resultIndex = chartParams.get(CommonConstant.RESULT_INDEX);
        ItemVO predictItem = mmPredictItemService.getItemByItemNo(itemCode);
        if (predictItem == null || predictItem.getLastTime() == null) {
            return result;
        }
        String timeFormat = StringUtils.isBlank(reqVO.getTimeFormat()) ? DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND : reqVO.getTimeFormat();
        PreLineTypeEnum lineType = chartParams.get(CommonConstant.LINE_TYPE) == null ? PreLineTypeEnum.TN : PreLineTypeEnum.getEumByCode(chartParams.get(CommonConstant.LINE_TYPE));
        BigDecimal rangeH = chartParams.get(CommonConstant.RANGE_H) == null ? BigDecimal.ZERO : new BigDecimal(chartParams.get(CommonConstant.RANGE_H));
        BigDecimal rangeL = chartParams.get(CommonConstant.RANGE_L) == null ? BigDecimal.ZERO : new BigDecimal(chartParams.get(CommonConstant.RANGE_L));
        BigDecimal limitH = chartParams.get(CommonConstant.LIMIT_H) == null ? BigDecimal.ZERO : new BigDecimal(chartParams.get(CommonConstant.LIMIT_H));
        BigDecimal limitL = chartParams.get(CommonConstant.LIMIT_L) == null ? BigDecimal.ZERO : new BigDecimal(chartParams.get(CommonConstant.LIMIT_L));
        BigDecimal rangeH = chartParams.get(CommonConstant.RANGE_H) == null ? null : new BigDecimal(chartParams.get(CommonConstant.RANGE_H));
        BigDecimal rangeL = chartParams.get(CommonConstant.RANGE_L) == null ? null : new BigDecimal(chartParams.get(CommonConstant.RANGE_L));
        BigDecimal limitH = chartParams.get(CommonConstant.LIMIT_H) == null ? null : new BigDecimal(chartParams.get(CommonConstant.LIMIT_H));
        BigDecimal limitL = chartParams.get(CommonConstant.LIMIT_L) == null ? null : new BigDecimal(chartParams.get(CommonConstant.LIMIT_L));
        int lengthLeft = chartParams.get(CommonConstant.LENGTH_LEFT) == null ? predictItem.getPredictLength() : new BigDecimal(chartParams.get(CommonConstant.LENGTH_LEFT)).intValue();
        int lengthRight = chartParams.get(CommonConstant.LENGTH_RIGHT) == null ? predictItem.getPredictLength() : new BigDecimal(chartParams.get(CommonConstant.LENGTH_RIGHT)).intValue();
@@ -322,7 +362,7 @@
        List<String> categories = DateUtils.getTimeScale(startTime, endTime, predictItem.getGranularity(), timeFormat);
        List<String> legend = new ArrayList<>();
        MmItemOutputEntity outPut = mmItemOutputService.getByItemid(predictItem.getId(), resultStr);
        MmItemOutputEntity outPut = mmItemOutputService.getByItemid(predictItem.getId(), resultStr, resultIndex);
        PreDataViewRespDTO dataView = new PreDataViewRespDTO();
        dataView.setItemId(predictItem.getId());
        dataView.setItemName(predictItem.getItemName());
@@ -331,8 +371,13 @@
        dataView.setRangeL(rangeL);
        dataView.setLimitH(limitH);
        dataView.setLimitL(limitL);
        dataView.setRealData(getHisData(outPut.getPointid(), startTime, endTime, timeFormat));
        if (StringUtils.isNotBlank(outPut.getPointid())) {
            dataView.setRealData(getHisData(outPut.getPointid(), startTime, endTime, timeFormat));
        } else {
            dataView.setRealData(new ArrayList<>());
        }
        dataView.setCurData(mmItemResultJsonService.getData(outPut.getId(), predictTime, timeFormat));
        dataView.setLineType(lineType.getCode());
        switch (lineType) {
            case TN:
                dataView.setPreDataN(mmItemResultService.getData(outPut.getId(), startTime, endTime, timeFormat));
@@ -344,6 +389,10 @@
            default:
                break;
        }
        if (!CollectionUtils.isEmpty(dataView.getRealData())) {
            Object[] rdo = dataView.getRealData().get(dataView.getRealData().size() - 1);
            dataView.setCurrValue(new BigDecimal(rdo[1].toString()));
        }
        if (!CollectionUtils.isEmpty(dataView.getCurData())) {
            List<Double> curList = dataView.getCurData().stream().map(t -> {
@@ -351,6 +400,42 @@
            }).collect(Collectors.toList());
            dataView.setPreMax(new BigDecimal(curList.stream().mapToDouble(Double::doubleValue).max().getAsDouble()).setScale(2, BigDecimal.ROUND_HALF_UP));
            dataView.setPreMin(new BigDecimal(curList.stream().mapToDouble(Double::doubleValue).min().getAsDouble()).setScale(2, BigDecimal.ROUND_HALF_UP));
            dataView.setPreLast(new BigDecimal(curList.get(curList.size() - 1)));
            dataView.setPreCumulant(new BigDecimal(curList.stream().mapToDouble(Double::doubleValue).sum()));
        }
        String alarmObj = chartParams.get(CommonConstant.ALARM_OBJ);
        if (StringUtils.isNotBlank(alarmObj)) {
            List<AlarmMessageRespDTO> alarmList = ConvertUtils.sourceToTarget(mmPredictAlarmMessageService.getList(alarmObj, predictTime), AlarmMessageRespDTO.class);
            dataView.setAlarmList(alarmList);
            if (CollectionUtils.isEmpty(alarmList)) {
                dataView.setAlarmMessage("暂无预警信息");
            } else {
                dataView.setAlarmMessage(alarmList.get(0).getContent());
            }
        }
        try {
            String adjValuePoint = chartParams.get(CommonConstant.ADJ_VALUE_POINT);
            if (StringUtils.isNotBlank(adjValuePoint)) {
                List<String> pointNos = new ArrayList<>();
                pointNos.add(adjValuePoint);
                Map<String, Object> adjValue = dataPointApi.queryPointsRealValue(pointNos);
                dataView.setAdjValue(new BigDecimal(adjValue.get(adjValuePoint).toString()));
            }
            String adjValueArrPoint = chartParams.get(CommonConstant.ADJ_VALUE_ARR_POINT);
            if (StringUtils.isNotBlank(adjValueArrPoint)) {
                String[] adjPointArr = adjValueArrPoint.split(",");
                Map<String, Object> adjValue = dataPointApi.queryPointsRealValue(Arrays.asList(adjPointArr));
                BigDecimal[] adjValueArr = new BigDecimal[adjPointArr.length];
                for(int i = 0; i < adjPointArr.length; i++) {
                    adjValueArr[i] = new BigDecimal(adjValue.get(adjPointArr[i]).toString());
                }
                dataView.setAdjValueArr(adjValueArr);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        result.setPredictTime(predictTime);
@@ -515,12 +600,13 @@
    @Override
    public Boolean createScheduleSuggest(ScheduleSuggestRespDTO dto) {
        stScheduleSuggestService.create(ConvertUtils.sourceToTarget(dto, StScheduleSuggestSaveReqVO.class));
        return true;
    }
    @Override
    public List<ScheduleSuggestRespDTO> listScheduleSuggest(Map<String, Object> params) {
        return Collections.emptyList();
    public List<ScheduleSuggestRespDTO> listScheduleSuggest(ScheduleSuggestReqDTO vo) {
        return stScheduleSuggestService.list(vo);
    }
    @Override
@@ -540,32 +626,198 @@
    }
    @Override
    public List<StScheduleSchemeDTO> listScheduleScheme(Map<String, Object> params) {
    public List<StScheduleSchemeDTO> listScheduleScheme(String triggerMethod, String triggerCondition) {
        Map<String, Object> params = new HashMap<>();
        params.put("triggerMethod", triggerMethod);
        params.put("triggerCondition", triggerCondition);
        return stScheduleSchemeService.list(params);
    }
    @Override
    public List<ChartParamDTO> getChartParamList(String chartCode) {
        if (StringUtils.isBlank(chartCode)) {
            return null;
        }
        return chartParamService.list(chartCode);
    }
    @Override
    public PageResult<StAlarmAndSuggestRespVO> getAlarmAndSuggestPage(StAlarmAndSuggestPageReqVO reqVO) {
        return stScheduleSchemeService.getAlarmAndSuggestPage(reqVO);
    }
    @Override
    public Map<String, Map<String, Double>> getPreDoubleData(PreDoubleDataReqVO reqVO) {
        List<MmPredictItemRespVO> doubleItemOutPuts = mmPredictItemService.getDoubleOutPutsByItemNos(reqVO.getItemNos());
        //<itemNo,<resultStr,double>>
        Map<String, Map<String, Double>> result = new HashMap<>(reqVO.getItemNos().size());
        for (MmPredictItemRespVO mmPredictItemRespVO : doubleItemOutPuts) {
            List<String> outPutIds = mmPredictItemRespVO.getOutPuts().stream().map(MmItemOutputRespVO::getId).collect(Collectors.toList());
            InfluxModelResultByOutPutIdsPOJO pojo = new InfluxModelResultByOutPutIdsPOJO();
            pojo.setOutPutIds(outPutIds);
            pojo.setType(DataTypeEnum.FLOAT.getCode());
            Map<String, List<InfluxModelResultVO>> outPutIdDoubles = influxDBService.queryModelResultsByOutPutIds(pojo, mmPredictItemRespVO.getLastTime(), mmPredictItemRespVO.getLastTime());
            Map<String, Double> outPutIdDouble = new HashMap<>(outPutIds.size());
            for (MmItemOutputRespVO outPut : mmPredictItemRespVO.getOutPuts()) {
                String outPutId = outPut.getId();
                if (outPutIdDoubles.containsKey(outPutId)) {
                    List<InfluxModelResultVO> influxModelResultVOS = outPutIdDoubles.get(outPutId);
                    if (!CollectionUtils.isEmpty(influxModelResultVOS)) {
                        outPutIdDouble.put(outPut.getResultstr(),Double.valueOf(influxModelResultVOS.get(0).getValue().toString()));
                    }
                }
            }
            result.put(mmPredictItemRespVO.getItemno(),outPutIdDouble);
        }
        return result;
    }
    public Map<String, BigDecimal> getPredictLastValue(PredictLastValueReqVO reqVO) {
        Map<String, BigDecimal> result = new HashMap<>(reqVO.getItemNos().size());
        if (CollectionUtils.isEmpty(reqVO.getItemNos())) {
            return result;
        }
        List<String[]> itemNos = reqVO.getItemNos();
        for (String[] itemNo : itemNos) {
            String key = itemNo[0] + "_" + itemNo[1] + "_" + itemNo[2];
            ItemVO predictItem = mmPredictItemService.getItemByItemNo(itemNo[0]);
            if (predictItem == null || predictItem.getLastTime() == null) {
                result.put(key, BigDecimal.ZERO);
            }
            MmItemOutputEntity outPut = mmItemOutputService.getByItemid(predictItem.getId(), itemNo[1], itemNo[2]);
            Date predictTime = predictItem.getLastTime();
            List<Object[]> curData = mmItemResultJsonService.getData(outPut.getId(), predictTime, DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
            if(CollectionUtils.isEmpty(curData)) {
                result.put(key, BigDecimal.ZERO);
            } else {
                result.put(key, new BigDecimal(curData.get(curData.size() - 1)[1].toString()));
            }
        }
        return result;
    }
    @Override
    public List<StScheduleRecordVO> getLastScheduleData(String scheduleCode, Integer limit) {
        if (StringUtils.isBlank(scheduleCode)) {
            return null;
        }
        return stScheduleRecordService.getLastScheduleResult(scheduleCode,limit);
    }
    @Override
    public Map<String, List<Object[]>> getPredictDataItemNo(PreDataItemNoReqVO reqVO) {
        if (StringUtils.isBlank(reqVO.getItemNo())) {
            return new HashMap<>();
        }
        ItemVO predictItem = mmPredictItemService.getItemByItemNo(reqVO.getItemNo());
        if (null == predictItem) {
            return new HashMap<>();
        }
        // 默认开始时间:运行时间
        if (null == reqVO.getStartTime()) {
            reqVO.setStartTime(predictItem.getLastTime());
        }
        // 默认结束时间:运行时间+预测长度*粒度
        if (null == reqVO.getEndTime()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(predictItem.getLastTime());
            calendar.add(Calendar.SECOND,predictItem.getPredictLength() * predictItem.getGranularity());
            reqVO.setEndTime(calendar.getTime());
        }
        List<String> itemNos = new ArrayList<String>(){{
           add(reqVO.getItemNo());
        }};
        List<MmPredictItemRespVO> ItemRespVOs = mmPredictItemService.getArrayOutPutsByItemNos(itemNos);
        if (CollectionUtils.isEmpty(ItemRespVOs)) {
            return new HashMap<>();
        }
        List<MmItemOutputRespVO> outPuts = ItemRespVOs.get(0).getOutPuts();
        if (CollectionUtils.isEmpty(outPuts)) {
            return new HashMap<>();
        }
        InfluxModelResultByOutPutIdsPOJO pojo = new InfluxModelResultByOutPutIdsPOJO();
        pojo.setOutPutIds(outPuts.stream().map(MmItemOutputRespVO::getId).collect(Collectors.toList()));
        pojo.setType(DataTypeEnum.FLOAT.getCode());
        Map<String, List<InfluxModelResultVO>> outPutDatas = influxDBService.queryModelResultsByOutPutIds(pojo, reqVO.getStartTime(), reqVO.getEndTime());
        Map<String,List<Object[]>> result = new HashMap<>(outPuts.size());
        for (MmItemOutputRespVO outPut : outPuts) {
            String outPutId = outPut.getId();
            if (outPutDatas.containsKey(outPutId)) {
                List<InfluxModelResultVO> influxModelResultVOS = outPutDatas.get(outPutId);
                result.put(null == outPut.getResultIndex() ? outPut.getResultstr() : outPut.getResultstr()+"_"+outPut.getResultIndex(),influxModelResultVOS.stream().map(e -> {
                    Object[] values = new Object[2];
                    values[0] = DateUtils.format(Date.from(e.getTimestamp()), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
                    values[1] = Double.valueOf(e.getValue().toString());
                    return values;
                }).collect(Collectors.toList()));
            }
        }
        return result;
    }
    @Override
    public List<ElectricityPriceSegmentedDTO> getElectricityPriceList(String year, String time) {
        return electricityPriceSegmentedService.getElectricityPriceList(year, time);
    }
    @Override
    public Boolean createElectricityPrice(List<ElectricityPriceSegmentedDTO> list) {
        electricityPriceSegmentedService.deleteByITimeId(list.get(0).getITimeId());
        list.forEach(dto -> electricityPriceSegmentedService.create(dto));
        return true;
    }
    @Override
    public Boolean updateScheduleModelSetting(String modelCode, String key, String value) {
        StScheduleModelEntity model = stScheduleModelService.getByModelCode(modelCode);
        stScheduleModelSettingService.updateByModelIdAndKey(model.getId(), key, value);
        return true;
    }
    /**
     * 计算功率因数 p²/(根号:p²+Q²)
     **/
    public Double calculateCos(Double PValue,Double QValue) {
        // 绝对值
        PValue = Math.abs(PValue);
        QValue = Math.abs(QValue);
        //PValue [0,0.001] 直接判断为关闭返回0
        if (PValue >= 0 && PValue <= 0.001) {
            return 0.0;
        }else {
            BigDecimal result = new BigDecimal(PValue).divide(BigDecimal.valueOf(Math.sqrt(Math.pow(PValue, 2) + Math.pow(QValue, 2))), 2, BigDecimal.ROUND_HALF_UP);
            return result.doubleValue();
        }
    }
    private Date[] calResultTime(ItemVO predictItem, Date startTimeReq, Date endTimeReq, int lengthLeft, int lengthRight) {
        Date[] result = new Date[3];
        Date predictTime = predictItem.getLastTime();
        Integer granularity = predictItem.getGranularity();
        Date startTime = startTimeReq;
        if (startTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(predictItem.getLastTime());
            calendar.add(Calendar.MINUTE, -1 * lengthLeft);
            calendar.add(Calendar.SECOND, -1 * lengthLeft * granularity);
            startTime = calendar.getTime();
        }
        Date endTime = endTimeReq;
        if (endTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(predictItem.getLastTime());
            calendar.add(Calendar.MINUTE, lengthRight);
            calendar.add(Calendar.SECOND, lengthRight * granularity);
            endTime = calendar.getTime();
        }
        if (endTime.getTime() <= startTime.getTime()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            calendar.add(Calendar.MINUTE, lengthRight);
            calendar.add(Calendar.SECOND, lengthRight * granularity);
            endTime = calendar.getTime();
        }
        result[0] = predictTime;