package com.huatek.busi.service.impl.cable;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.huatek.busi.common.BusiConstant;
import com.huatek.busi.common.CurveType;
import com.huatek.busi.common.DateUtils;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.common.util.TimeUtil;
import com.huatek.busi.common.util.Tools;
import com.huatek.busi.dao.*;
import com.huatek.busi.dto.BusiSensorQueryParamDto;
import com.huatek.busi.dto.EquipmentInfoDto;
import com.huatek.busi.dto.HomeSearchDto;
import com.huatek.busi.dto.cable.BusiCableCirculationDto;
import com.huatek.busi.dto.cable.BusiCableCirculationFailureStatisticsDto;
import com.huatek.busi.dto.cable.BusiCableCirculationStatisticsDto;
import com.huatek.busi.dto.curve.BaseCurveQueryDto;
import com.huatek.busi.dto.curve.PointItemDto;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.cable.CableCirculationMapper;
import com.huatek.busi.mapper.cable.CableCirculationStatisticsMapper;
import com.huatek.busi.service.IBusiCableSensorService;
import com.huatek.busi.service.IBusiCableSubTreeService;
import com.huatek.busi.service.IecBydworkParamService;
import com.huatek.busi.service.cable.BusiCableThresholdService;
import com.huatek.busi.service.cable.CableCirculationCacheService;
import com.huatek.busi.service.cable.CableCirculationService;
import com.huatek.busi.service.impl.cac.AbstractCacEtlService;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.HomeActualDataVo;
import com.huatek.busi.vo.HomeActualInfoVo;
import com.huatek.busi.vo.HomeActualVo;
import com.huatek.busi.vo.cable.*;
import com.huatek.busi.vo.curve.PointItemVo;
import com.huatek.busi.vo.echarts.EchartLineDataVo;
import com.huatek.busi.vo.warning.BusiIcgeVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.WherePrams;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Stream;

import static com.huatek.busi.service.impl.cable.BusiCableCirculationServiceImpl.setYAxisData;

@Slf4j
@Component
@Service(interfaceClass = CableCirculationService.class)
@Transactional(rollbackFor = Exception.class)
public class CableCirculationServiceImpl extends AbstractCacEtlService<IBusiCable>
        implements CableCirculationService {

    @Autowired
    private CableCirculationMapper cableCirculationMapper;
    @Autowired
    private IecBydworkParamService iecBydworkParamService;
    @Autowired
    private BusiCableThresholdService busiCableThresholdService;
    @Autowired
    private CableCirculationDao circulationDao;
    @Autowired
    private BusiSiteTreeDao busiSiteTreeDao;
    @Autowired
    private CableCirculationCacheService cableCirculationCacheService;
    @Autowired
    private CableCirculationStatisticsMapper cableCirculationStatisticsMapper;

    @Autowired
    private CableCirculationDao cableCirculationDao;

    @Autowired
    private IBusiCableSubTreeService iBusiCableSubTreeService;

    @Autowired
    private BusiOnlineMonitorDataDao busiOnlineMonitorDataDao;

    @Autowired
    private BusiCableCirculationDao busiCableCirculationDao;

    @Autowired
    private BusiCableSensorDao busiCableSensorDao;

    @Autowired
    private IBusiCableSensorService iBusiCableSensorService;

    @Override
    public void saveHistoryData(IBusiCable cacEntity, EquipmentInfoDto equipmentInfo) {
        // 电缆环流
        // 设备状态
        String state = iecBydworkParamService.getIecType(cacEntity.getMainTreeId(), cacEntity.getTimeStamp());
        if (StringUtils.isEmpty(state)) {
            logger.warn("IecType is empty! eqmCode: {}, timeStamp: {}", cacEntity.getEquipmentCode(),
                    cacEntity.getTimeStamp());
        }
        cacEntity.setRunState(state);
        // 设置rowkey，导入hbase使用
        cacEntity.setHbaseRowkey(Tools.strReverse(TimeUtil.getTimeStr(cacEntity.getTimeStamp())) + "_"
                + cacEntity.getSensorId() + "_" + TimeUtil.getTimeStr(cacEntity.getTimeStamp()) + "_"
                + cacEntity.getCacMonitorTypeCode() + "_" + cacEntity.getMainTreeId());

        super.saveHistoryData(cacEntity, equipmentInfo);
    }

    @Override
    public void updateCurrentData(IBusiCable cacEntity, EquipmentInfoDto equipmentInfo) {
        cableCirculationCacheService.saveCableCirculationCache(cacEntity);
    }

    public HomeActualInfoVo build1(HomeActualInfoVo homeActualInfoVo, BusiCableSensor busiCableSensor, String mainTreeId) {
        homeActualInfoVo.setEquipmentBrand(busiCableSensor.getSensorBrand());
        homeActualInfoVo.setEquipmentName(busiCableSensor.getSensorName());
        homeActualInfoVo.setInstallLocation(busiCableSensor.getPositionDes());
        homeActualInfoVo.setEqmId(busiCableSensor.getEquipmentId());
        homeActualInfoVo.setPhase(busiCableSensor.getPosition());
        homeActualInfoVo.setManufactor(busiCableSensor.getManufactor());
        homeActualInfoVo.setSensorBrand(busiCableSensor.getSensorBrand());
        homeActualInfoVo.setUseDate(busiCableSensor.getUseDate());
        homeActualInfoVo.setSensorId(busiCableSensor.getSensorCode());
        homeActualInfoVo.setSensorName(busiCableSensor.getSensorName());
        homeActualInfoVo.setMainTreeId(mainTreeId);
        return homeActualInfoVo;
    }

    @Override
    public HomeActualVo queryActual(HomeSearchDto param) {
        HomeActualVo homeActualVo = new HomeActualVo();
        HomeActualInfoVo homeActualInfoVo = new HomeActualInfoVo();
        List<BusiCableSensor> busiCableSensors = busiCableSensorDao.list(new WherePrams()
                .where("sensor_code", param.getSensorCode()));

        if (ObjectUtils.isEmpty(busiCableSensors)) {
            return homeActualVo;
        }
        BusiCableSensor busiCableSensor = busiCableSensors.get(0);
        String mainTreeId = iBusiCableSubTreeService.findByPK(busiCableSensor.getEquipmentId()).getEquipmentId();
        homeActualInfoVo = build1(homeActualInfoVo, busiCableSensor, mainTreeId);


        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -1));
        List<BusiOnlineMonitorData> busiOnlineMonitorDatas = busiOnlineMonitorDataDao.list(new WherePrams()
                .where("sensor_code", param.getSensorCode())
                .and("day", "like", date));
        //组装各种率
        if (!ObjectUtils.isEmpty(busiOnlineMonitorDatas)) {
            BusiOnlineMonitorData busiOnlineMonitorData = busiOnlineMonitorDatas.get(0);
            homeActualInfoVo.setRunState(busiOnlineMonitorData.getRunState());
            homeActualInfoVo.setFalseAlarmRate(busiOnlineMonitorData.getFalseAlarmRate());
            homeActualInfoVo.setLossRate(busiOnlineMonitorData.getLossRate());
            homeActualInfoVo.setRepairCount(busiOnlineMonitorData.getRepairCount());
            homeActualInfoVo.setDTime(busiOnlineMonitorData.getCreatedTime());
        }
        homeActualVo.setHomeActualInfoVo(homeActualInfoVo);
        List<IBusiCable> list = cableCirculationDao.list(new WherePrams()
                .where("sensor_id", param.getSensorCode())
                .orderBy("time_stamp desc limit 1"));
        HomeActualDataVo homeActualDataVo = new HomeActualDataVo();
        List<HomeActualDataVo> homeActualDataVos = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {

            return homeActualVo;
        }

        IBusiCable iBusiCable = list.get(0);
        homeActualDataVo.setDTime(iBusiCable.getTimeStamp());
        homeActualDataVo.setName("电流)");
        homeActualDataVo.setValue(iBusiCable.getTotalCoreCurrent());
        BusiCableThreshold cableThreshold = busiCableThresholdService.getCableThreshold(mainTreeId, list.get(0).getRunState(), param.getSensorCode());

        String thresholdValue = "";
        if (!ObjectUtils.isEmpty(cableThreshold)) {
            thresholdValue = cableThreshold.getElectPrewarningVal();
        }
        homeActualDataVo.setThresholdValue(thresholdValue);
        homeActualDataVos.add(homeActualDataVo);
        homeActualVo.setHomeActualDataVos(homeActualDataVos);
        return homeActualVo;
    }

    @Override
    public List<HomeActualVo> queryActuals() {
        List<HomeActualVo> homeActualVos = new ArrayList<>();
        List<String> equipmentTypeList = new ArrayList<>();
        equipmentTypeList.add(SiteConstants.CableTreeEnum.DLHL_EQM.getValue());
        BusiSensorQueryParamDto param = new BusiSensorQueryParamDto();
        param.setEquipmentTypeList(equipmentTypeList);
        List<BusiSensorVo> sensorList = iBusiCableSensorService.findSensorList(param);
        if (CollectionUtils.isEmpty(sensorList)) {
            return homeActualVos;
        }
        for (BusiSensorVo busiSensorVo : sensorList) {
            HomeSearchDto homeSearchDto = new HomeSearchDto();
            homeSearchDto.setSensorCode(busiSensorVo.getSensorCode());
            HomeActualVo homeActualVo = this.queryActual(homeSearchDto);
            homeActualVo.setName(busiSensorVo.getMainEquipmentName());
            homeActualVos.add(homeActualVo);
        }
        return homeActualVos;
    }

    /**
     * 查询电缆环流信息
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> findCACPageData(Map<String, Object> params) {
        if (params.get("page") != null && params.get("limit") != null) {
            PageHelper.startPage(page(params), limit(params));
        }
        Page<Map<String, Object>> pageInfo = cableCirculationMapper.findCACPageData(params);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "请求成功", pageInfo.getResult());
    }

    @Override
    public Map<String, Object> exportCacMonitorData(Map<String, Object> mapParams) {
        Map<String, Object> returnMap = new HashMap<>();
        if (mapParams.containsKey("mainTreeId") && StringUtils.isNotEmpty(String.valueOf(mapParams.get("mainTreeId")))) {
            BusiSiteTree busiSiteTree = busiSiteTreeDao.get(String.valueOf(mapParams.get("mainTreeId")));
            List<BusiCableCirculationReportVo> circulationVos = cableCirculationMapper.exportCacMonitorData(mapParams);
            for (int i = 0; i < circulationVos.size(); i++) {
                if (circulationVos.get(i).getRunState().equals("1")) {
                    circulationVos.get(i).setRunState("发电");
                } else if (circulationVos.get(i).getRunState().equals("2")) {
                    circulationVos.get(i).setRunState("抽水");
                } else if (circulationVos.get(i).getRunState().equals("3")) {
                    circulationVos.get(i).setRunState("空闲");
                } else {
                    circulationVos.get(i).setRunState("空载");
                }
            }
            String replaceRegex = "[\\\\n`~!@#$%^&*()+=|{}':;',\\\\\\\\[\\\\\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
            String treeName = busiSiteTree.getName().replaceAll(replaceRegex, "-");
            returnMap.put("fileName", String.format("%s%s", treeName, "电缆环流监测数据"));
            returnMap.put("title", String.format("%s%s", treeName, "电缆环流监测数据"));
            if (circulationVos.isEmpty()) {
                circulationVos = new ArrayList<>();
                circulationVos.add(new BusiCableCirculationReportVo());
            } else {
//                circulationVos.stream().forEach(transformerIcge -> {
//                    transformerIcge.setType(SiteConstants.IcgeType.getName(transformerIcge.getType()));
//                });
            }
            returnMap.put("data", circulationVos);
        } else {
            throw new RuntimeException("主设备编码不正确");
        }
        return returnMap;
    }

//    @Override
//    public void updateCurrentData(IBusiCable cacEntity) {
//        cableCirculationCacheService.saveCableCirculationCache(cacEntity);
//    }


    @Override
    public void saveBusiWarning(IBusiCable cacEntity, String cacMonitorTypeCode, String sensorId,
                                EquipmentInfoDto equipmentInfo) {
        // 阈值
        BusiCableThreshold cableThreshold = busiCableThresholdService.getCableThreshold(cacEntity.getMainTreeId(), cacEntity.getRunState(), cacEntity.getSensorId());
        if (cableThreshold == null) {
            logger.warn("cableThreshold not exists! mainTreeId: {}, runState: {}, sensorCode: {}",
                    cacEntity.getMainTreeId(), cacEntity.getRunState(), cacEntity.getSensorId());
            return;
        }
        Map<String, Object> stabilityMap =
                busiStabilityService.getStabilityBySensorCodeAndStatus(sensorId, cacEntity.getRunState());
        // 电缆环流告警
        String txWarning = isDLHLWarning(cacEntity, cableThreshold);
        if ("1".equals(txWarning)) {
            // 保存告警
            BusiEqmWarning busiEqmWarning =
                    newEw(BusiConstant.EqType.EQ_TYPE7, BusiConstant.GzType.GZ_TYPE17, formateDlhlWarningMsg(cacEntity), cacMonitorTypeCode, "1");
            busiEqmWarning.setWarningTime(cacEntity.getTimeStamp());
            busiEqmWarning.setWarningFlag("1");
            busiEqmWarning.setRunState(cacEntity.getRunState());
            busiEqmWarning = this.buildCableWarning(busiEqmWarning, equipmentInfo);
            // 保存告警详情
            BusiIcgeVo busiIcgeVo = new BusiIcgeVo();
            busiIcgeVo.setCollectValue(cacEntity.getTotalCoreCurrent());
            busiIcgeVo.setAlarmValue(cacEntity.getTotalCoreCurrent());
            busiIcgeVo.setPhase(cacEntity.getPhase());
            busiIcgeVo.setEquipmentName(equipmentInfo.getSubEquipmentName());
            // 稳定性指标
            busiIcgeVo.setStabilityIndex(getString(stabilityMap, "totalCurrent", "--"));
            busiIcgeVo.setThresholdValue(cableThreshold.getElectThresholdVal());
            busiIcgeVo.setWarningValue(cableThreshold.getElectPrewarningVal());
            busiIcgeVo.setEquipmentStatus(cacEntity.getRunState());
            busiIcgeVo.setCollectDate(cacEntity.getTimeStamp());
            this.buildWarningInfo(busiEqmWarning, JSON.toJSONString(busiIcgeVo));
        } else if ("2".equals(txWarning)) {
            // 保存告警
            BusiEqmWarning busiEqmWarning =
                    newEw(BusiConstant.EqType.EQ_TYPE7, BusiConstant.GzType.GZ_TYPE17, formateDlhlWarningMsg(cacEntity), cacMonitorTypeCode, "2");
            busiEqmWarning.setWarningTime(cacEntity.getTimeStamp());
            busiEqmWarning.setWarningFlag("2");
            busiEqmWarning.setRunState(cacEntity.getRunState());
            busiEqmWarning = this.buildCableWarning(busiEqmWarning, equipmentInfo);
            // 保存告警详情
            BusiIcgeVo busiIcgeVo = new BusiIcgeVo();
            busiIcgeVo.setCollectValue(cacEntity.getTotalCoreCurrent());
            busiIcgeVo.setAlarmValue(cacEntity.getTotalCoreCurrent());
            busiIcgeVo.setPhase(cacEntity.getPhase());
            busiIcgeVo.setEquipmentName(equipmentInfo.getSubEquipmentName());
            // 稳定性指标
            busiIcgeVo.setStabilityIndex(getString(stabilityMap, "totalCurrent", "--"));
            busiIcgeVo.setThresholdValue(cableThreshold.getElectThresholdVal());
            busiIcgeVo.setWarningValue(cableThreshold.getElectPrewarningVal());
            busiIcgeVo.setEquipmentStatus(cacEntity.getRunState());
            busiIcgeVo.setCollectDate(cacEntity.getTimeStamp());
            this.buildWarningInfo(busiEqmWarning, JSON.toJSONString(busiIcgeVo));
        }
    }

    private String isDLHLWarning(IBusiCable cacEntity, BusiCableThreshold cableThreshold) {
        String flag = "0";
        if (cableThreshold.getElectThresholdVal() != null && !"".equals(cableThreshold.getElectThresholdVal())) {
            if (DecimalUtil.getVal(cacEntity.getTotalCoreCurrent()).compareTo(DecimalUtil.getVal(cableThreshold.getElectThresholdVal())) > 0) {
                if (DecimalUtil.getVal(cacEntity.getTotalCoreCurrent()).compareTo(DecimalUtil.getVal(cableThreshold.getElectPrewarningVal())) < 0) {
                    flag = "2";
                }
                if (DecimalUtil.getVal(cacEntity.getTotalCoreCurrent()).compareTo(DecimalUtil.getVal(cableThreshold.getElectPrewarningVal())) > 0) {
                    flag = "1";
                }
            }
        }
        return flag;
    }

    private String formateDlhlWarningMsg(IBusiCable cacEntity) {
        return format("电缆环流电流:{}(A)超标", cacEntity.getTotalCoreCurrent());
    }

    @Override
    protected List<Map<String, Object>> queryMonitorDataList(LocalDateTime startTime, LocalDateTime endTime) {
        return cableCirculationMapper.queryMonitorDataList(startTime, endTime);
    }

    @Override
    protected void saveBusiOnlineMonitorData(BusiOnlineMonitorData busiOnlineMonitorData, Map<String, Object> item) {
        String type = popString(item, "type");
        busiOnlineMonitorData.setSubEquipmentType(SiteConstants.CableTreeEnum.DLHL_EQM.getValue());
        busiOnlineMonitorData.setExtType(SiteConstants.ExternalTypeEnum.DL.getValue());
        busiOnlineMonitorData.setEquipmentType(SiteConstants.SiteTreeEnum.DL_EQM.getValue());
        // 这里将保存的任务交给父类方法完成，子类只需要修改指定几个字段就可以了
        super.saveBusiOnlineMonitorData(busiOnlineMonitorData, item);
    }

    @Override
    public List<BaseCurveQueryDto> findSensorCodeList(LocalDate day) {
        return cableCirculationMapper.findSensorCodeList(day.atStartOfDay(), day.plusDays(1).atStartOfDay());
    }

    @Override
    public List<PointItemVo> findDaylyPointList(BaseCurveQueryDto sensorCode, LocalDate day, String subType) {
        return cableCirculationMapper.findDaylyPointList(sensorCode, subType, day.atStartOfDay(),
                day.plusDays(1).atStartOfDay());
    }

    @Override
    public PointItemDto getDaylyPointStatistics(BaseCurveQueryDto param) {
        return cableCirculationMapper.getDaylyPointStatistics(param);
    }

    @Override
    public Map<String, Object> page(BusiCableCirculationDto dto) {
        PageInfo<BusiCableCirculationVo> pageInfo = PageHelper.startPage(dto.getPage(), dto.getLimit())
                .doSelectPageInfo(() -> cableCirculationMapper.selectBusiCableCircuPage(dto));
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "查询成功", pageInfo.getList());
    }

    @Override
    public Map<String, Object> addCable(BusiCableCirculationDto dto) {
        IBusiCable cableCirculation = new IBusiCable();
        BeanUtils.copyPropertiesWithIgnoreNull(dto, cableCirculation);
        cableCirculation.setId(Uuid.getUUID());
        cableCirculation.setStatus(SiteConstants.Status.NORMAL.getValue());
        cableCirculation.setTimeStamp(LocalDateTime.now());
        int count = circulationDao.add(cableCirculation);
        if (count > 0) {
            log.debug("addCable: {}", count);
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "新增成功", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "新增失败", "");
    }

    @Override
    public Map<String, Object> findCableById(String id) {
        IBusiCable circulation = circulationDao.get(id);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "操作成功", circulation);
    }

    @Override
    public Map<String, Object> updateCable(BusiCableCirculationDto dto) {
        IBusiCable cableCirculation = new IBusiCable();
        BeanUtils.copyPropertiesWithIgnoreNull(dto, cableCirculation);
        int count = circulationDao.updateLocal(cableCirculation);
        if (count > 0) {
            log.debug("updateCable: {}", count);
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "修改成功", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "修改失败", "");
    }

    @Override
    public Map<String, Object> deleteCable(List<String> ids) {
        //删除
        if (cableCirculationMapper.deleteBusiCable(ids) > 0) {
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "删除成功", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "删除失败", "");
    }

    @Override
    public Map<String, Object> getRealData(String equipmentId) {
        Map<String, Object> data = new HashMap<>();
        CableCirculationDataVo cableCirculationDataVos = new CableCirculationDataVo();
        // 查询实时数据
        List<BusiCableCirculationVo> realData = cableCirculationMapper.getRealData(equipmentId);
        if (CollectionUtil.isNotEmpty(realData)) {
            // 获取基本信息
            cableCirculationDataVos = busiCableThresholdService.getCableData(realData.get(0).getSensorId(), equipmentId);
        }
        data.put("realData", realData);
        data.put("cableData", cableCirculationDataVos);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "查询成功", data);
    }

    @Override
    public Map<String, Object> getHistoryTrendChart(BusiCableCirculationStatisticsDto dto) {
        EchartLineDataVo echartLineDataVo = getTrendData(dto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "查询成功", echartLineDataVo);
    }

    private EchartLineDataVo getTrendData(BusiCableCirculationStatisticsDto dto) {

        if (dto.getStartTime() == null || dto.getEndTime() == null) {
            dto.check();
        }
        CurveType curveType = CurveType.newInstance("电缆环流(A)", 1);
        String subTitle = "电缆环流(A)";

        EchartLineDataVo result = new EchartLineDataVo(subTitle + "趋势曲线");


        int availableCount = 0;
        // 设置X轴坐标值：升序且不重复；保存每条曲线每个X坐标对应的值在allPointMap里，X轴坐标值相同的点会覆盖
        Map<String, Map<String, Object>> allPointMap = Maps.newLinkedHashMap();
        List<BusiCableCirculationIncreaseRateCacheVo> historyDatas = cableCirculationStatisticsMapper.getHistoryData(dto);

        availableCount += historyDatas.size();
        String lineName = subTitle;
        Map<String, Object> valMap = Maps.newHashMapWithExpectedSize(historyDatas.size());
        for (BusiCableCirculationIncreaseRateCacheVo historyData : historyDatas) {
//            valMap.put(DateUtil.formatLcoalDateTime(historyData.getDTime()), historyData.getTotalCoreCurrent());
            valMap.put(historyData.getDTime().toString(), historyData.getTotalCoreCurrent());
        }
        allPointMap.put(lineName, valMap);
        //设置开始日期和结束日期之间的X轴值
        long days = ChronoUnit.DAYS.between(dto.getStartTime(), dto.getEndTime());
        if (days >= 0) {
            Stream.iterate(dto.getStartTime(), d -> d.plusDays(1)).limit(days + 1)
                    .forEach(day -> result.getXAxisData().add(day.toString()));
        }
        // 根据X轴进行构造曲线
        setYAxisData(result, curveType, allPointMap, subTitle);
        result.setAvailableCount(availableCount);
        return result;
    }

    @Override
    public BusiCableCirculationStatisticsVo getListEquInfo(String cacMonitorTypeCode, LocalDate day, String sensorCode) {
        BusiCableCirculationFailureStatisticsDto param = new BusiCableCirculationFailureStatisticsDto();
        param.setStartTime(day.atStartOfDay());
        param.setEndTime(day.plusDays(1).atStartOfDay());
        param.setCacMonitorTypeCode(cacMonitorTypeCode);
        param.setSensorCode(sensorCode);
        List<BusiCableCirculationStatisticsVo> list = cableCirculationMapper.getListEquInfo(param);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
