package com.hz.business.service.impl; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Assert; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.hz.business.base.*; import com.hz.business.domain.*; import com.hz.business.dto.BatteryFolderDto; import com.hz.business.dto.TagDto; import com.hz.business.enums.*; import com.hz.business.mapper.*; import com.hz.business.req.*; import com.hz.business.req.BatteryParam; import com.hz.business.service.IBatteryService; import com.hz.business.util.CustomerTitleHandler; import com.hz.business.util.PhoenixUtils; import com.hz.business.util.StrUtils; import com.hz.business.vo.*; import com.hz.common.config.HzConfig; import com.hz.common.constant.Constants; import com.hz.common.core.domain.entity.SysDictData; import com.hz.common.utils.*; import com.hz.system.mapper.SysDictDataMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import com.hz.common.utils.bean.BeanUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.apache.commons.collections.CollectionUtils; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.*; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; import java.util.stream.Collectors; /** * 电池信息Service业务层处理 * * @author zyg * @date 2022-02-15 */ @Slf4j @Service public class BatteryServiceImpl extends ServiceImpl implements IBatteryService { private static final String FAST_CHARGE = "C111"; @Value("${lindorm.database:}") private String database; @Value("${lindorm.talbeName:}") private String tableName; @Value("${lindorm.behaviorTable:}") private String behaviorTable; @Value("${lindorm.batteryTable:}") private String batteryTable; @Value("${lindorm.energyTable:}") private String energyTable; @Resource TagMapper tagMapper; @Resource BatteryTagMapper batteryTagMapper; @Resource BatteryFolderMapper batteryFolderMapper; @Resource BatteryCoreMapper batteryCoreMapper; @Resource BatteryModelMapper batteryModelMapper; @Resource TagChildMapper tagChildMapper; @Resource FolderMapper folderMapper; @Resource BatteryMapper batteryMapper; @Resource AlarmMsgMapper alarmMsgMapper; @Resource SysDictDataMapper dictDataMapper; @Resource ElectricQuantityMapper eqMapper; @Resource SohItemQuantityMapper sohMapper; @Resource SohOdoMapper sohOdoMapper; @Resource FastChargeBatteryMapper fastChargeBatteryMapper; @Resource KilometreCountMapper kilometreCountMapper; @Resource ModelAdjustableParamEntityMapper adjustableParamEntityMapper; /** * 查询电池信息 * * @param id 电池信息主键 * @return 电池信息 */ @Override public BatteryVo getBatteryDetail(Long id) throws SQLException { //查询数据 Battery battery = this.getById(id); //类型转换 BatteryVo vo = new BatteryVo(); BeanUtils.copyProperties(battery, vo); String model = vo.getPackModelCode() + vo.getCellModelCode(); Set batteryModelSet = new HashSet<>(); batteryModelSet.add(model); List batteryModelList = new ArrayList<>(); if (batteryModelSet.size() > 0) { batteryModelList = batteryModelMapper.getModel(model); } //翻译字段 //SOH float soh = 0f; try { soh = batteryModelMapper.getSohBySn(vo.getSn()); } catch (Exception e) { } vo.setSoh(String.valueOf(soh)); List batteryCoreList = new ArrayList<>(); if (vo.getBatteryCoreType() != null) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryCore::getBatteryCoreType, vo.getBatteryCoreType()); wp.eq(BatteryCore::getIsDelete, 0); wp.select(BatteryCore::getBatteryCoreType, BatteryCore::getName); batteryCoreList = batteryCoreMapper.selectList(wp); } List alarmMsgList = new ArrayList<>(); if (vo.getSn() != null) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.eq(AlarmMsg::getSn, vo.getSn()); wp.eq(AlarmMsg::getIsDelete, 0); wp.select(AlarmMsg::getAlarmStatus, AlarmMsg::getSn); alarmMsgList = alarmMsgMapper.selectList(wp); } vo.setChargeStatusText(ChargeStatusEnum.getDesc(vo.getChargeStatus())); vo.setBatteryStatusText(BatteryStatusEnum.getDesc(vo.getBatteryStatus())); if (batteryCoreList.size() > 0) { batteryCoreList.forEach(m -> { if (vo.getBatteryCoreType() != null && m.getBatteryCoreType().equals(vo.getBatteryCoreType())) { vo.setBatteryCoreTypeText(m.getName()); } }); } if (alarmMsgList.size() > 0) { alarmMsgList.forEach(m -> { if (vo.getSn() != null && m.getSn().equals(vo.getSn())) { vo.setFaultStatus(m.getAlarmStatus()); } }); } if (!CollectionUtils.isEmpty(batteryModelList)) { batteryModelList.forEach(m -> { if (vo.getPackModelCode() != null && m.getPackModel().equals(vo.getPackModelCode()) && vo.getCellModelCode() != null && m.getCellModel().equals(vo.getCellModelCode())) { vo.setBatteryModel(m.getBatteryModel()); } }); } vo.setFaultStatusText(FaultStatusEnum.getDesc(vo.getFaultStatus())); //计算剩余里程 List> flinkMapList = getFlinkMapList(batteryTable, vo.getSn()); if (flinkMapList.size() > 0 && flinkMapList.get(0).get("remain_odo") != null) { vo.setCurrentOdo(new BigDecimal(flinkMapList.get(0).get("remain_odo").toString()).setScale(2, RoundingMode.UP)); } Connection conn = null; PreparedStatement psSelect = null; //周均能耗 能耗排名 try { conn = PhoenixUtils.getConnection(); psSelect = conn.prepareStatement(" use " + database + " "); psSelect.setFetchSize(1000); psSelect.close(); String sql = "select energy,eg_rank from " + energyTable + " where sn ='" + vo.getSn() + "' order by id desc limit 1"; psSelect = conn.prepareStatement(sql); ResultSet resultSet = psSelect.executeQuery(); List> mapList = ResultSetToJson.toListMap(resultSet, false); if (mapList.size() > 0) { vo.setEnergyConsumeWeek(new BigDecimal(mapList.get(0).get("energy").toString())); vo.setEnergyConsumeOrder(Integer.valueOf(mapList.get(0).get("eg_rank").toString())); } } catch (Exception e) { } finally { if (psSelect != null) { psSelect.close(); } if (conn != null) { conn.close(); } } return vo; } /** * 通过sn获取电池详细信息 * * @param sn 参数 * @return 电池信息 */ @Override public BatteryVo getDetailInfo(String sn) throws SQLException { //todo //查询数据 Battery battery = this.getOne(new LambdaQueryWrapper() .last(" limit 1 ") .eq(Battery::getIsDelete, 0) .and(StringUtils.isNotBlank(sn), p -> p.like(Battery::getSn, sn) .or().like(Battery::getVin, sn))); //类型转换 BatteryVo vo = new BatteryVo(); BeanUtils.copyProperties(battery, vo); String model = vo.getPackModelCode() + vo.getCellModelCode(); Set batteryModelSet = new HashSet<>(); batteryModelSet.add(model); List batteryModelList = new ArrayList<>(); if (batteryModelSet.size() > 0) { batteryModelList = batteryModelMapper.getModel(model); } //翻译字段 List batteryCoreList = new ArrayList<>(); if (vo.getBatteryCoreType() != null) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryCore::getBatteryCoreType, vo.getBatteryCoreType()); wp.eq(BatteryCore::getIsDelete, 0); wp.select(BatteryCore::getBatteryCoreType, BatteryCore::getName); batteryCoreList = batteryCoreMapper.selectList(wp); } List alarmMsgList = new ArrayList<>(); if (vo.getSn() != null) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.eq(AlarmMsg::getSn, vo.getSn()); wp.eq(AlarmMsg::getIsDelete, 0); wp.select(AlarmMsg::getAlarmStatus, AlarmMsg::getSn); alarmMsgList = alarmMsgMapper.selectList(wp); } vo.setChargeStatusText(ChargeStatusEnum.getDesc(vo.getChargeStatus())); vo.setBatteryStatusText(BatteryStatusEnum.getDesc(vo.getBatteryStatus())); if (batteryCoreList.size() > 0) { batteryCoreList.forEach(m -> { if (vo.getBatteryCoreType() != null && m.getBatteryCoreType().equals(vo.getBatteryCoreType())) { vo.setBatteryCoreTypeText(m.getName()); } }); } if (alarmMsgList.size() > 0) { alarmMsgList.forEach(m -> { if (vo.getSn() != null && m.getSn().equals(vo.getSn())) { vo.setFaultStatus(m.getAlarmStatus()); } }); } if (!CollectionUtils.isEmpty(batteryModelList)) { batteryModelList.forEach(m -> { if (vo.getPackModelCode() != null && m.getPackModel().equals(vo.getPackModelCode()) && vo.getCellModelCode() != null && m.getCellModel().equals(vo.getCellModelCode())) { vo.setBatteryModel(m.getBatteryModel()); } }); } vo.setFaultStatusText(FaultStatusEnum.getDesc(vo.getFaultStatus())); //翻译字段 //SOH float soh = 0f; try { soh = batteryModelMapper.getSohBySn(vo.getSn()); } catch (Exception e) { } vo.setSoh(String.valueOf(soh)); //计算剩余里程 try { List> flinkMapList = getFlinkMapList(batteryTable, vo.getSn()); if (flinkMapList.size() > 0 && flinkMapList.get(0).get("remain_odo") != null) { vo.setCurrentOdo(new BigDecimal(flinkMapList.get(0).get("remain_odo").toString()).setScale(2, RoundingMode.UP)); } } catch (Exception e) { } Connection conn = null; PreparedStatement psSelect = null; //周均能耗 能耗排名 try { conn = PhoenixUtils.getConnection(); psSelect = conn.prepareStatement(" use " + database + " "); psSelect.setFetchSize(1000); psSelect.close(); String sql = "select energy,eg_rank from " + energyTable + " where sn ='" + vo.getSn() + "' order by id desc limit 1"; psSelect = conn.prepareStatement(sql); ResultSet resultSet = psSelect.executeQuery(); List> mapList = ResultSetToJson.toListMap(resultSet, false); if (mapList.size() > 0) { vo.setEnergyConsumeWeek(new BigDecimal(mapList.get(0).get("energy").toString())); vo.setEnergyConsumeOrder(Integer.valueOf(mapList.get(0).get("eg_rank").toString())); } } catch (Exception e) { } finally { if (psSelect != null) { psSelect.close(); } if (conn != null) { conn.close(); } } return vo; } /** * 查询自定义分析-电池编号精确查询 * * @param sn 参数 * @return 电池信息 */ @Override public BatteryVo getBattery(String sn) { String[] sns = sn.split(","); //类型转换 BatteryVo vo = new BatteryVo(); //查询数据 for (String sn1 : sns) { Battery battery = this.getOne(new QueryWrapper() .last(" limit 1 ") .eq("is_delete", 0) .and(p -> p.eq("sn", sn1) .or().eq("vin", sn1))); Assert.notNull(battery, "未找到电池编号为" + sn1 + "的电池信息"); BeanUtils.copyProperties(battery, vo); } String model = vo.getPackModelCode() + vo.getCellModelCode(); Set batteryModelSet = new HashSet<>(); batteryModelSet.add(model); List batteryModelList = new ArrayList<>(); if (batteryModelSet.size() > 0) { batteryModelList = batteryModelMapper.getModel(model); } //翻译字段 List batteryCoreList = new ArrayList<>(); if (vo.getBatteryCoreType() != null) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryCore::getBatteryCoreType, vo.getBatteryCoreType()); wp.eq(BatteryCore::getIsDelete, 0); wp.select(BatteryCore::getBatteryCoreType, BatteryCore::getName); batteryCoreList = batteryCoreMapper.selectList(wp); } List alarmMsgList = new ArrayList<>(); if (vo.getSn() != null) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.eq(AlarmMsg::getSn, vo.getSn()); wp.eq(AlarmMsg::getIsDelete, 0); wp.select(AlarmMsg::getAlarmStatus, AlarmMsg::getSn); alarmMsgList = alarmMsgMapper.selectList(wp); } vo.setChargeStatusText(ChargeStatusEnum.getDesc(vo.getChargeStatus())); vo.setBatteryStatusText(BatteryStatusEnum.getDesc(vo.getBatteryStatus())); if (batteryCoreList.size() > 0) { batteryCoreList.forEach(m -> { if (vo.getBatteryCoreType() != null && m.getBatteryCoreType().equals(vo.getBatteryCoreType())) { vo.setBatteryCoreTypeText(m.getName()); } }); } if (alarmMsgList.size() > 0) { alarmMsgList.forEach(m -> { if (vo.getSn() != null && m.getSn().equals(vo.getSn())) { vo.setFaultStatus(m.getAlarmStatus()); } }); } if (!CollectionUtils.isEmpty(batteryModelList)) { batteryModelList.forEach(m -> { if (vo.getPackModelCode() != null && m.getPackModel().equals(vo.getPackModelCode()) && vo.getCellModelCode() != null && m.getCellModel().equals(vo.getCellModelCode())) { vo.setBatteryModel(m.getBatteryModel()); } }); } vo.setFaultStatusText(FaultStatusEnum.getDesc(vo.getFaultStatus())); return vo; } /** * 查询电池信息列表 * * @param param 电池信息 * @return 电池信息集合 */ @Override public PageInfo selectBatteryList(BatteryParam param) { //电池类型 List cellList = new ArrayList<>(); List packList = new ArrayList<>(); if (!param.getBatteryModel().isEmpty()) { List batteryModel = batteryModelMapper.selectList(new LambdaQueryWrapper().in(!param.getBatteryModel().isEmpty(), BatteryModel::getId, param.getBatteryModel())); batteryModel.forEach(o -> { cellList.add(o.getCellModel()); packList.add(o.getPackModel()); }); } //故障状态 Set snSet = new HashSet<>(); List> alarmMsgList = batteryMapper.getFaultDeviceList(null); if (alarmMsgList.size() > 0) { alarmMsgList.forEach(o -> { if (o != null && o.get("sn") != null) { snSet.add(o.get("sn").toString()); } }); } /*LambdaQueryWrapper wap = new LambdaQueryWrapper<>(); wap.eq(AlarmMsg::getIsDelete, 0); wap.isNull(AlarmMsg::getAlarmFreeTime); wap.select(AlarmMsg::getSn); List alarmMsgList = alarmMsgMapper.selectList(wap); if (alarmMsgList.size() > 0) { alarmMsgList.forEach(o -> snSet.add(o.getSn())); }*/ if (param.getFaultStatus() != null) { if (param.getFaultStatus() == 1) { if (CollectionUtils.isEmpty(snSet)) { return new PageInfo<>(); } } } //用户标签 Set batteryIdSet = new HashSet<>(); if (StringUtils.isNotBlank(param.getTag())) { List tags = new ArrayList<>(); tags = Arrays.asList(param.getTag().split(",")); Set tagIdSet = new HashSet<>(); tags.forEach(o -> tagIdSet.add(Long.parseLong(o))); if (tags.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryTag::getTagId, tagIdSet); wp.eq(BatteryTag::getTagType, 0); wp.eq(BatteryTag::getIsDelete, 0); wp.isNotNull(BatteryTag::getBatteryId); wp.select(BatteryTag::getBatteryId); List batteryTags = batteryTagMapper.selectList(wp); if (batteryTags.size() > 0) { batteryTags.forEach(o -> batteryIdSet.add(o.getBatteryId())); } } if (CollectionUtils.isEmpty(batteryIdSet)) { return new PageInfo<>(); } } PageHelper.startPage(param.getPageIndex(), param.getPageSize()); QueryWrapper wrapper = new QueryWrapper<>(); wrapper.and(StringUtils.isNotBlank(param.getSn()), p -> p.like("sn", param.getSn()) .or().like("vin", param.getSn())); wrapper.in(!packList.isEmpty(), "pack_model_code", packList); wrapper.in(!cellList.isEmpty(), "cell_model_code", cellList); wrapper.eq("is_delete", 0); wrapper.eq(StringUtils.isNotBlank(param.getBatteryCoreType()), "battery_core_type", param.getBatteryCoreType()); wrapper.in(batteryIdSet.size() > 0, "id", batteryIdSet); wrapper.in((param.getFaultStatus() != null && param.getFaultStatus() == 1 && snSet.size() > 0), "sn", snSet); wrapper.notIn((param.getFaultStatus() != null && param.getFaultStatus() == 0 && snSet.size() > 0), "sn", snSet); wrapper.orderByDesc("update_time"); //查询结果 List list = this.list(wrapper); PageInfo orderPageInfo = new PageInfo<>(list); List batteryVoList = new ArrayList<>(); //准备翻译 List tagList = new ArrayList<>(); List batteryFolderList = new ArrayList<>(); List batteryModelList = new ArrayList<>(); List batteryCorelList = new ArrayList<>(); Set batteryCoreSet = new HashSet<>(); Set collectIdSet = new HashSet<>(); Set snFaultSet = new HashSet<>(); List modelList = new ArrayList<>(); List batteryModelSet = new ArrayList<>(); orderPageInfo.getList().forEach(o -> { if (o.getBatteryCoreType() != null) { batteryCoreSet.add(o.getBatteryCoreType()); } if (o.getPackModelCode() != null && o.getCellModelCode() != null) { String model = o.getPackModelCode() + o.getCellModelCode(); if (!batteryModelSet.contains(model)) { batteryModelSet.add(model); } } collectIdSet.add(o.getId()); snFaultSet.add(o.getSn()); }); if (snFaultSet.size() > 0) { String[] strArray = snFaultSet.toArray(new String[snFaultSet.size()]); List> modelDetailList = batteryMapper.getFaultDetail(strArray); if (!CollectionUtils.isEmpty(modelDetailList)) { modelList = JSONArray.parseArray(JSON.toJSONString(modelDetailList), ModelDetailVo.class); } } if (batteryModelSet.size() > 0) { batteryModelList = batteryModelMapper.getModelByPackAndCellModel(batteryModelSet); } List batteryCoreList = getDictDataByType("business_battery_core_type"); if (batteryCoreSet.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryCore::getBatteryCoreType, batteryCoreSet); wp.eq(BatteryCore::getIsDelete, 0); wp.select(BatteryCore::getBatteryCoreType, BatteryCore::getName); batteryCorelList = batteryCoreMapper.selectList(wp); } if (collectIdSet.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryFolder::getBatteryId, collectIdSet); wp.eq(BatteryFolder::getFolderType, 0); wp.eq(BatteryFolder::getIsDelete, 0); wp.eq(BatteryFolder::getUserId, SecurityUtils.getUserId()); wp.select(BatteryFolder::getBatteryId); batteryFolderList = batteryFolderMapper.selectList(wp); tagList = tagMapper.getTagList(collectIdSet, 0); } List finalBatteryModelList = batteryModelList; List finalTagList = tagList; List finalBatteryCorelList = batteryCorelList; List finalBatteryFolderList = batteryFolderList; List finalModelDetailVoList = modelList; orderPageInfo.getList().forEach(o -> { BatteryVo vo = new BatteryVo(); BeanUtils.copyProperties(o, vo); vo.setChargeStatusText(ChargeStatusEnum.getDesc(vo.getChargeStatus())); if (!CollectionUtils.isEmpty(finalBatteryCorelList)) { finalBatteryCorelList.forEach(m -> { if (o.getBatteryCoreType() != null && m.getBatteryCoreType().equals(o.getBatteryCoreType())) { vo.setBatteryCoreTypeText(m.getName()); } }); } if (finalBatteryFolderList.size() > 0) { finalBatteryFolderList.forEach(m -> { if (o.getId() != null && m.getBatteryId().equals(o.getId())) { vo.setCollected(1); } }); } if (finalBatteryModelList.size() > 0) { finalBatteryModelList.forEach(m -> { if (o.getPackModelCode() != null && m.getPackModel().equals(o.getPackModelCode()) && o.getCellModelCode() != null && m.getCellModel().equals(o.getCellModelCode())) { vo.setBatteryModel(m.getBatteryModel()); } }); } if (finalModelDetailVoList.size() > 0) { finalModelDetailVoList.forEach(m -> { if (m.getSn().equals(o.getSn())) { vo.setAlarmName(m.getAlgoName()); vo.setFaultLocation(m.getFaultLocation()); vo.setFaultInfluence(m.getFaultInfluence()); } }); } if (finalTagList.size() > 0) { Set tagIdList = new HashSet<>(); Set tagNameList = new HashSet<>(); finalTagList.forEach(m -> { if (o.getId() != null && m.getBatteryId().equals(o.getId())) { tagIdList.add(String.valueOf(m.getId())); tagNameList.add(m.getTagName()); } }); if (tagIdList.size() > 0) { vo.setTag(String.join(",", tagIdList)); vo.setTagText(String.join(",", tagNameList)); } } vo.setFaultStatus(FaultStatusEnum.GOOD.code()); if (snSet.size() > 0) { if (o.getSn() != null && snSet.contains(o.getSn())) { vo.setFaultStatus(FaultStatusEnum.BAD.code()); } } vo.setFaultStatusText(FaultStatusEnum.getDesc(vo.getFaultStatus())); batteryVoList.add(vo); }); PageInfo result = new PageInfo<>(batteryVoList); result.setTotal(orderPageInfo.getTotal()); return result; } /** * 查询快充电池信息列表 * * @param param 电池信息 * @return 电池信息集合 */ @Override public PageInfo selectFastChargeBatteryList(BatteryParam param) { //电池类型 List cellList = new ArrayList<>(); List packList = new ArrayList<>(); if (!param.getBatteryModel().isEmpty()) { List batteryModel = batteryModelMapper.selectList(new LambdaQueryWrapper().in(!param.getBatteryModel().isEmpty(), BatteryModel::getId, param.getBatteryModel())); batteryModel.forEach(o -> { cellList.add(o.getCellModel()); packList.add(o.getPackModel()); }); } //故障状态 Set snSet = new HashSet<>(); List> alarmMsgList = batteryMapper.getFaultDeviceList(FAST_CHARGE); if (alarmMsgList.size() > 0) { alarmMsgList.forEach(o -> { if (o != null && o.get("sn") != null) { snSet.add(o.get("sn").toString()); } }); } /*LambdaQueryWrapper wap = new LambdaQueryWrapper<>(); wap.eq(AlarmMsg::getIsDelete, 0); wap.eq(AlarmMsg::getModelCode, FAST_CHARGE); wap.isNull(AlarmMsg::getAlarmFreeTime); wap.select(AlarmMsg::getSn); List alarmMsgList = alarmMsgMapper.selectList(wap); if (alarmMsgList.size() > 0) { alarmMsgList.forEach(o -> snSet.add(o.getSn())); }*/ if (param.getFaultStatus() != null) { if (param.getFaultStatus() == 1) { if (CollectionUtils.isEmpty(snSet)) { return new PageInfo<>(); } } } //用户标签 Set batteryIdSet = new HashSet<>(); if (StringUtils.isNotBlank(param.getTag())) { List tags = new ArrayList<>(); tags = Arrays.asList(param.getTag().split(",")); Set tagIdSet = new HashSet<>(); tags.forEach(o -> tagIdSet.add(Long.parseLong(o))); if (tags.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryTag::getTagId, tagIdSet); wp.eq(BatteryTag::getTagType, 0); wp.eq(BatteryTag::getIsDelete, 0); wp.isNotNull(BatteryTag::getBatteryId); wp.select(BatteryTag::getBatteryId); List batteryTags = batteryTagMapper.selectList(wp); if (batteryTags.size() > 0) { batteryTags.forEach(o -> batteryIdSet.add(o.getBatteryId())); } } if (CollectionUtils.isEmpty(batteryIdSet)) { return new PageInfo<>(); } } PageHelper.startPage(param.getPageIndex(), param.getPageSize()); QueryWrapper wrapper = new QueryWrapper<>(); wrapper.and(StringUtils.isNotBlank(param.getSn()), p -> p.like("sn", param.getSn()) .or().like("vin", param.getSn())); wrapper.in(!packList.isEmpty(), "pack_model_code", packList); wrapper.in(!cellList.isEmpty(), "cell_model_code", cellList); wrapper.eq(StringUtils.isNotBlank(param.getBatteryCoreType()), "battery_core_type", param.getBatteryCoreType()); wrapper.in(batteryIdSet.size() > 0, "id", batteryIdSet); wrapper.in((param.getFaultStatus() != null && param.getFaultStatus() == 1 && snSet.size() > 0), "sn", snSet); wrapper.notIn((param.getFaultStatus() != null && param.getFaultStatus() == 0 && snSet.size() > 0), "sn", snSet); wrapper.orderByDesc("update_time"); //查询结果 List list = fastChargeBatteryMapper.selectList(wrapper); PageInfo orderPageInfo = new PageInfo<>(list); List batteryVoList = new ArrayList<>(); //准备翻译 List tagList = new ArrayList<>(); List batteryFolderList = new ArrayList<>(); List batteryModelList = new ArrayList<>(); List batteryCorelList = new ArrayList<>(); Set batteryCoreSet = new HashSet<>(); Set collectIdSet = new HashSet<>(); List batteryModelSet = new ArrayList<>(); orderPageInfo.getList().forEach(o -> { if (o.getBatteryCoreType() != null) { batteryCoreSet.add(o.getBatteryCoreType()); } if (o.getPackModelCode() != null && o.getCellModelCode() != null) { String model = o.getPackModelCode() + o.getCellModelCode(); if (!batteryModelSet.contains(model)) { batteryModelSet.add(model); } } collectIdSet.add(o.getId()); }); if (batteryModelSet.size() > 0) { batteryModelList = batteryModelMapper.getModelByPackAndCellModel(batteryModelSet); } if (batteryCoreSet.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryCore::getBatteryCoreType, batteryCoreSet); wp.eq(BatteryCore::getIsDelete, 0); wp.select(BatteryCore::getBatteryCoreType, BatteryCore::getName); batteryCorelList = batteryCoreMapper.selectList(wp); } if (collectIdSet.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(BatteryFolder::getBatteryId, collectIdSet); wp.eq(BatteryFolder::getFolderType, 0); wp.eq(BatteryFolder::getIsDelete, 0); wp.eq(BatteryFolder::getUserId, SecurityUtils.getUserId()); wp.select(BatteryFolder::getBatteryId); batteryFolderList = batteryFolderMapper.selectList(wp); tagList = tagMapper.getTagList(collectIdSet, 0); } List finalBatteryModelList = batteryModelList; List finalTagList = tagList; List finalBatteryCorelList = batteryCorelList; List finalBatteryFolderList = batteryFolderList; orderPageInfo.getList().forEach(o -> { FastChargeBatteryVo vo = new FastChargeBatteryVo(); BeanUtils.copyProperties(o, vo); if (!CollectionUtils.isEmpty(finalBatteryCorelList)) { finalBatteryCorelList.forEach(m -> { if (o.getBatteryCoreType() != null && m.getBatteryCoreType().equals(o.getBatteryCoreType())) { vo.setBatteryCoreTypeText(m.getName()); } }); } if (finalBatteryFolderList.size() > 0) { finalBatteryFolderList.forEach(m -> { if (o.getId() != null && m.getBatteryId().equals(o.getId())) { vo.setCollected(1); } }); } if (finalBatteryModelList.size() > 0) { finalBatteryModelList.forEach(m -> { if (o.getPackModelCode() != null && m.getPackModel().equals(o.getPackModelCode()) && o.getCellModelCode() != null && m.getCellModel().equals(o.getCellModelCode())) { vo.setBatteryModel(m.getBatteryModel()); } }); } if (finalTagList.size() > 0) { Set tagIdList = new HashSet<>(); Set tagNameList = new HashSet<>(); finalTagList.forEach(m -> { if (o.getId() != null && m.getBatteryId().equals(o.getId())) { tagIdList.add(String.valueOf(m.getId())); tagNameList.add(m.getTagName()); } }); if (tagIdList.size() > 0) { vo.setTag(String.join(",", tagIdList)); vo.setTagText(String.join(",", tagNameList)); } } vo.setFaultStatus(FaultStatusEnum.GOOD.code()); if (snSet.size() > 0) { if (o.getSn() != null && snSet.contains(o.getSn())) { vo.setFaultStatus(FaultStatusEnum.BAD.code()); } } vo.setFaultStatusText(FaultStatusEnum.getDesc(vo.getFaultStatus())); batteryVoList.add(vo); }); PageInfo result = new PageInfo<>(batteryVoList); result.setTotal(orderPageInfo.getTotal()); return result; } private void setTotalBatteryTotal(TodayCompareOtherVo bsVo, BatteryOverviewParam param, List carModelList) { //车型数据 //当日 、昨日、上周、上月 字符串 Date yesDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd 23:59:59"); String yesterday = sf.format(yesDate); String today = sf.format(new Date()); String lastWeek = DateUtil.getPreviousWeekSunday() + " 23:59:59"; String lastMonth = DateUtil.getLastMaxMonthDate() + " 23:59:59"; //找到了数据 String carModel = carModelList.size() > 0 ? "'" + String.join("','", carModelList) + "'" : null; int yes = batteryMapper.getBatteryTotalCountByDate(yesterday, carModel, param.getPackModel()); int tod = batteryMapper.getBatteryTotalCountByDate(today, carModel, param.getPackModel()); int law = batteryMapper.getBatteryTotalCountByDate(lastWeek, carModel, param.getPackModel()); int lam = batteryMapper.getBatteryTotalCountByDate(lastMonth, carModel, param.getPackModel()); bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //当日数据提前准备 bsVo.setCount(DecimalFormat.getNumberInstance().format(tod)); bsVo.setYesterday(calculateRate(BigDecimal.valueOf(tod), BigDecimal.valueOf(yes))); int res = setFlag(BigDecimal.valueOf(tod), BigDecimal.valueOf(yes)); bsVo.setYesterdayFlag(res); bsVo.setWeek(calculateRate(BigDecimal.valueOf(tod), BigDecimal.valueOf(law))); res = setFlag(BigDecimal.valueOf(tod), BigDecimal.valueOf(law)); bsVo.setWeekFlag(res); bsVo.setMonth(calculateRate(BigDecimal.valueOf(tod), BigDecimal.valueOf(lam))); res = setFlag(BigDecimal.valueOf(tod), BigDecimal.valueOf(lam)); bsVo.setMonthFlag(res); } /** * 获取电池数据概览 * * @return com.hz.business.vo.BatteryStatisticsVo */ private void setBatteryStatistics(BatteryStatisticsVo bsVo, BatteryOverviewParam param, List carModelList, int total) { // Date nowDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); Date yesDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 2); //两点前数据为更新完毕的情况,采用t+2数据 Date frontDates = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 3); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd020000"); //今日 String today = sf.format(nowDate).replaceAll("-", ""); //T+1 String yesterday = sf.format(yesDate).replaceAll("-", ""); String lastWeek = DateUtil.getPreviousWeekSundayYes(nowDate); String todays = sf.format(yesDate).replaceAll("-", ""); //T+2 String yesterdays = sf.format(frontDates).replaceAll("-", ""); String lastWeeks = DateUtil.getPreviousWeekSundayYes(yesDate); String lastMonth = DateUtil.getLastMaxMonthDateYes(); lastWeek = lastWeek.replaceAll("-", ""); lastMonth = lastMonth.replaceAll("-", ""); lastWeeks = lastWeeks.replaceAll("-", ""); List dateStrList = new ArrayList<>(); if (Long.valueOf(sdf.format(new Date())) > Long.valueOf(sdf2.format(new Date()))) { dateStrList.add(today); dateStrList.add(yesterday); dateStrList.add(lastWeek); } else { dateStrList.add(todays); dateStrList.add(yesterdays); dateStrList.add(lastWeeks); } dateStrList.add(lastMonth); String[] strArray = dateStrList.toArray(new String[dateStrList.size()]); String carModel = carModelList.size() > 0 ? "'" + String.join("','", carModelList) + "'" : null; List> mapList = batteryMapper.getHistoryData(carModel, param.getPackModel(), param.getCellModel(), strArray); List quantityItemVoList = new ArrayList<>(); if (mapList.size() > 0) { quantityItemVoList = JSONArray.parseArray(JSON.toJSONString(mapList), QuantityItemDateStaticVo.class); } //1-电池总量 2-24小时充电总电能(kWh) 3-放电总时长 4-行驶总里程 5-电池类型 6-在线电池总量 //电池总量 TodayCompareOtherVo totalBatteryCountVo = new TodayCompareOtherVo(); totalBatteryCountVo.setTitle("电池总数(台)"); totalBatteryCountVo.setContent("统计平台接入电池的总数"); setYesWeekMonthData(totalBatteryCountVo, quantityItemVoList, BatteryOverviewEnum.TOTAL.code(), today, yesterday, lastWeek, todays, yesterdays, lastWeeks, lastMonth, total); bsVo.setTotalBatteryCountVo(totalBatteryCountVo); //装机总量指标 TodayCompareOtherVo totalElectricQuantityVo = new TodayCompareOtherVo(); totalElectricQuantityVo.setTitle("装机总能量(kWh)"); totalElectricQuantityVo.setContent("统计所有电池的能量总和"); setWeekMonthData(totalElectricQuantityVo, quantityItemVoList, BatteryOverviewEnum.CAPACITY.code(), today, yesterday, lastWeek, todays, yesterdays, lastWeeks, lastMonth, total); bsVo.setTotalElectricQuantityVo(totalElectricQuantityVo); int count = Integer.parseInt(totalBatteryCountVo.getCount().replaceAll(",", "")); //24小时充电总能量 TodayCompareOtherVo allDayChargeVo = new TodayCompareOtherVo(); allDayChargeVo.setTitle("昨日充电总能量(kWh)"); allDayChargeVo.setContent("昨日电池充入的总能量"); setYesWeekMonthData(allDayChargeVo, quantityItemVoList, BatteryOverviewEnum.CHARGE.code(), today, yesterday, lastWeek, todays, yesterdays, lastWeeks, lastMonth, count); bsVo.setAllDayChargeVo(allDayChargeVo); //行驶总里程 TodayCompareOtherVo totalMileageVo = new TodayCompareOtherVo(); totalMileageVo.setTitle("行驶总里程(百万公里)"); totalMileageVo.setContent("所有车辆行驶里程数的总和"); setYesWeekMonthData(totalMileageVo, quantityItemVoList, BatteryOverviewEnum.ODO.code(), today, yesterday, lastWeek, todays, yesterdays, lastWeeks, lastMonth, count); if (totalMileageVo.getCount() != null) { String res = DecimalFormat.getNumberInstance().format(new BigDecimal(totalMileageVo.getCount().replaceAll(",", "")) .divide(BigDecimal.valueOf(1000000), 2, RoundingMode.HALF_UP)); totalMileageVo.setCount(res); } bsVo.setTotalMileageVo(totalMileageVo); //在线电池总量 TodayCompareOtherVo onLineBatteryVo = new TodayCompareOtherVo(); onLineBatteryVo.setTitle("昨日上线电池数(台)"); onLineBatteryVo.setPrompt("昨日上线电池比例(%)"); onLineBatteryVo.setContent("昨日上线电池数及比例,比例计算方式:昨日上线电池数/昨日电池总量*100%"); setYesWeekMonthData(onLineBatteryVo, quantityItemVoList, BatteryOverviewEnum.ONLINE.code(), today, yesterday, lastWeek, todays, yesterdays, lastWeeks, lastMonth, count); //千分位处理 //setOnLineBatteryData(onLineBatteryVo, param, BigDecimal.valueOf(total), carModelList); bsVo.setOnLineBatteryVo(onLineBatteryVo); } private void setWeekMonthData(TodayCompareOtherVo bsVo, List quantityItemVoList, Integer type, String today, String yesterday, String lastWeek, String todays, String yesterdays, String lastWeeks, String lastMonth, int total) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd020000"); bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //当日数据提前准备 if (quantityItemVoList.size() > 0) { BigDecimal tod = BigDecimal.ZERO; BigDecimal yes = BigDecimal.ZERO; BigDecimal law = BigDecimal.ZERO; BigDecimal lam = BigDecimal.ZERO; List list = quantityItemVoList.stream() .filter(o -> String.valueOf(type).equals(o.getItem())).collect(Collectors.toList()); for (QuantityItemDateStaticVo vo : list) { if (Long.valueOf(sdf.format(new Date())) > Long.valueOf(sdf2.format(new Date()))) { if (vo.getStaticDate().equals(today)) { tod = vo.getQuantity(); } if (vo.getStaticDate().equals(lastWeek)) { law = vo.getQuantity(); } } else { if (vo.getStaticDate().equals(todays)) { tod = vo.getQuantity(); } if (vo.getStaticDate().equals(lastWeeks)) { law = vo.getQuantity(); } } if (vo.getStaticDate().equals(lastMonth)) { lam = vo.getQuantity(); } } if (type == 8) { bsVo.setCount(DecimalFormat.getNumberInstance().format(tod.divide(BigDecimal.valueOf(1L), 2, RoundingMode.HALF_UP))); } else { bsVo.setCount(DecimalFormat.getNumberInstance().format(tod)); } boolean percent = false; if (type.equals(BatteryOverviewEnum.CAPACITY.code())) { percent = true; } if (percent) { if (law.compareTo(BigDecimal.ZERO) != 0 && yes.compareTo(BigDecimal.ZERO) != 0 && lam.compareTo(BigDecimal.ZERO) != 0) { bsVo.setYesterday(calculateRate(tod, yes)); int res; bsVo.setWeek(calculateRate(tod, law)); res = setFlag(tod, law); bsVo.setWeekFlag(res); bsVo.setMonth(calculateRate(tod, lam)); res = setFlag(tod, lam); bsVo.setMonthFlag(res); } else { bsVo.setWeek("0"); bsVo.setMonth("0"); bsVo.setWeekFlag(3); bsVo.setMonthFlag(3); } } } } /** * 获取电池数据概览 * * @return com.hz.business.vo.BatteryStatisticsVo */ @Override @Cacheable(cacheNames = "query::batteryStatisticsCache", key = "#batteryOverviewParam") public BatteryStatisticsVo getBatteryStatistics(BatteryOverviewParam batteryOverviewParam) { BatteryStatisticsVo bsVo = new BatteryStatisticsVo(); //改为合众车型查询 List carModelList1 = new ArrayList<>(); List carModelList = new ArrayList<>(); if (!batteryOverviewParam.getCarModel().isEmpty()) { carModelList1 = batteryMapper.getCarModelByHzModel(batteryOverviewParam.getCarModel()); if (carModelList1.size() > 0) { carModelList1.forEach(o -> { carModelList.addAll(Arrays.asList(o.split(","))); }); } } setBatteryOverviewParam(batteryOverviewParam); int total = batteryMapper.selectCount(new LambdaQueryWrapper() .select(Battery::getSn) .eq(Battery::getIsDelete, 0) .in(carModelList.size() > 0, Battery::getModel, carModelList) .in(!batteryOverviewParam.getPackModel().isEmpty(), Battery::getPackModelCode, batteryOverviewParam.getPackModel()) .in(!batteryOverviewParam.getCellModel().isEmpty(), Battery::getCellModelCode, batteryOverviewParam.getCellModel()) ); setBatteryStatistics(bsVo, batteryOverviewParam, carModelList, total); int count = Integer.parseInt(bsVo.getTotalBatteryCountVo().getCount().replaceAll(",", "")); // //装机总量指标 // TodayCompareOtherVo totalElectricQuantityVo = new TodayCompareOtherVo(); // totalElectricQuantityVo.setTitle("装机总能量(GWh)"); // totalElectricQuantityVo.setContent("统计所有电池的能量总和"); // setTotalElectricQuantityVo(totalElectricQuantityVo, batteryOverviewParam, carModelList); // bsVo.setTotalElectricQuantityVo(totalElectricQuantityVo); //当前报警电池总数 TodayCompareOtherVo currentBatteryFaultVo = new TodayCompareOtherVo(); currentBatteryFaultVo.setTitle("累计报警电池数(台)"); currentBatteryFaultVo.setPrompt("累计报警电池比例(%)"); currentBatteryFaultVo.setContent("截⽌昨⽇平台累计报警电池数及比例,比例计算方式:累计报警电池数/电池总量*100%"); setFaultAverageTodayVo(currentBatteryFaultVo, batteryOverviewParam, carModelList, BigDecimal.valueOf(count)); bsVo.setCurrentBatteryFaultVo(currentBatteryFaultVo); //上高压电池总量 TodayCompareOtherVo upperHighVoltageVo = new TodayCompareOtherVo(); setUpperHighVoltageVo(upperHighVoltageVo, batteryOverviewParam, BigDecimal.valueOf(count), carModelList); upperHighVoltageVo.setTitle("上高压电池数(台)"); upperHighVoltageVo.setPrompt("上高压电池比例(%)"); upperHighVoltageVo.setContent("车辆最后一条状态数据为上高压时的所有电池数及比例,比例计算方式:上高压电池数/电池总量*100%"); bsVo.setUpperHighVoltageVo(upperHighVoltageVo); //SOH>80%电池数量 TodayCompareOtherVo sohOverServerPercentVo = new TodayCompareOtherVo(); sohOverServerPercentVo.setTitle("SOH≥80%电池数(台)"); sohOverServerPercentVo.setPrompt("SOH≥80%电池比例(%)"); sohOverServerPercentVo.setContent("所有SOH大于80%的电池数及比例,比例计算方式:SOH>80%的电池数/电池总量*100%"); setSoh(sohOverServerPercentVo, batteryOverviewParam, BigDecimal.valueOf(count), carModelList); bsVo.setSohOverServerPercentVo(sohOverServerPercentVo); //运营车数量 TodayCompareOtherVo businessCarVo = new TodayCompareOtherVo(); businessCarVo.setTitle("运营车辆数(辆)"); businessCarVo.setPrompt("运营车辆比例(%)"); businessCarVo.setContent("当前运营车辆数及比例,比例计算方式:运营车辆数/电池总量*100%"); setBusinessVo(businessCarVo, batteryOverviewParam, BigDecimal.valueOf(count), carModelList); bsVo.setBusinessCarVo(businessCarVo); return bsVo; } private void setBatteryOverviewParam(BatteryOverviewParam batteryOverviewParam) { List ids = batteryOverviewParam.getBatteryModel(); if (!ids.isEmpty()) { List batteryModelList = batteryModelMapper.getBatteryModelListByIds(ids); List cellList = new ArrayList<>(); List packList = new ArrayList<>(); batteryModelList.forEach(o -> { cellList.add(o.getCellModel()); packList.add(o.getPackModel()); }); batteryOverviewParam.setCellModel(cellList); batteryOverviewParam.setPackModel(packList); } } /** * 运营车数量 * * @param bsVo 实体类 */ private void setBusinessVo(TodayCompareOtherVo bsVo, BatteryOverviewParam param, BigDecimal total, List carModelList) { bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //车型数据 String carModel = carModelList.size() > 0 ? "'" + String.join("','", carModelList) + "'" : null; long todayNum = 0L; try { todayNum = batteryMapper.getBusinessCount(carModel, param.getPackModel(), param.getCellModel()); } catch (Exception e) { } BigDecimal todayCount = BigDecimal.valueOf(todayNum); //当日数据提前准备 bsVo.setCount(DecimalFormat.getNumberInstance().format(todayCount)); bsVo.setYesterday(calculatePercent(todayCount, total)); } /** * 装机总能量 * * @param bsVo 参数 * @param param 参数 */ private void setTotalElectricQuantityVo(TodayCompareOtherVo bsVo, BatteryOverviewParam param, List carModelList) { SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd020000"); Date nowDate = new Date(System.currentTimeMillis()); Date yesDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); Date yessDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 2); String today = sf.format(nowDate); String todays = sf.format(yesDate); String lastWeek = DateUtil.getPreviousWeekSundayYes(yesDate); String lastWeeks = DateUtil.getPreviousWeekSundayYes(yessDate); String lastMonth = DateUtil.getLastMaxMonthDate(); lastWeek = lastWeek.replaceAll("-", ""); lastMonth = lastMonth.replaceAll("-", ""); List dateStrList = new ArrayList<>(); if (Long.valueOf(sdf.format(new Date())) > Long.valueOf(sdf2.format(new Date()))) { dateStrList.add(today); dateStrList.add(lastWeek); } else { dateStrList.add(todays); dateStrList.add(lastWeeks); } dateStrList.add(lastMonth); List voList = eqMapper.getSomeData(dateStrList); bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //当日数据提前准备 BigDecimal todayCount = BigDecimal.ZERO; for (ElectricQuantity bms : voList) { if (Long.valueOf(sdf.format(new Date())) > Long.valueOf(sdf2.format(new Date()))) { if (bms.getDateInfo().equals(today)) { JSONObject object = JSONObject.parseObject(bms.getDataJson()); if (carModelList.size() > 0) { final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(o -> { if (object.getBigDecimal(o) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(o)); } }); } todayCount = modelTotal[0]; } else { todayCount = new BigDecimal(object.get("total").toString()); } break; } } else { if (bms.getDateInfo().equals(todays)) { JSONObject object = JSONObject.parseObject(bms.getDataJson()); if (carModelList.size() > 0) { final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(o -> { if (object.getBigDecimal(o) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(o)); } }); } todayCount = modelTotal[0]; } else { todayCount = new BigDecimal(object.get("total").toString()); } break; } } } BigDecimal divide = todayCount.divide(BigDecimal.valueOf(1000000L), 2, RoundingMode.HALF_UP); bsVo.setCount(DecimalFormat.getNumberInstance().format(divide)); BigDecimal finalTodayCount = todayCount; String finalLastWeek = lastWeek; String finalLastMonth = lastMonth; voList.forEach(o -> { if (Long.valueOf(sdf.format(new Date())) > Long.valueOf(sdf2.format(new Date()))) { if (o.getDateInfo().equals(finalLastWeek)) { JSONObject object = JSONObject.parseObject(o.getDataJson()); BigDecimal week = BigDecimal.ZERO; if (!param.getCarModel().isEmpty()) { final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(om -> { if (object.getBigDecimal(om) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(om)); } }); } week = modelTotal[0]; } else { week = new BigDecimal(object.get("total").toString()); } bsVo.setWeek(calculateRate(finalTodayCount, week)); if (bsVo.getWeek() == null) { bsVo.setWeekFlag(null); } else { int res = setFlag(finalTodayCount, week); bsVo.setWeekFlag(res); } } } else { if (o.getDateInfo().equals(lastWeeks)) { JSONObject object = JSONObject.parseObject(o.getDataJson()); BigDecimal week = BigDecimal.ZERO; if (!param.getCarModel().isEmpty()) { final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(om -> { if (object.getBigDecimal(om) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(om)); } }); } week = modelTotal[0]; } else { week = new BigDecimal(object.get("total").toString()); } bsVo.setWeek(calculateRate(finalTodayCount, week)); if (bsVo.getWeek() == null) { bsVo.setWeekFlag(null); } else { int res = setFlag(finalTodayCount, week); bsVo.setWeekFlag(res); } } } if (o.getDateInfo().equals(finalLastMonth)) { BigDecimal mon = BigDecimal.ZERO; JSONObject object = JSONObject.parseObject(o.getDataJson()); if (!param.getCarModel().isEmpty()) { final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(om -> { if (object.getBigDecimal(om) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(om)); } }); } mon = modelTotal[0]; } else { mon = new BigDecimal(object.get("total").toString()); } bsVo.setMonth(calculateRate(finalTodayCount, mon)); if (bsVo.getMonth() == null) { bsVo.setMonthFlag(null); } else { int res = setFlag(finalTodayCount, mon); bsVo.setMonthFlag(res); } } }); } /** * 电池总量 * * @param bsVo 实体类 */ private void setTotalBatteryCountData(TodayCompareOtherVo bsVo, BatteryOverviewParam param, Integer type, List carModelList) { //车型数据 //当日 、昨日、上周、上月 字符串 Date yesDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 2); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); String yesterday = sf.format(yesDate); Date nowDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); String today = sf.format(nowDate); String lastWeek = DateUtil.getPreviousWeekSundayYes(nowDate); String lastMonth = DateUtil.getLastMaxMonthDateYes(); List dateStrList = new ArrayList<>(); dateStrList.add(yesterday); dateStrList.add(today); dateStrList.add(lastWeek); dateStrList.add(lastMonth); //找到了数据 List voList = new ArrayList<>(); switch (type) { case 0: voList = batteryMapper.getBatteryModelData(dateStrList); break; case 1: voList = batteryMapper.getAllDayChargeData(dateStrList); break; case 2: voList = batteryMapper.getDischargeData(dateStrList); break; case 3: voList = batteryMapper.getTotalMileage(dateStrList); break; default: } bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //当日数据提前准备 BigDecimal todayCount = BigDecimal.ZERO; for (BatteryModelStatistics bms : voList) { if (sf.format(bms.getTimeInfo()).contains(today)) { if (carModelList.size() > 0) { JSONObject object = JSONObject.parseObject(bms.getData()); final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(o -> { if (object.getBigDecimal(o) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(o)); } }); } todayCount = modelTotal[0]; //todayCount = object != null ? object.getBigDecimal(param.getCarModel()) : BigDecimal.ZERO; } else { todayCount = bms.getTotal(); } break; } } bsVo.setCount(DecimalFormat.getNumberInstance().format(todayCount == null ? 0 : todayCount)); BigDecimal finalTodayCount = todayCount; voList.forEach(o -> { if (sf.format(o.getTimeInfo()).contains(yesterday)) { BigDecimal yes = BigDecimal.ZERO; if (!param.getCarModel().isEmpty()) { JSONObject object = JSONObject.parseObject(o.getData()); //yes = object != null ? object.getBigDecimal(param.getCarModel()) : BigDecimal.ZERO; final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(om -> { if (object.getBigDecimal(om) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(om)); } }); } yes = modelTotal[0]; } else { yes = o.getTotal(); } bsVo.setYesterday(calculateRate(finalTodayCount, yes)); if (bsVo.getYesterday() == null) { bsVo.setYesterdayFlag(null); } else { int res = setFlag(finalTodayCount, yes); bsVo.setYesterdayFlag(res); } } if (sf.format(o.getTimeInfo()).contains(lastWeek)) { BigDecimal week = BigDecimal.ZERO; if (!param.getCarModel().isEmpty()) { JSONObject object = JSONObject.parseObject(o.getData()); final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(om -> { if (object.getBigDecimal(om) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(om)); } }); } week = modelTotal[0]; //week = object != null ? object.getBigDecimal(param.getCarModel()) : BigDecimal.ZERO; } else { week = o.getTotal(); } bsVo.setWeek(calculateRate(finalTodayCount, week)); if (bsVo.getWeek() == null) { bsVo.setWeekFlag(null); } else { int res = setFlag(finalTodayCount, week); bsVo.setWeekFlag(res); } } if (sf.format(o.getTimeInfo()).contains(lastMonth)) { BigDecimal mon = BigDecimal.ZERO; if (!param.getCarModel().isEmpty()) { JSONObject object = JSONObject.parseObject(o.getData()); final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(om -> { if (object.getBigDecimal(om) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(om)); } }); } mon = modelTotal[0]; //mon = object != null ? object.getBigDecimal(param.getCarModel()) : BigDecimal.ZERO; } else { mon = o.getTotal(); } bsVo.setMonth(calculateRate(finalTodayCount, mon)); if (bsVo.getMonth() == null) { bsVo.setMonthFlag(null); } else { int res = setFlag(finalTodayCount, mon); bsVo.setMonthFlag(res); } } }); } /** * 在线电池总量 * * @param bsVo 实体类 */ private void setOnLineBatteryData(TodayCompareOtherVo bsVo, BatteryOverviewParam param, BigDecimal total, List carModelList) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); String today = sf.format(new Date(System.currentTimeMillis() - 1000 * 24 * 60 * 60)); //找到了数据 BatteryModelStatistics vo = batteryMapper.getOnlineBatteryData(today); if (vo != null) { if (!param.getCarModel().isEmpty()) { JSONObject object = JSON.parseObject(vo.getData()); if (object != null) { final BigDecimal[] modelTotal = {BigDecimal.ZERO}; if (carModelList.size() > 0) { carModelList.forEach(o -> { if (object.getBigDecimal(o) != null) { modelTotal[0] = modelTotal[0].add(object.getBigDecimal(o)); } }); } vo.setTotal(modelTotal[0]); } } bsVo.setCount(vo.getTotal() != null ? String.valueOf(vo.getTotal()) : "0"); bsVo.setYesterday("0"); if (vo.getTotal() != null && total.compareTo(BigDecimal.ZERO) > 0) { BigDecimal percent = new BigDecimal(bsVo.getCount()).multiply(new BigDecimal(100)).divide(total, 2, RoundingMode.HALF_UP); bsVo.setYesterday(String.valueOf(percent)); } } } /** * 当前报警电池数 * * @param bsVo 实体类 */ private void setFaultAverageTodayVo(TodayCompareOtherVo bsVo, BatteryOverviewParam param, List carModelList, BigDecimal total) { //List batteryList = this.list(new LambdaQueryWrapper() // .select(Battery::getSn) // .in(carModelList.size() > 0, Battery::getModel, carModelList) // .eq(StringUtils.isNotBlank(param.getPackModel()), Battery::getPackModelCode, param.getPackModel()) // .eq(Battery::getIsDelete, 0)); //List collect = batteryList.stream().map(Battery::getSn).collect(Collectors.toList()); //找到了数据 //String carModel = carModelList.size() > 0 ? "'" + String.join("','", carModelList) + "'" : null; int fault = alarmMsgMapper.getAlarmSnCount(param.getPackModel(), param.getCellModel(), carModelList); bsVo.setCount(DecimalFormat.getNumberInstance().format(fault)); bsVo.setYesterday(calculatePercent(BigDecimal.valueOf(fault), total)); } /** * 上高压电池量 * * @param bsVo 实体类 */ private void setUpperHighVoltageVo(TodayCompareOtherVo bsVo, BatteryOverviewParam param, BigDecimal total, List carModelList) { if (!param.getCarModel().isEmpty()) { //找到了数据 int fault = batteryMapper.selectCount(new LambdaQueryWrapper() .eq(Battery::getUpperHighVoltageStatus, 1) .in(carModelList.size() > 0, Battery::getModel, carModelList) .isNotNull(Battery::getVin) .ne(Battery::getVin, "") .in(!param.getPackModel().isEmpty(), Battery::getPackModelCode, param.getPackModel()) .in(!param.getCellModel().isEmpty(), Battery::getCellModelCode, param.getCellModel()) .eq(Battery::getIsDelete, 0)); bsVo.setCount(String.valueOf(fault)); bsVo.setYesterday(calculatePercent(BigDecimal.valueOf(fault), total)); } else { int fault = batteryMapper.selectCount(new LambdaQueryWrapper() .eq(Battery::getUpperHighVoltageStatus, 1) .in(!param.getPackModel().isEmpty(), Battery::getPackModelCode, param.getPackModel()) .in(!param.getCellModel().isEmpty(), Battery::getCellModelCode, param.getCellModel()) .eq(Battery::getIsDelete, 0) .isNotNull(Battery::getVin) .ne(Battery::getVin, "") ); bsVo.setCount(DecimalFormat.getNumberInstance().format(fault)); bsVo.setYesterday(calculatePercent(BigDecimal.valueOf(fault), total)); } } /** * 判断增加还是减少 同比 1-上升 2-下降 3-持平 * * @param source 当前数据 * @param target 参照 * @return java.math.BigDecimal */ private Integer setFlag(BigDecimal source, BigDecimal target) { int result = 3; int res = source.compareTo(target); switch (res) { case 1: result = 1; break; case -1: result = 2; break; default: } return result; } /** * 计算对比率 * * @param source 当前数据 * @param target 参照 * @return java.math.BigDecimal */ private String calculateRate(BigDecimal source, BigDecimal target) { if (source == null || target == null) { return null; } if (target.equals(BigDecimal.ZERO)) { return "0"; } BigDecimal result = (source.subtract(target)).multiply(BigDecimal.valueOf(100)) .divide(target, 2, RoundingMode.HALF_UP); return String.valueOf(result.abs()); } /** * 计算占比 * * @param source 当前数据 * @param target 参照 * @return java.math.BigDecimal */ private String calculatePercent(BigDecimal source, BigDecimal target) { if (source == null || target == null) { return null; } if (target.equals(BigDecimal.ZERO)) { return "0"; } BigDecimal result = source.multiply(BigDecimal.valueOf(100)).divide(target, 2, RoundingMode.HALF_UP); return String.valueOf(result.abs()); } private List getDictDataByType(String dictType) { List dictDatas = DictUtils.getDictCache(dictType); if (com.hz.common.utils.StringUtils.isNotEmpty(dictDatas)) { return dictDatas; } dictDatas = dictDataMapper.selectDictDataByType(dictType); if (com.hz.common.utils.StringUtils.isNotEmpty(dictDatas)) { DictUtils.setDictCache(dictType, dictDatas); return dictDatas; } return null; } /** * 获取电池环状图信息 * * @return com.hz.business.vo.BatteryCycleDataVo */ @Override public BatteryCycleDataVo getBatteryCyclePercentList() { BatteryCycleDataVo vo = new BatteryCycleDataVo(); //电池类型占比 setBatteryTypePercentList(vo); //车型占比 setCarModelPercentList(vo); //SOH占比分布 setSohPercentList(vo); //BMS版本号分布 TODO bms数据缺失 没有数据 return vo; } /** * SOH占比 * * @param vo 参数 */ private void setSohPercentList(BatteryCycleDataVo vo) { List carModelPercentList = new ArrayList<>(); //soh最新信息 // List sohDataList = batteryMapper.getSohData(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd020000"); String dateStr = sdf.format(new Date()); String dateStrs = sdf.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)); List sohDataList = sohMapper.selectList(new LambdaQueryWrapper() .eq(SohItemQuantity::getDateInfo, Long.valueOf(sdf2.format(new Date())) > Long.valueOf(sdf3.format(new Date())) ? dateStr : dateStrs) .eq(SohItemQuantity::getIsDelete, 0)); if (sohDataList.size() > 0) { long total = sohDataList.stream().mapToLong(SohItemQuantity::getQuantity).sum(); sohDataList.forEach(o -> { BaseCycleChartVo v = new BaseCycleChartVo(); v.setName(o.getItem()); v.setCount(o.getQuantity()); if (total == 0) { v.setPercent(null); } else { v.setPercent(BigDecimal.valueOf(v.getCount() * 100).divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP)); } carModelPercentList.add(v); }); } vo.setSohPercentList(carModelPercentList); } /** * 车型占比 * * @param vo 参数 */ private void setCarModelPercentList(BatteryCycleDataVo vo) { List carModelPercentList = new ArrayList<>(); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd020000"); List batteryList = null; if (Long.parseLong(sdf2.format(new Date())) >= Long.parseLong(sdf3.format(new Date()))) { batteryList = batteryMapper.getHzCarModelCount(1); } else { batteryList = batteryMapper.getHzCarModelCount(2); } List hzCarModelList = batteryModelMapper.getHzCarModelList(); batteryList.forEach(o -> { hzCarModelList.forEach(v -> { if (v.getSModelCode().contains(o.getItem())) { o.setItem(v.getHzModelName()); } }); }); Map collect = batteryList.stream().collect(Collectors.groupingBy(Battery::getItem, Collectors.summingLong(Battery::getElectricQuantity))); if (!CollectionUtils.isEmpty(batteryList)) { long total = batteryList.stream().mapToLong(Battery::getElectricQuantity).sum(); batteryList.forEach(o -> { if (!StringUtils.isNotBlank(o.getItem())) { o.setItem("未知车型"); } }); collect.forEach((k, v) -> { BaseCycleChartVo cycleChartVo = new BaseCycleChartVo(); cycleChartVo.setName(k); cycleChartVo.setCount(v); if (total == 0) { cycleChartVo.setPercent(null); } else { cycleChartVo.setPercent(BigDecimal.valueOf(cycleChartVo.getCount() * 100).divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP)); } carModelPercentList.add(cycleChartVo); }); } vo.setCarModelPercentList(carModelPercentList); } /** * 电池类型占比 * * @param vo 父类 */ private void setBatteryTypePercentList(BatteryCycleDataVo vo) { // // "total":{"2101TZ" : 3, "2101TS" : 3, "2101TY" : 1} // BatteryModelStatistics bms = batteryMapper.getBatteryTypePercent(); // JSONObject totalObject = JSONObject.parseObject(bms.getData()).getJSONObject("total"); // Iterator iterator = totalObject.keySet().iterator(); // List batteryTypePercentList = new ArrayList<>(); // BigDecimal total = BigDecimal.ZERO; // List packCellList = new ArrayList<>(); // while (iterator.hasNext()) { // String key = iterator.next(); // String val = totalObject.getString(key); // BaseCycleChartVo bcVo = new BaseCycleChartVo(); // bcVo.setName(key); // if (!packCellList.contains(key.replace("_", ""))) { // packCellList.add(key.replace("_", "")); // } // bcVo.setCount(Long.parseLong(val)); // total = total.add(new BigDecimal(val)); // batteryTypePercentList.add(bcVo); // } // // List modelByPackAndCellModel = batteryModelMapper.getModelByPackAndCellModel(packCellList); // batteryTypePercentList.forEach(o -> { // if (!CollectionUtils.isEmpty(modelByPackAndCellModel)) { // modelByPackAndCellModel.forEach(m -> { // if (o.getName().replace("_", "").equals(m.getPackModel() + m.getCellModel())) { // o.setName(m.getBatteryModel()); // } // }); // } // }); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd020000"); List baseCycleChartVos = new ArrayList<>(); List maps = new ArrayList<>(); BigDecimal total = BigDecimal.ZERO; if (Long.parseLong(sdf2.format(new Date())) >= Long.parseLong(sdf3.format(new Date()))) { maps = batteryModelMapper.getBatteryModelLists(1); } else { maps = batteryModelMapper.getBatteryModelLists(2); } for (BatteryModelCountVo map : maps) { total = total.add(new BigDecimal(map.getItem())); } maps.forEach(item -> { BaseCycleChartVo baseCycleChartVo = new BaseCycleChartVo(); baseCycleChartVo.setName(item.getModel()); baseCycleChartVo.setCount(Math.round(item.getItem())); baseCycleChartVos.add(baseCycleChartVo); }); //计算百分比 if ((total.compareTo(BigDecimal.ZERO) != 0)) { if (!CollectionUtils.isEmpty(baseCycleChartVos)) { BigDecimal finalTotal = total; baseCycleChartVos.forEach(o -> { if (o.getCount() != null) { o.setPercent(BigDecimal.valueOf(o.getCount() * 100).divide(finalTotal, 2, RoundingMode.HALF_UP)); } }); } } vo.setBatteryTypePercentList(baseCycleChartVos); } /** * 获取电池故障类型日趋势信息 * * @return com.hz.business.base.BaseLineChartVo */ @Override public BaseLineChartVo getFaultTrend() { return null; } /** * 获取性能类实时指标信息 * * @return com.hz.business.vo.BatteryCycleDataVo */ @Override public PerformanceRealTimeVo getPerformanceRealTime() { return null; } /** * 收藏电池 * * @param dto 电池id * @return java.lang.String */ @Override public String doCollectBattery(BatteryFolderDto dto) { if (dto.getId() != null && dto.getIsDelete() != null && dto.getIsDelete() == 1) { BatteryFolder batteryFolder = batteryFolderMapper.selectById(dto.getId()); batteryFolder.setIsDelete(1); int insert = batteryFolderMapper.updateById(batteryFolder); if (insert <= 0) { return "操作失败"; } } else { String res = checkBatteryFolder(dto); if (!res.equals(Constants.OK)) { return res; } BatteryFolder batteryFolder = new BatteryFolder(); BeanUtils.copyProperties(dto, batteryFolder); batteryFolder.setFolderType(0); batteryFolder.setUserId(SecurityUtils.getUserId()); int insert = batteryFolderMapper.insert(batteryFolder); if (insert <= 0) { return "操作失败"; } } return Constants.OK; } /** * 校验收藏参数 * * @param dto * @return java.lang.String */ private String checkBatteryFolder(BatteryFolderDto dto) { if (dto.getBatteryId() == null) { return "缺失电池信息"; } if (dto.getFolderId() == null) { return "缺失收藏夹信息"; } Battery battery = this.getById(dto.getBatteryId()); if (battery == null) { return "电池信息不存在"; } int count = folderMapper.selectCount(new LambdaQueryWrapper() .eq(Folder::getUserId, SecurityUtils.getUserId()) .eq(Folder::getId, dto.getFolderId()) .eq(Folder::getIsDelete, 0)); if (count <= 0) { return "收藏夹不存在"; } count = batteryFolderMapper.selectCount(new LambdaQueryWrapper() .eq(BatteryFolder::getUserId, SecurityUtils.getUserId()) .eq(BatteryFolder::getBatteryId, dto.getBatteryId()) .eq(BatteryFolder::getIsDelete, 0)); if (count > 0) { return "已收藏,请勿重复收藏"; } return Constants.OK; } /** * 添加电池标签 * * @param tagDto 标签类 * @return java.lang.String */ @Override @Transactional public String batteryAddTag(TagDto tagDto) { BatteryTag batteryTag = new BatteryTag(); BeanUtils.copyProperties(tagDto, batteryTag); batteryTag.setTagType(0); return batteryTagMapper.insert(batteryTag) > 0 ? Constants.OK : "添加标签失败"; } /** * 修改电池标签 * * @param tagDto 标签类 * @return java.lang.String */ @Override public String batteryEditTag(TagDto tagDto) { BatteryTag batteryTag = batteryTagMapper.selectById(tagDto.getId()); BeanUtils.copyProperties(tagDto, batteryTag); batteryTag.setTagType(0); return batteryTagMapper.updateById(batteryTag) > 0 ? Constants.OK : "操作失败"; } /** * 修改电池标签 * * @param id 唯一标识 * @return java.lang.String */ @Override public String batteryDelTag(Long id) { return batteryTagMapper.deleteById(id) > 0 ? Constants.OK : "修改标签失败"; } /** * 查询电池历史故障 * * @param sn 电池编号 * @return java.util.List */ @Override public BatteryHistoryFaultVo getHistoryFault(String sn) { return null; } /** * 查询电池标签 * * @param param 电池id * @return java.util.List */ @Override public PageInfo batteryQueryTag(BatteryTagParam param) { PageHelper.startPage(param.getPageIndex(), param.getPageSize()); List batteryTagVoList = new ArrayList<>(); List batteryTags = batteryTagMapper.selectList(new LambdaQueryWrapper() .eq(BatteryTag::getBatteryId, param.getId()) .eq(BatteryTag::getTagType, 0) .eq(BatteryTag::getIsDelete, 0) .orderByDesc(BatteryTag::getUpdateTime)); PageInfo orderPageInfo = new PageInfo<>(batteryTags); //准备翻译 List tagList = new ArrayList<>(); List tagChildList = new ArrayList<>(); Set tagSet = new HashSet<>(); Set childTagSet = new HashSet<>(); orderPageInfo.getList().forEach(o -> { if (o.getTagId() != null) { tagSet.add(o.getTagId()); } if (StringUtils.isNotBlank(o.getChildTagList())) { String[] str = o.getChildTagList().split(","); List childList = Arrays.asList(str); childList.forEach(m -> childTagSet.add(Long.parseLong(m))); } }); if (tagSet.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(Tag::getId, tagSet); wp.eq(Tag::getIsDelete, 0); wp.select(Tag::getId, Tag::getTagName); tagList = tagMapper.selectList(wp); } if (childTagSet.size() > 0) { LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(TagChild::getId, childTagSet); wp.eq(TagChild::getIsDelete, 0); wp.select(TagChild::getId, TagChild::getName, TagChild::getParentId); tagChildList = tagChildMapper.selectList(wp); } List finalTagList = tagList; List finalTagChildList = tagChildList; orderPageInfo.getList().forEach(o -> { BatteryTagVo vo = new BatteryTagVo(); BeanUtils.copyProperties(o, vo); if (finalTagList.size() > 0) { finalTagList.forEach(m -> { if (o.getTagId() != null && m.getId().equals(o.getTagId())) { vo.setTagName(m.getTagName()); } }); } if (finalTagChildList.size() > 0) { List childList = new ArrayList<>(); finalTagChildList.forEach(m -> { if (o.getChildTagList() != null && o.getTagId() != null && m.getParentId() == o.getTagId().longValue() && o.getChildTagList().contains(String.valueOf(m.getId()))) { childList.add(m.getName()); } }); vo.setChildTagTextList(String.join(",", childList)); } batteryTagVoList.add(vo); }); PageInfo result = new PageInfo<>(batteryTagVoList); result.setTotal(orderPageInfo.getTotal()); return result; } /** * 查询电池标签 * * @param id 电池关联标签id * @return BatteryTagVo */ @Override public BatteryTagVo getBatteryTagDetail(Long id) { BatteryTagVo vo = new BatteryTagVo(); BatteryTag batteryTag = batteryTagMapper.selectById(id); if (batteryTag != null) { // BeanUtils.copyProperties(batteryTag, vo); //准备翻译 Tag tag = new Tag(); List tagChildList = new ArrayList<>(); String tagName = ""; Set childTagSet = new HashSet<>(); if (batteryTag.getTagId() != null) { tag = tagMapper.selectById(batteryTag.getTagId()); tagName = tag.getTagName(); } if (batteryTag.getChildTagList() != null) { String[] ids = batteryTag.getChildTagList().split(","); for (String str : ids) { childTagSet.add(Long.parseLong(str)); } LambdaQueryWrapper wp = new LambdaQueryWrapper<>(); wp.in(TagChild::getId, childTagSet); wp.eq(TagChild::getIsDelete, 0); wp.select(TagChild::getId, TagChild::getName, TagChild::getParentId); tagChildList = tagChildMapper.selectList(wp); } BeanUtils.copyProperties(batteryTag, vo); if (StringUtils.isNotBlank(tagName)) { vo.setTagName(tagName); } if (tagChildList.size() > 0) { List childList = new ArrayList<>(); tagChildList.forEach(m -> { if (batteryTag.getChildTagList() != null && batteryTag.getChildTagList().contains(String.valueOf(m.getId()))) { childList.add(m.getName()); } }); vo.setChildTagTextList(String.join(",", childList)); } } return vo; } /** * 电池安全诊断 * * @param sn 电池编号 * @return com.hz.business.vo.BatteryHistoryFaultVo */ @Override public BatteryHistoryFaultVo checkBattery(String sn) { return null; } /** * 电池列表准备工作 * * @return java.util.List */ @Override public List getTagBattery(Integer type) { return tagMapper.selectList(new LambdaQueryWrapper() .eq(Tag::getTagType, type) .eq(Tag::getIsDelete, 0)); } /** * 电池概览 * * @param param 参数 * @return java.util.List */ @Override public BatteryOverviewVo getBatteryOverview(BatteryOverviewParam param) { return null; } /** * 我的故障收藏 * * @param param 我的故障收藏 * @return java.util.List */ @Override public PageInfo getMyCollectData(BatteryFolderParam param) { if (param.getFolderId() == null) { return new PageInfo<>(); } PageHelper.startPage(param.getPageIndex(), param.getPageSize()); List batteryTagVoList = new ArrayList<>(); //查询 List batteryFolders = batteryFolderMapper.selectList(new LambdaQueryWrapper() .ge(param.getStartTime() != null, BatteryFolder::getCreateTime, param.getStartTime() + " 00:00:00") .le(param.getEndTime() != null, BatteryFolder::getCreateTime, param.getEndTime() + " 23:59:59") .and(null != param.getSearchKey(), p -> p.like(BatteryFolder::getSn, param.getSearchKey()) .or().like(BatteryFolder::getVin, param.getSearchKey())) .eq(BatteryFolder::getFolderType, 0) .eq(BatteryFolder::getUserId, SecurityUtils.getUserId()) .eq(param.getFolderId() != null, BatteryFolder::getFolderId, param.getFolderId()) .eq(BatteryFolder::getIsDelete, 0)); PageInfo orderPageInfo = new PageInfo<>(batteryFolders); //准备翻译 orderPageInfo.getList().forEach(o -> { BatteryFolderVo vo = new BatteryFolderVo(); BeanUtils.copyProperties(o, vo); vo.setCollectionTime(o.getCreateTime()); batteryTagVoList.add(vo); }); PageInfo result = new PageInfo<>(batteryTagVoList); result.setTotal(orderPageInfo.getTotal()); return result; } /** * 获取SOH里程分布图 * * @return java.util.List */ @Override public List getSohMileage() { List sohMileageVoList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd020000"); String dateStr = sdf.format(new Date()); String dateStrs = sdf.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)); List sohOdoList = sohOdoMapper.selectList(new LambdaQueryWrapper() .eq(SohOdo::getDateInfo, Long.valueOf(sdf2.format(new Date())) > Long.valueOf(sdf3.format(new Date())) ? dateStr : dateStrs) .eq(SohOdo::getIsDelete, 0)); //List> mapList = batteryMapper.getSohMileageData(); if (!CollectionUtils.isEmpty(sohOdoList)) { sohMileageVoList = JSONArray.parseArray(sohOdoList.get(0).getData(), SohMileageVo.class); } return sohMileageVoList; } /** * 查询电池详细信息chart * * @param param 参数 * @return 电池信息 */ @Override public BatteryDetailChartVo getDetailCharts(BatteryDetailChartParam param) throws ParseException, SQLException { BatteryDetailChartVo vo = new BatteryDetailChartVo(); List flinkDataList = getFlinkData(param); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //时间轴 List timeList = flinkDataList.stream().map(o -> sdf.format(o.getTime())).collect(Collectors.toList()); //最高电压 List maxVoltageList = new ArrayList<>(); /*List maxVoltageList = flinkDataList.stream() .map(o -> (o.getCellMaxVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxVol() / 1000) .collect(Collectors.toList());*/ //最低电压 List minVoltageList = new ArrayList<>(); /*List minVoltageList = flinkDataList.stream() .map(o -> (o.getCellMinVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinVol() / 1000) .collect(Collectors.toList());*/ //最高温度 List cellMaxTempList = new ArrayList<>(); /*List cellMaxTempList = flinkDataList.stream() .map(o -> (o.getCellMaxTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxTemp()) .collect(Collectors.toList());*/ //最低温度 List cellMinTempList = new ArrayList<>(); /*List cellMinTempList = flinkDataList.stream() .map(o -> (o.getCellMinTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinTemp()) .collect(Collectors.toList());*/ //总电压 List packVoltageList = flinkDataList.stream() .map(o -> (o.getPackVoltage().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackVoltage()) .collect(Collectors.toList()); //总电流 List packCrntList = flinkDataList.stream() .map(o -> (o.getPackCrnt().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackCrnt()) .collect(Collectors.toList()); //SOC List packSocList = flinkDataList.stream() .map(o -> (o.getPackSoc().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackSoc()) .collect(Collectors.toList()); //绝缘电阻 List insulationRssList = flinkDataList.stream() .map(o -> (o.getInsulationRss().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getInsulationRss()) .collect(Collectors.toList()); //压差 List voltageDifferenceList = new ArrayList<>(); /*List voltageDifferenceList = flinkDataList.stream() .map(p -> p.getBmsCellVoltDiff().floatValue()) .collect(Collectors.toList());*/ //车速 List vehSpdList = flinkDataList.stream() .map(o -> (o.getVehSpd() == null || o.getVehSpd().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getVehSpd()) .collect(Collectors.toList()); //单体电压 List voltDiffList = flinkDataList.stream() .map(FlinkData::getCellVoltage) .collect(Collectors.toList()); //单体温度 List batTempDiffList = flinkDataList.stream() .map(o -> (o.getCellTemp().replaceAll(String.valueOf(Constants.BATTERY_ERROR_CODE), "null"))) .collect(Collectors.toList()); //if (maxVoltageList.size() <= 0 && minVoltageList.size() <= 0 && voltageDifferenceList.size() <= 0 && voltDiffList.size() > 0) { if (voltDiffList.size() > 0) { for (String s : voltDiffList) { List listTemp = Arrays.asList(s.split(",")); List list = listTemp.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (list.size() > 0) { String max = list.stream().max(Comparator.comparing(Float::parseFloat)).get(); String min = list.stream().min(Comparator.comparing(Float::parseFloat)).get(); Float maxFloat = Float.parseFloat(max); Float minFloat = Float.parseFloat(min); maxVoltageList.add(maxFloat); minVoltageList.add(minFloat); voltageDifferenceList.add(Float.valueOf(String.format("%.2f", (maxFloat - minFloat) * 1000))); } } } //if (cellMaxTempList.size() <= 0 && cellMinTempList.size() <= 0 && batTempDiffList.size() > 0) { if (batTempDiffList.size() > 0) { for (String s : batTempDiffList) { List listTemp = Arrays.asList(s.split(",")); List list = listTemp.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (list.size() > 0) { String max = list.stream().max(Comparator.comparing(Float::parseFloat)).get(); String min = list.stream().min(Comparator.comparing(Float::parseFloat)).get(); Float maxFloat = Float.parseFloat(max); Float minFloat = Float.parseFloat(min); cellMaxTempList.add(maxFloat); cellMinTempList.add(minFloat); } } } List> bmsCellVoltDiffList = new ArrayList<>(); if (voltDiffList.size() > 0) { for (int i = 0; i < voltDiffList.size(); i++) { if (StringUtils.isNotBlank(voltDiffList.get(i))) { String[] split = voltDiffList.get(i).trim().split(","); int len = split.length; for (int j = 0; j < len; j++) { if (bmsCellVoltDiffList.size() <= j) { bmsCellVoltDiffList.add(new ArrayList<>()); } float value = Float.parseFloat(StringUtils.isNotBlank(split[j]) ? split[j] : "0"); bmsCellVoltDiffList.get(j).add((value == Constants.BATTERY_ERROR_CODE) ? null : value); } } } } List> bmsBatTempDiffList = new ArrayList<>(); if (batTempDiffList.size() > 0) { for (int i = 0; i < batTempDiffList.size(); i++) { if (StringUtils.isNotBlank(batTempDiffList.get(i))) { String[] split = batTempDiffList.get(i).trim().split(","); int len = split.length; for (int j = 0; j < len; j++) { if (bmsBatTempDiffList.size() <= j) { bmsBatTempDiffList.add(new ArrayList<>()); } float value = Float.parseFloat(StringUtils.isNotBlank(split[j]) ? split[j] : "0"); bmsBatTempDiffList.get(j).add((value == Constants.BATTERY_ERROR_CODE) ? null : value); } } } } //补充空值 int maxVoltageSize = 0; for (List list : bmsCellVoltDiffList) { if (list.size() > maxVoltageSize) { maxVoltageSize = list.size(); } } for (List list : bmsCellVoltDiffList) { while (list.size() < maxVoltageSize) { list.add(null); } } int maxTemSize = 0; for (List list : bmsBatTempDiffList) { if (list.size() > maxTemSize) { maxTemSize = list.size(); } } for (List list : bmsBatTempDiffList) { while (list.size() < maxTemSize) { list.add(null); } } vo.setTimeList(timeList); vo.setMaxVoltageList(maxVoltageList); vo.setMinVoltageList(minVoltageList); vo.setCellMaxTempList(cellMaxTempList); vo.setCellMinTempList(cellMinTempList); vo.setPackVoltageList(packVoltageList); vo.setPackCrntList(packCrntList); vo.setPackSocList(packSocList); vo.setInsulationRssList(insulationRssList); vo.setVoltageDifferenceList(voltageDifferenceList); vo.setBmsCellVoltDiffList(bmsCellVoltDiffList); vo.setBmsBatTempDiffList(bmsBatTempDiffList); vo.setVehSpdList(vehSpdList); return vo; } /** * 获取flink数据 * * @param param 参数 * @return java.util.List */ private List getFlinkData(BatteryDetailChartParam param) throws ParseException, SQLException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder builder = new StringBuilder(); //SnKey =sn的hashCode 绝对值 + sn + long最大值减去时间戳 String snKey = Math.abs(param.getSn().hashCode()) + "_" + param.getSn(); long timeStamp = Long.MAX_VALUE; // CellMaxVol,CellMinVol,CellMaxTemp,CellMinTemp,BmsCellVoltDiff,VehSpd builder.append("select SN,Time,PackVoltage,PackCrnt,PackSoc,CellVoltage,CellTemp,InsulationRss,Info from ") .append(database + "." + tableName).append(" where "); if (param.getStartTime() == null && param.getEndTime() == null) { long start = System.currentTimeMillis() - 1000 * 24 * 60 * 60; long end = System.currentTimeMillis(); String snKeyStart = snKey + "_" + (timeStamp - start); builder.append(" SnKey<='").append(snKeyStart).append("'"); String snKeyEnd = snKey + "_" + (timeStamp - end); builder.append(" and SnKey>='").append(snKeyEnd).append("'"); } else { if (param.getStartTime() != null) { long start = sdf.parse(param.getStartTime()).getTime(); String snKeyStart = snKey + "_" + (timeStamp - start); builder.append(" SnKey<='").append(snKeyStart).append("'"); } if (param.getEndTime() != null) { long end = sdf.parse(param.getEndTime()).getTime(); String snKeyEnd = snKey + "_" + (timeStamp - end); if (param.getStartTime() != null) { builder.append(" and "); } builder.append(" SnKey>='").append(snKeyEnd).append("'"); } } builder.append(" limit 2000"); List flinkDataList = new ArrayList<>(); Connection conn = null; PreparedStatement psSelect = null; try { conn = PhoenixUtils.getConnection(); //psSelect = conn.prepareStatement(" use " + database + " "); //psSelect.setFetchSize(1000); //psSelect.execute(); //psSelect.close(); psSelect = conn.prepareStatement(builder.toString()); ResultSet resultSet = psSelect.executeQuery(); flinkDataList = convertList(resultSet); } catch (Exception e) { } finally { if (psSelect != null) { psSelect.close(); } if (conn != null) { conn.close(); } } List flinkList = flinkDataList.stream() .sorted(Comparator.comparing(FlinkData::getTime)) .collect(Collectors.toList()); log.info("OK:{}", sdf.format(new Date())); return flinkList; } /** * 获取上个月份的最后一天 * * @return */ public static Date lastMonthEndDay() { Calendar instance = Calendar.getInstance(); // 调整日期到当月第一天 instance.set(Calendar.DAY_OF_MONTH, 1); // 再把日期减去一天即可 instance.add(Calendar.DAY_OF_MONTH, -1); return instance.getTime(); } /** * 电池总量 * * @param bsVo 实体类 */ private void setSoh(TodayCompareOtherVo bsVo, BatteryOverviewParam param, BigDecimal total, List carModelList) { bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //车型数据 //当日 、上周、上月 字符串 SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); String today = sf.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)) + " 23:59:59"; //找到了数据 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); String partNow = "p" + sdf.format(new Date()); String partBefore = "p" + sdf.format(lastMonthEndDay()); String partitions = partNow + "," + partBefore; String carModel = carModelList.size() > 0 ? "'" + String.join("','", carModelList) + "'" : null; int todayNum = batteryMapper.getSohCount(carModel, today, partitions, param.getPackModel(), param.getPackModel()); BigDecimal todayCount = new BigDecimal(0); if (total.compareTo(new BigDecimal(0)) != 0) { todayCount = total.subtract(BigDecimal.valueOf(todayNum)); } //当日数据提前准备 bsVo.setCount(DecimalFormat.getNumberInstance().format(todayCount)); bsVo.setYesterday(calculatePercent(todayCount, total)); } /** * 电池健康度诊断--健康度趋势图 * * @param param 参数 * @return com.hz.business.base.DateValueVo */ @Override public BatteryHealthVo getHealthResult(BatteryHealthParam param) throws ParseException { BatteryHealthVo vo = new BatteryHealthVo(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long stamp = System.currentTimeMillis(); String begin = sf.format(stamp) + " 00:00:00"; String end = sf.format(stamp) + " 23:59:59"; //计算查询时间内的分区的范围 if (param.getStartTime() == null && param.getEndTime() == null) { Date yesDate = new Date(stamp - 1000 * 60 * 60 * 24 * 7); begin = sf.format(yesDate) + " 00:00:00"; end = sf.format(stamp) + " 23:59:59"; } else { begin = sf.format(sdf.parse(param.getStartTime() + " 00:00:00")); end = sf.format(sdf.parse(param.getEndTime() + " 23:59:59")); } //获取时间段内的分区 String partitions = getPartitions(begin, end); HealthScore srVo = batteryMapper.getCurrentHealthScore(param.getSn()); //当前健康度评分 if (srVo != null && srVo.getHealthState() != null) { //当前健康度评分 vo.setCurrentHealthScore(srVo.getHealthState()); //性能诊断 vo.setDiagnosticResult(srVo.getReason()); } List healthScoreList = batteryMapper.getHistoryHealthScore(param.getSn(), begin, end, partitions); List healthScoreOverview = new ArrayList<>(); if (!CollectionUtils.isEmpty(healthScoreList)) { healthScoreList.forEach(o -> { DateValueVo v = new DateValueVo(); v.setXValue(o.getTime()); v.setYValue(o.getHealthState()); healthScoreOverview.add(v); }); } //健康度评分趋势图 vo.setHealthScoreOverview(healthScoreOverview); //诊断结果 List diagnosticVoList = setDiagnosticVoList(param.getSn()); List collect = diagnosticVoList.stream().sorted(Comparator.comparing(DiagnosticVo::getCollectionTime).reversed()).collect(Collectors.toList()); vo.setDiagnosticVoList(collect); //SOH趋势图 setSohLineChartVo(vo, param.getSn(), partitions, begin, end); //内阻一致性 setResistanceChartVoList(vo, param.getSn(), partitions, begin, end); //SOH一致性 setSohDiffVoList(vo, param.getSn(), partitions, begin, end); //SOC一致性 setSocChartVoList(vo, param.getSn(), partitions, begin, end); //温度一致性 setTemperatureChartVoList(vo, param.getSn(), partitions, begin, end); //电池健康度衰减趋势 setHealthReduceOverview(vo, param.getSn()); return vo; } private void setHealthReduceOverview(BatteryHealthVo vo, String sn) { //横轴公里数列表 List odoList = new ArrayList<>(); //当前电池健康度 List singleList = batteryMapper.getHistoryHealthScoreReduce(sn); //odo排序 singleList = singleList.stream().sorted(Comparator.comparing(Battery::getTimeSt)).collect(Collectors.toList()); for (int i = 0; i < singleList.size(); i++) { if (i > 1) { BigDecimal b1 = BigDecimal.valueOf(singleList.get(i).getOdo() - singleList.get(i - 1).getOdo()); BigDecimal b2 = BigDecimal.valueOf(Double.parseDouble(String.valueOf(singleList.get(i).getTimeSt().getTime() / (1000 * 60 * 60 * 24) - singleList.get(i - 1).getTimeSt().getTime() / (1000 * 60 * 60 * 24)))); if (b1.compareTo(new BigDecimal(0)) != 0 && b2.compareTo(new BigDecimal(0)) != 0) { if (b1.divide(b2, 1, RoundingMode.UP).compareTo(new BigDecimal("400.0")) > 0) { singleList.remove(i); i--; } } } } //同种车型电池soh和odo信息 StringBuilder builder = new StringBuilder(); for (int i = 1; i < 60; i++) { builder.append(" WHEN odo >= ").append(5000 * i).append(" AND odo < ").append(5000 * (i + 1)) .append(" THEN '").append(5000 * i).append("~").append(5000 * (i + 1)).append("KM").append("' \n "); } List modelList = batteryMapper.getCarModelSoh(sn, builder.toString()); //odo排序 modelList = modelList.stream().sorted(Comparator.comparing(Battery::getOdo)).collect(Collectors.toList()); for (int i = 0; i < modelList.size(); i++) { if (i > 1) { if (modelList.get(i).getOdo() - modelList.get(i - 1).getOdo() > 50000 && modelList.get(i).getSoh() - modelList.get(i - 1).getSoh() > 5) { if (modelList.get(i).getSoh() - modelList.get(i - 1).getSoh() > 5) { modelList.remove(i); i--; } } } } // if(battery!=null){ // modelList.remove(battery); // } List allBatteryList = new ArrayList<>(); if (singleList.size() > 0) { singleList.forEach(o -> { allBatteryList.add(new BigDecimal(o.getOdo())); }); List list = singleList.stream().map(o -> new BigDecimal(o.getOdo()).setScale(1, RoundingMode.HALF_UP)).collect(Collectors.toList()); if (list.size() > 0) { //添加横轴数据 odoList.addAll(list); } } if (modelList.size() > 0) { modelList.forEach(o -> { allBatteryList.add(new BigDecimal(o.getOdo())); }); List list1 = modelList.stream().map(o -> new BigDecimal(o.getOdo()).setScale(1, RoundingMode.HALF_UP)).collect(Collectors.toList()); if (list1.size() > 0) { //添加横轴数据 odoList.addAll(list1); } } //排序 Collections.sort(odoList); //排序 Collections.sort(allBatteryList); //返回值装配 BaseLineChartOdoVo baseLineChartOdoVo = new BaseLineChartOdoVo(); //横轴 baseLineChartOdoVo.setHorizontalAxis(odoList); //纵轴 List kindList = new ArrayList<>(); //本车电池soh KindFloatValueListVo kindValueVo = new KindFloatValueListVo(); kindValueVo.setName("电池soh"); //本车型电池平均soh KindFloatValueListVo kindValueVo1 = new KindFloatValueListVo(); kindValueVo1.setName("车型电池平均soh"); List singleSohList = new ArrayList<>(); List modelSohList = new ArrayList<>(); if (allBatteryList.size() > 0) { for (BigDecimal o : allBatteryList) { BigDecimal singleSoh = null; for (Battery m : singleList) { if (o.equals(new BigDecimal(m.getOdo()))) { singleSoh = new BigDecimal(m.getSoh()).setScale(2, RoundingMode.HALF_UP); break; } } singleSohList.add(singleSoh); } for (BigDecimal o : allBatteryList) { BigDecimal modelSoh = null; for (Battery m : modelList) { if (o.equals(new BigDecimal(m.getOdo()))) { modelSoh = new BigDecimal(m.getSoh()).setScale(2, RoundingMode.HALF_UP); break; } } modelSohList.add(modelSoh); } } kindValueVo.setValue(singleSohList); kindList.add(kindValueVo); kindValueVo1.setValue(modelSohList); kindList.add(kindValueVo1); baseLineChartOdoVo.setKindList(kindList); //返回给前端 vo.setHealthReduceOverview(baseLineChartOdoVo); } private void setSohLineChartVo(BatteryHealthVo vo, String sn, String partitions, String begin, String end) { BaseLineFloatChartVo v = new BaseLineFloatChartVo(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List sohDiffList = batteryMapper.getSohLineChartVo(sn, begin, end, partitions); if (!CollectionUtils.isEmpty(sohDiffList)) { //时间轴 List timeList = sohDiffList.stream().map(o -> sdf.format(o.getCollectionTime())).collect(Collectors.toList()); //soh String[] split = sohDiffList.get(0).getCoreListStr().split(","); int len = split.length; Map> map = new HashMap>(); for (int i = 0; i < len; i++) { map.put("cell-" + i, new ArrayList()); } for (int i = 0; i < sohDiffList.size(); i++) { List list = Arrays.asList(sohDiffList.get(i).getCoreListStr().replaceAll("[\\[|\\]]", "").split(",")); if (!CollectionUtils.isEmpty(list)) { for (int j = 0; j < list.size(); j++) { map.get("cell-" + j).add(list.get(j) == null ? BigDecimal.ZERO : new BigDecimal(list.get(j).replace(" ", ""))); } } } List valueListVos = new ArrayList<>(); if (map.keySet().size() > 0) { for (int i = 0; i < map.size(); i++) { int finalIndex = i; map.forEach((key, value) -> { if (key.equals("cell-" + finalIndex)) { KindFloatValueListVo vk = new KindFloatValueListVo(); vk.setName(key); vk.setValue(value); valueListVos.add(vk); } }); } } v.setTimeAxis(timeList); v.setKindList(valueListVos); } vo.setSohLineChartVo(v); } /** * 获取分区段 * * @param begin 开始日期 * @param end 截止日期 * @return java.lang.String */ private String getPartitions(String begin, String end) { //2020-01-01 2020-03-25 ===》 p202001,p202001p202002,p202003 String partitions = ""; List tempList = new ArrayList<>(); //填充时间段内的所有分区 Set months = DateUtils.getMonths(begin, end); if (!CollectionUtils.isEmpty(months)) { months.forEach(o -> { tempList.add("p" + o); }); partitions = String.join(",", tempList); } return partitions; } /** * 内阻一致性 * * @param vo 电池信息对象 * @param sn 电池编号 * @param partitions 分区列表 * @param begin 开始时间 * @param end 截止时间 */ private void setResistanceChartVoList(BatteryHealthVo vo, String sn, String partitions, String begin, String end) { List healthScoreList = batteryMapper.setResistanceChartVoList(sn, begin, end, partitions); List sohDiffList = new ArrayList<>(); if (!CollectionUtils.isEmpty(healthScoreList)) { healthScoreList.forEach(o -> { DateValueVo v = new DateValueVo(); v.setXValue(o.getCollectionTime()); v.setYValue(o.getResult()); sohDiffList.add(v); }); } vo.setResistanceChartVoList(sohDiffList); } /** * soh一致性 * * @param vo 电池信息对象 * @param sn 电池编号 * @param partitions 分区列表 * @param begin 开始时间 * @param end 截止时间 */ private void setSohDiffVoList(BatteryHealthVo vo, String sn, String partitions, String begin, String end) { List healthScoreList = batteryMapper.setSohDiffVoList(sn, begin, end, partitions); List sohDiffList = new ArrayList<>(); if (!CollectionUtils.isEmpty(healthScoreList)) { healthScoreList.forEach(o -> { DateValueVo v = new DateValueVo(); v.setXValue(o.getCollectionTime()); v.setYValue(o.getResult()); sohDiffList.add(v); }); } vo.setSohChartVoList(sohDiffList); } /** * soc一致性 * * @param vo 电池信息对象 * @param sn 电池编号 * @param partitions 分区列表 * @param begin 开始时间 * @param end 截止时间 */ private void setSocChartVoList(BatteryHealthVo vo, String sn, String partitions, String begin, String end) { List healthScoreList = batteryMapper.setSocChartVoList(sn, begin, end, partitions); List sohDiffList = new ArrayList<>(); if (!CollectionUtils.isEmpty(healthScoreList)) { healthScoreList.forEach(o -> { DateValueVo v = new DateValueVo(); v.setXValue(o.getCollectionTime()); v.setYValue(o.getResult()); sohDiffList.add(v); }); } vo.setSocChartVoList(sohDiffList); } /** * 温度一致性 * * @param vo 电池信息对象 * @param sn 电池编号 * @param partitions 分区列表 * @param begin 开始时间 * @param end 截止时间 */ private void setTemperatureChartVoList(BatteryHealthVo vo, String sn, String partitions, String begin, String end) { List healthScoreList = batteryMapper.setTemperatureChartVoList(sn, begin, end, partitions); List sohDiffList = new ArrayList<>(); if (!CollectionUtils.isEmpty(healthScoreList)) { healthScoreList.forEach(o -> { DateValueVo v = new DateValueVo(); v.setXValue(o.getCollectionTime()); v.setYValue(o.getResult()); sohDiffList.add(v); }); } vo.setTemperatureChartVoList(sohDiffList); } /** * 获取一致性数据 * * @return java.util.List */ private List setDiagnosticVoList(String sn) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); String partNow = "p" + sdf.format(new Date()); String partBefore = "p" + sdf.format(lastMonthEndDay()); List diagnosticVoList = new ArrayList<>(); //algo_soh —— cellsoh_diff soh List sohDiffList = batteryMapper.getSohDiff(sn, null, null, partNow, partBefore); if (!CollectionUtils.isEmpty(sohDiffList)) { DiagnosticVo sohDiff = new DiagnosticVo(); sohDiff.setProject(UniformityEnum.SOH_DIFF.message()); sohDiff.setReferenceValue("0~10%"); sohDiff.setOrder(1); sohDiff.setResult(String.valueOf(sohDiffList.get(0).getResult() + "%")); sohDiff.setCollectionTime(sohDiffList.get(0).getCollectionTime()); diagnosticVoList.add(sohDiff); } List sohList = batteryMapper.getSoh(sn, null, null, partNow, partBefore); if (!CollectionUtils.isEmpty(sohList)) { DiagnosticVo soh = new DiagnosticVo(); soh.setResult(String.valueOf(sohList.get(0).getResult() + "%")); soh.setCollectionTime(sohList.get(0).getCollectionTime()); soh.setProject(UniformityEnum.SOH.message()); soh.setReferenceValue("80%~100%"); soh.setOrder(0); diagnosticVoList.add(soh); } //algo_mid_sorout——sor_diff List sorList = batteryMapper.getSorDiff(sn, null, null, partNow, partBefore); if (!CollectionUtils.isEmpty(sorList)) { DiagnosticVo sor = new DiagnosticVo(); sor.setResult(String.valueOf(sorList.get(0).getResult() + "mΩ")); sor.setCollectionTime(sorList.get(0).getCollectionTime()); sor.setProject(UniformityEnum.SOR.message()); sor.setReferenceValue("0~2mΩ"); sor.setOrder(2); diagnosticVoList.add(sor); } //algo_mid_uniform_result——cellsoc_diff celltemp_diff List socList = batteryMapper.getSocDiff(sn, null, null, partNow, partBefore); if (!CollectionUtils.isEmpty(socList)) { DiagnosticVo soc = new DiagnosticVo(); soc.setResult(String.valueOf(socList.get(0).getResult() + "%")); soc.setCollectionTime(socList.get(0).getCollectionTime()); soc.setProject(UniformityEnum.SOC.message()); soc.setReferenceValue("0~15%"); soc.setOrder(3); diagnosticVoList.add(soc); } List tempList = batteryMapper.getTempDiff(sn, null, null, partNow, partBefore); if (!CollectionUtils.isEmpty(tempList)) { DiagnosticVo temp = new DiagnosticVo(); temp.setResult(String.valueOf(tempList.get(0).getResult() + "℃")); temp.setCollectionTime(tempList.get(0).getCollectionTime()); temp.setProject(UniformityEnum.TEMP_DIFF.message()); temp.setReferenceValue("0~15℃"); temp.setOrder(4); diagnosticVoList.add(temp); } return diagnosticVoList; } private static List convertList(ResultSet rs) { List flinkDataList = new ArrayList(); try { List> mapList = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } if (rowData.containsKey("Info")) { rowData.putAll(ResultSetToJson.info2Map(rowData.get("Info").toString())); } mapList.add(rowData); } flinkDataList = JSONArray.parseArray(JSON.toJSONString(mapList), FlinkData.class); } catch (Exception e) { } return flinkDataList; } /** * 导出电池详情数据 * * @param param 参数 */ @Override public void exportDetailExcel(BatteryDetailChartParam param, HttpServletResponse response) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //最高电压 List maxVoltageList = new ArrayList<>(); //最低电压 List minVoltageList = new ArrayList<>(); //最高温度 List cellMaxTempList = new ArrayList<>(); //最低温度 List cellMinTempList = new ArrayList<>(); //总电压 List packVoltageList = new ArrayList<>(); //总电流 List packCrntList = new ArrayList<>(); //压差 List voltageDifferenceList = new ArrayList<>(); //SOC List packSocList = new ArrayList<>(); //单体电压 List voltVoList = new ArrayList<>(); //单体温度 List tempVoList = new ArrayList<>(); //绝缘电阻 List insulationRssDiffList = new ArrayList<>(); List> indexList = new ArrayList<>(); List> headVoltList = new ArrayList<>(); List> headTempList = new ArrayList<>(); List> cellVoltObjectDiff = new ArrayList<>(); List> batTempObjectDiff = new ArrayList<>(); List sheetNames = new ArrayList<>(); sheetNames.add("最高电压"); sheetNames.add("最低电压"); sheetNames.add("最高温度"); sheetNames.add("最低温度"); sheetNames.add("总电压"); sheetNames.add("总电流"); sheetNames.add("压差"); sheetNames.add("SOC"); sheetNames.add("单体电压"); sheetNames.add("单体温度"); sheetNames.add("绝缘电阻"); // 输出流 OutputStream outputStream = null; String fileFinalPath = HzConfig.getUploadPath() + File.separator + param.getVin() + ".xlsx"; File file = new File(fileFinalPath); outputStream = new FileOutputStream(fileFinalPath); int lenTemp = 0; int lenVolt = 0; // 导出的数据 List flinkDataList = getFlinkData(param); if (!CollectionUtils.isEmpty(flinkDataList)) { flinkDataList.forEach(o -> { String timeStr = sdf.format(o.getTime()); //总电压 BaseExportExcelVo packVoltage = new BaseExportExcelVo(); packVoltage.setTime(timeStr); packVoltage.setQuantity(o.getPackVoltage().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getPackVoltage())); packVoltageList.add(packVoltage); //总电流 BaseExportExcelVo packCrnt = new BaseExportExcelVo(); packCrnt.setTime(timeStr); packCrnt.setQuantity(o.getPackCrnt().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getPackCrnt())); packCrntList.add(packCrnt); //SOC BaseExportExcelVo packSoc = new BaseExportExcelVo(); packSoc.setTime(timeStr); packSoc.setQuantity(o.getPackSoc().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getPackSoc())); packSocList.add(packSoc); //绝缘电阻 BaseExportExcelVo insulationRssDiff = new BaseExportExcelVo(); insulationRssDiff.setTime(timeStr); insulationRssDiff.setQuantity(o.getInsulationRss().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getInsulationRss())); insulationRssDiffList.add(insulationRssDiff); //单体电压 BaseExportExcelStringVo baseVoltExportExcelStringVo = new BaseExportExcelStringVo(); baseVoltExportExcelStringVo.setTime(timeStr); baseVoltExportExcelStringVo.setData(o.getCellVoltage()); voltVoList.add(baseVoltExportExcelStringVo); //单体温度 BaseExportExcelStringVo baseTempExportExcelStringVo = new BaseExportExcelStringVo(); baseTempExportExcelStringVo.setTime(timeStr); baseTempExportExcelStringVo.setData(o.getCellTemp()); tempVoList.add(baseTempExportExcelStringVo); //最高/最低电压 压差 BaseExportExcelVo voltageDifference = new BaseExportExcelVo(); BaseExportExcelVo maxVoltage = new BaseExportExcelVo(); BaseExportExcelVo minVoltage = new BaseExportExcelVo(); minVoltage.setTime(timeStr); maxVoltage.setTime(timeStr); voltageDifference.setTime(timeStr); if (StringUtils.isNotBlank(o.getCellVoltage())) { List listTemp = Arrays.asList(o.getCellVoltage().split(",")); List list = listTemp.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (list.size() > 0) { String max = list.stream().max(Comparator.comparing(Float::parseFloat)).get(); String min = list.stream().min(Comparator.comparing(Float::parseFloat)).get(); maxVoltage.setQuantity(new BigDecimal(max)); minVoltage.setQuantity(new BigDecimal(min)); voltageDifference.setQuantity(maxVoltage.getQuantity().subtract(minVoltage.getQuantity())); } } maxVoltageList.add(maxVoltage); minVoltageList.add(minVoltage); voltageDifferenceList.add(voltageDifference); //最高/最低温度 BaseExportExcelVo cellMaxTemp = new BaseExportExcelVo(); cellMaxTemp.setTime(timeStr); BaseExportExcelVo cellMinTemp = new BaseExportExcelVo(); cellMinTemp.setTime(timeStr); if (StringUtils.isNotBlank(o.getCellTemp())) { List listTemp = Arrays.asList(o.getCellTemp().split(",")); List list = listTemp.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (list.size() > 0) { String max = list.stream().max(Comparator.comparing(Float::parseFloat)).get(); String min = list.stream().min(Comparator.comparing(Float::parseFloat)).get(); cellMaxTemp.setQuantity(new BigDecimal(max)); cellMinTemp.setQuantity(new BigDecimal(min)); } } cellMaxTempList.add(cellMaxTemp); cellMinTempList.add(cellMinTemp); }); if (voltVoList.size() > 0) { voltVoList.forEach(o -> { String[] split = (o.getTime() + "," + o.getData()).split(","); List result = Arrays.asList(split); cellVoltObjectDiff.add(result); }); String[] split = voltVoList.get(0).getData().trim().split(","); lenVolt = split.length; } if (tempVoList.size() > 0) { tempVoList.forEach(o -> { String[] split = (o.getTime() + "," + o.getData()).split(","); List result = Arrays.asList(split); batTempObjectDiff.add(result); }); String[] split = tempVoList.get(0).getData().trim().split(","); lenTemp = split.length; } } List timeList = Arrays.asList("日期时间"); headVoltList.add(timeList); headTempList.add(timeList); for (int i = 1; i <= lenVolt; i++) { List cellHeadList = Arrays.asList("cell-" + i); headVoltList.add(cellHeadList); } for (int i = 1; i <= lenTemp; i++) { List cellHeadList = Arrays.asList("cell-" + i); headTempList.add(cellHeadList); } indexList.add(maxVoltageList); indexList.add(minVoltageList); indexList.add(cellMaxTempList); indexList.add(cellMinTempList); indexList.add(packVoltageList); indexList.add(packCrntList); indexList.add(voltageDifferenceList); indexList.add(packSocList); indexList.add(cellVoltObjectDiff); indexList.add(batTempObjectDiff); indexList.add(insulationRssDiffList); // 多sheel导出 ExcelWriter excelWriter = EasyExcel.write(outputStream, BaseExportExcelVo.class).excelType(ExcelTypeEnum.XLSX).build(); for (int i = 0; i < sheetNames.size(); i++) { WriteSheet writeSheet; if ("单体电压".equals(sheetNames.get(i))) { writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)) .head(headVoltList) .build(); } else if ("单体温度".equals(sheetNames.get(i))) { writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)) .head(headTempList) .build(); } else { writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)).registerWriteHandler(new CustomerTitleHandler(sheetNames.get(i))).build(); } excelWriter.write(indexList.get(i), writeSheet); } excelWriter.finish(); //文件上传到阿里云 //String aliYunFilePath = aliyunOSSUtil.upload(file); //String fileSource = propertyConfig.getOssDomain() + "/" + aliYunFilePath; //FileOutputStream stream = new FileOutputStream(fileSource); /*boolean del = file.delete(); if (!del) { log.warn("本地文件删除失败"); }*/ this.export2File(file, response); } private void export2File(File file, HttpServletResponse response) throws IOException { InputStream fis = null; try { fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + file.getName()); response.addHeader("Content-Length", "" + file.length()); response.setContentType("application/vnd.ms-excel"); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); outputStream.write(buffer); outputStream.flush(); outputStream.close(); file.delete(); } catch (Exception e) { log.error("文件导出报错: {}", e.getMessage(), e); } finally { if (fis != null) { fis.close(); } } } /** * 导出电池详情数据 * * @param param 参数 */ @Override public void exportHealthExcel(BatteryDetailChartParam param, HttpServletResponse response) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //健康度评分趋势图 List healthScoreOverviewList = new ArrayList<>(); //内阻一致性 List resistanceChartVoList = new ArrayList<>(); //SOH一致性 List sohDiffVoList = new ArrayList<>(); //SOC一致性 List socChartVoList = new ArrayList<>(); //温度一致性 List temperatureChartVoList = new ArrayList<>(); //SOH趋势图 List sohLineChartVoList = new ArrayList<>(); BatteryHealthVo vo = new BatteryHealthVo(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); long stamp = System.currentTimeMillis(); String begin = sf.format(stamp) + " 00:00:00"; String end = sf.format(stamp) + " 23:59:59"; //计算查询时间内的分区的范围 if (param.getStartTime() == null && param.getEndTime() == null) { Date yesDate = new Date(stamp - 1000 * 60 * 60 * 24 * 7); begin = sf.format(yesDate) + " 00:00:00"; end = sf.format(stamp) + " 23:59:59"; } else { begin = sf.format(sdf.parse(param.getStartTime() + " 00:00:00")); end = sf.format(sdf.parse(param.getEndTime() + " 23:59:59")); } //获取时间段内的分区 String partitions = getPartitions(begin, end); List healthScoreList = batteryMapper.getHistoryHealthScore(param.getSn(), begin, end, partitions); List healthScoreOverview = new ArrayList<>(); if (!CollectionUtils.isEmpty(healthScoreList)) { healthScoreList.forEach(o -> { DateValueVo v = new DateValueVo(); v.setXValue(o.getTime()); v.setYValue(o.getHealthState()); healthScoreOverview.add(v); }); } //健康度评分趋势图 vo.setHealthScoreOverview(healthScoreOverview); //健康度评分趋势图 if (!CollectionUtils.isEmpty(healthScoreOverview)) { healthScoreOverview.forEach(o -> { BaseExportExcelVo v = new BaseExportExcelVo(); v.setTime(sdf.format(o.getXValue())); v.setQuantity(o.getYValue()); healthScoreOverviewList.add(v); }); } //SOH趋势图 //SOH趋势图 setSohLineChartVo(vo, param.getSn(), partitions, begin, end); if (!CollectionUtils.isEmpty(vo.getSohLineChartVo().getKindList())) { vo.getSohLineChartVo().getKindList().forEach(o -> { BaseExportExcelStringVo v = new BaseExportExcelStringVo(); v.setData(o.getValue().toString()); sohLineChartVoList.add(v); }); for (int i = 0; i < sohLineChartVoList.size(); i++) { sohLineChartVoList.get(i).setTime(vo.getSohLineChartVo().getTimeAxis().get(i)); } } //内阻一致性 setResistanceChartVoList(vo, param.getSn(), partitions, begin, end); if (!CollectionUtils.isEmpty(vo.getResistanceChartVoList())) { vo.getResistanceChartVoList().forEach(o -> { BaseExportExcelVo v = new BaseExportExcelVo(); v.setTime(sdf.format(o.getXValue())); v.setQuantity(o.getYValue()); resistanceChartVoList.add(v); }); } //SOH一致性 setSohDiffVoList(vo, param.getSn(), partitions, begin, end); if (!CollectionUtils.isEmpty(vo.getSohChartVoList())) { vo.getSohChartVoList().forEach(o -> { BaseExportExcelVo v = new BaseExportExcelVo(); v.setTime(sdf.format(o.getXValue())); v.setQuantity(o.getYValue()); sohDiffVoList.add(v); }); } //SOC一致性 setSocChartVoList(vo, param.getSn(), partitions, begin, end); if (!CollectionUtils.isEmpty(vo.getSocChartVoList())) { vo.getSocChartVoList().forEach(o -> { BaseExportExcelVo v = new BaseExportExcelVo(); v.setTime(sdf.format(o.getXValue())); v.setQuantity(o.getYValue()); socChartVoList.add(v); }); } //温度一致性 setTemperatureChartVoList(vo, param.getSn(), partitions, begin, end); if (!CollectionUtils.isEmpty(vo.getTemperatureChartVoList())) { vo.getTemperatureChartVoList().forEach(o -> { BaseExportExcelVo v = new BaseExportExcelVo(); v.setTime(sdf.format(o.getXValue())); v.setQuantity(o.getYValue()); temperatureChartVoList.add(v); }); } // 输出流 OutputStream outputStream = null; String fileFinalPath = HzConfig.getUploadPath() + File.separator + param.getSn() + ".xlsx"; File file = new File(fileFinalPath); outputStream = new FileOutputStream(file); // 多sheel导出 ExcelWriter excelWriter = EasyExcel.write(outputStream).build(); WriteSheet test5 = EasyExcel.writerSheet(0, "SOH趋势图").head(BaseExportExcelStringVo.class).build(); WriteSheet test6 = EasyExcel.writerSheet(1, "内阻一致性").head(BaseExportExcelVo.class).build(); WriteSheet test7 = EasyExcel.writerSheet(2, "SOH一致性").head(BaseExportExcelVo.class).build(); WriteSheet test8 = EasyExcel.writerSheet(3, "SOC一致性").head(BaseExportExcelVo.class).build(); WriteSheet test9 = EasyExcel.writerSheet(4, "温度一致性").head(BaseExportExcelVo.class).build(); excelWriter.write(healthScoreOverviewList, test5) .write(resistanceChartVoList, test6) .write(sohDiffVoList, test7) .write(socChartVoList, test8) .write(temperatureChartVoList, test9); excelWriter.finish(); this.export2File(file, response); } /** * 查询电池实时位置统计信息 * * @return 电池信息 */ @Override public List getBatteryLocation() { List list = batteryMapper.getBatteryLocation(); List res = new ArrayList<>(); Integer count = 0; for (Battery battery : list) { count += battery.getCount(); } for (Battery battery : list) { BatteryLocationVo batteryLocationVo = new BatteryLocationVo(); BeanUtils.copyProperties(battery, batteryLocationVo); batteryLocationVo.setCount(battery.getCount()); batteryLocationVo.setProvince(StrUtils.getProvince(battery.getProvince())); batteryLocationVo.setPercentage(count != 0 ? BigDecimal.valueOf(battery.getCount().floatValue() / count.floatValue()).setScale(4, RoundingMode.HALF_UP).toString() : "0.0000"); res.add(batteryLocationVo); } res.sort(Comparator.comparing(BatteryLocationVo::getCount).reversed()); return res; } /** * 查询电池实时位置统计信息 * * @return 电池信息 */ @Override public List getBatteryChargingLocation() { List list = batteryMapper.getBatteryChargingLocation(); List res = new ArrayList<>(); Integer count = 0; for (Battery battery : list) { count += battery.getCount(); } for (Battery battery : list) { BatteryLocationVo batteryLocationVo = new BatteryLocationVo(); BeanUtils.copyProperties(battery, batteryLocationVo); batteryLocationVo.setCount(battery.getCount()); batteryLocationVo.setChargingProvince(StrUtils.getProvince(battery.getChargingProvince())); batteryLocationVo.setPercentage(count != 0 ? BigDecimal.valueOf(battery.getCount().floatValue() / count.floatValue()).setScale(4, RoundingMode.HALF_UP).toString() : "0.0000"); res.add(batteryLocationVo); } res.sort(Comparator.comparing(BatteryLocationVo::getCount).reversed()); return res; } /** * 查询电池详细信息-用电行为 * * @param param 参数 * @return 电池信息 */ @Override public BatteryDetailChartVo getDetailCharge(BatteryDetailChartParam param) throws ParseException, SQLException { BatteryDetailChartVo vo = new BatteryDetailChartVo(); List flinkDataList = getFlinkData(param); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //时间轴 List timeList = flinkDataList.stream().map(o -> sdf.format(o.getTime())).collect(Collectors.toList()); //单体压差 List bmsCellVoltDiffList = new ArrayList<>(); /*List bmsCellVoltDiffList = flinkDataList.stream() .map(o -> (o.getBmsCellVoltDiff().floatValue() == Constants.BATTERY_ERROR_CODE) ? null : o.getBmsCellVoltDiff().floatValue()) .collect(Collectors.toList());*/ //电池包Soc List packSocList = flinkDataList.stream() .map(o -> (o.getPackSoc().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackSoc()) .collect(Collectors.toList()); //电芯最高温度 List cellMaxTempList = new ArrayList<>(); /*List cellMaxTempList = flinkDataList.stream() .map(o -> (o.getCellMaxTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxTemp()) .collect(Collectors.toList());*/ //电芯最低温度 List cellMinTempList = new ArrayList<>(); /*List cellMinTempList = flinkDataList.stream() .map(o -> (o.getCellMinTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinTemp()) .collect(Collectors.toList());*/ //最高电压 List maxVoltList = new ArrayList<>(); /*List maxVoltList = flinkDataList.stream() .map(o -> (o.getCellMaxVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxVol() / 1000) .collect(Collectors.toList());*/ //最低电压 List minVoltList = new ArrayList<>(); /*List minVoltList = flinkDataList.stream() .map(o -> (o.getCellMinVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinVol() / 1000) .collect(Collectors.toList());*/ //电池整包电压 List packVoltageList = flinkDataList.stream() .map(o -> (o.getPackVoltage().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackVoltage()) .collect(Collectors.toList()); //电池包输出电流 List packCrntList = flinkDataList.stream() .map(o -> (o.getPackCrnt() == null || o.getPackCrnt().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackCrnt()) .collect(Collectors.toList()); //车速 List vehSpdList = flinkDataList.stream() .map(o -> (o.getVehSpd() == null || o.getVehSpd().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getVehSpd()) .collect(Collectors.toList()); //单体电压 List voltDiffList = flinkDataList.stream() .map(FlinkData::getCellVoltage) .collect(Collectors.toList()); //单体电压 List tempDiffList = flinkDataList.stream() .map(FlinkData::getCellTemp) .collect(Collectors.toList()); if (voltDiffList.size() > 0) { for (String s : voltDiffList) { List listTemp = Arrays.asList(s.split(",")); List list = listTemp.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (list.size() > 0) { String max = list.stream().max(Comparator.comparing(Float::parseFloat)).get(); String min = list.stream().min(Comparator.comparing(Float::parseFloat)).get(); Float maxFloat = Float.parseFloat(max); Float minFloat = Float.parseFloat(min); maxVoltList.add(maxFloat); minVoltList.add(minFloat); bmsCellVoltDiffList.add(maxFloat - minFloat); } } } //if (cellMaxTempList.size() <= 0 && cellMinTempList.size() <= 0 && batTempDiffList.size() > 0) { if (tempDiffList.size() > 0) { for (String s : tempDiffList) { List listTemp = Arrays.asList(s.split(",")); List list = listTemp.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (list.size() > 0) { String max = list.stream().max(Comparator.comparing(Float::parseFloat)).get(); String min = list.stream().min(Comparator.comparing(Float::parseFloat)).get(); Float maxFloat = Float.parseFloat(max); Float minFloat = Float.parseFloat(min); cellMaxTempList.add(maxFloat); cellMinTempList.add(minFloat); } } } List> bmsCellVoltList = new ArrayList<>(); if (voltDiffList.size() > 0) { for (int i = 0; i < voltDiffList.size(); i++) { if (StringUtils.isNotBlank(voltDiffList.get(i))) { String[] split = voltDiffList.get(i).trim().split(","); int len = split.length; for (int j = 0; j < len; j++) { if (bmsCellVoltList.size() <= j) { bmsCellVoltList.add(new ArrayList<>()); } float value = Float.parseFloat(StringUtils.isNotBlank(split[j]) ? split[j] : "0"); bmsCellVoltList.get(j).add((value == Constants.BATTERY_ERROR_CODE) ? null : value); } } } } //补充空值 int maxVoltageSize = 0; for (List list : bmsCellVoltList) { if (list.size() > maxVoltageSize) { maxVoltageSize = list.size(); } } for (List list : bmsCellVoltList) { while (list.size() < maxVoltageSize) { list.add(null); } } vo.setTimeList(timeList); vo.setCellMaxTempList(cellMaxTempList); vo.setCellMinTempList(cellMinTempList); vo.setPackVoltageList(packVoltageList); vo.setPackCrntList(packCrntList); vo.setPackSocList(packSocList); vo.setVehSpdList(vehSpdList); vo.setMaxVoltageList(maxVoltList); vo.setMinVoltageList(minVoltList); vo.setVoltageDifferenceList(bmsCellVoltDiffList); vo.setBmsCellVoltDiffList(bmsCellVoltList); return vo; } /** * 导出电池详情数据-用电行为 * * @param param 参数 */ @Override public void exportDetailChargeExcel(BatteryDetailChartParam param, HttpServletResponse response) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //最高电压 List maxVoltageList = new ArrayList<>(); //最低电压 List minVoltageList = new ArrayList<>(); //最高温度 List cellMaxTempList = new ArrayList<>(); //最低温度 List cellMinTempList = new ArrayList<>(); //总电压 List packVoltageList = new ArrayList<>(); //总电流 List packCrntList = new ArrayList<>(); //压差 List voltageDifferenceList = new ArrayList<>(); //SOC List packSocList = new ArrayList<>(); //单体电压 List voltVoList = new ArrayList<>(); //绝缘电阻 List vehSpdList = new ArrayList<>(); List> indexList = new ArrayList<>(); List> headVoltList = new ArrayList<>(); List> cellVoltObjectDiff = new ArrayList<>(); // 输出流 OutputStream outputStream = null; List flinkDataList = null; String fileFinalPath = HzConfig.getUploadPath() + File.separator + param.getVin() + ".xlsx"; File file = new File(fileFinalPath); try { outputStream = new FileOutputStream(file); int lenTemp = 0; int lenVolt = 0; // 导出的数据 flinkDataList = getFlinkData(param); if (!CollectionUtils.isEmpty(flinkDataList)) { flinkDataList.forEach(o -> { String timeStr = sdf.format(o.getTime()); //最高电压 BaseExportExcelVo maxVoltage = new BaseExportExcelVo(); maxVoltage.setTime(timeStr); maxVoltage.setQuantity(o.getCellMaxVol().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getCellMaxVol() / 1000)); maxVoltageList.add(maxVoltage); //最低电压 BaseExportExcelVo minVoltag = new BaseExportExcelVo(); minVoltag.setTime(timeStr); minVoltag.setQuantity(o.getCellMinVol().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getCellMinVol() / 1000)); minVoltageList.add(minVoltag); //最高温度 BaseExportExcelVo cellMaxTemp = new BaseExportExcelVo(); cellMaxTemp.setTime(timeStr); cellMaxTemp.setQuantity(o.getCellMaxTemp().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getCellMaxTemp())); cellMaxTempList.add(cellMaxTemp); //最低温度 BaseExportExcelVo cellMinTemp = new BaseExportExcelVo(); cellMinTemp.setTime(timeStr); cellMinTemp.setQuantity(o.getCellMinTemp().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getCellMinTemp())); cellMinTempList.add(cellMinTemp); //总电压 BaseExportExcelVo packVoltage = new BaseExportExcelVo(); packVoltage.setTime(timeStr); packVoltage.setQuantity(o.getPackVoltage().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getPackVoltage())); packVoltageList.add(packVoltage); //总电流 BaseExportExcelVo packCrnt = new BaseExportExcelVo(); packCrnt.setTime(timeStr); packCrnt.setQuantity(o.getPackCrnt().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getPackCrnt())); packCrntList.add(packCrnt); //SOC BaseExportExcelVo packSoc = new BaseExportExcelVo(); packSoc.setTime(timeStr); packSoc.setQuantity(o.getPackSoc().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getPackSoc())); packSocList.add(packSoc); //压差 BaseExportExcelVo voltageDifference = new BaseExportExcelVo(); voltageDifference.setTime(timeStr); voltageDifference.setQuantity(o.getBmsCellVoltDiff().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getBmsCellVoltDiff())); voltageDifferenceList.add(voltageDifference); //车速 BaseExportExcelVo vehSpdVo = new BaseExportExcelVo(); vehSpdVo.setTime(timeStr); vehSpdVo.setQuantity(o.getVehSpd() == null || o.getVehSpd().equals(Constants.BATTERY_ERROR_CODE) ? null : BigDecimal.valueOf(o.getVehSpd())); vehSpdList.add(vehSpdVo); //单体电压 BaseExportExcelStringVo baseVoltExportExcelStringVo = new BaseExportExcelStringVo(); baseVoltExportExcelStringVo.setTime(timeStr); baseVoltExportExcelStringVo.setData(o.getCellVoltage()); voltVoList.add(baseVoltExportExcelStringVo); }); if (voltVoList.size() > 0) { voltVoList.forEach(o -> { String[] split = (o.getTime() + "," + o.getData()).split(","); List result = Arrays.asList(split); cellVoltObjectDiff.add(result); }); String[] split = voltVoList.get(0).getData().trim().split(","); lenVolt = split.length; } } List timeList = Arrays.asList("日期时间"); headVoltList.add(timeList); for (int i = 1; i <= lenVolt; i++) { List cellHeadList = Arrays.asList("cell-" + i); headVoltList.add(cellHeadList); } // 多sheel导出 List sheetNames = new ArrayList<>(); sheetNames.add("最高电压"); sheetNames.add("最低电压"); sheetNames.add("最高温度"); sheetNames.add("最低温度"); sheetNames.add("总电压"); sheetNames.add("总电流"); sheetNames.add("压差"); sheetNames.add("SOC"); sheetNames.add("单体电压"); sheetNames.add("车速"); indexList.add(maxVoltageList); indexList.add(minVoltageList); indexList.add(cellMaxTempList); indexList.add(cellMinTempList); indexList.add(packVoltageList); indexList.add(packCrntList); indexList.add(voltageDifferenceList); indexList.add(packSocList); indexList.add(cellVoltObjectDiff); indexList.add(vehSpdList); ExcelWriter excelWriter = EasyExcel.write(outputStream, BaseExportExcelVo.class).excelType(ExcelTypeEnum.XLSX).build(); for (int i = 0; i < sheetNames.size(); i++) { WriteSheet writeSheet; if ("单体电压".equals(sheetNames.get(i))) { writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)) .head(headVoltList) .build(); } else { writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)).registerWriteHandler(new CustomerTitleHandler(sheetNames.get(i))).build(); } excelWriter.write(indexList.get(i), writeSheet); } excelWriter.finish(); this.export2File(file, response); } catch (FileNotFoundException | ParseException | SQLException e) { throw new RuntimeException(e); } finally { if (outputStream != null) { outputStream.close(); } } } /** * 用电行为分析 * * @param vin 参数 * @return List */ @Override public BehaviorAnalysisVo getBehaviorAnalysis(String vin) throws SQLException { BehaviorAnalysisVo vo = new BehaviorAnalysisVo(); List carPowerVoList = getCarPowerFlinkData(vin); //计算最后一次放电详情 setLastCycleChartVo(carPowerVoList, vo); //计算历史用电分布 vo.setHistoryCycleChartVoList(getCycleChartList(carPowerVoList)); return vo; } /** * 计算最后一次放电详情 * * @param carPowerVoList 数据 * @param vo 参数 */ private void setLastCycleChartVo(List carPowerVoList, BehaviorAnalysisVo vo) { List lastCycleChartVoList = new ArrayList<>(); if (!CollectionUtils.isEmpty(carPowerVoList)) { List voList = new ArrayList<>(); if (carPowerVoList.get(0).getStsFlg() == 1) { //最后一次数据是放电 for (CarPowerVo carPowerVo : carPowerVoList) { if (carPowerVo.getStsFlg() == 0) { break; } else { voList.add(carPowerVo); } } } else { //最后一次数据是充电,找到上一次充电和本次充电之间的数据 for (int i = 1; i < carPowerVoList.size(); i++) { if (carPowerVoList.get(i).getStsFlg() == 0) { break; } else { voList.add(carPowerVoList.get(i)); } } } if (voList.size() > 0) { lastCycleChartVoList = getCycleChartList(voList); } } else { lastCycleChartVoList = getCycleChartList(new ArrayList<>()); } vo.setLastCycleChartVoList(lastCycleChartVoList); } /** * 除了动力驱动和PTC热管理 其他均为0 * * @param voList 参数 * @return List */ private List getCycleChartList(List voList) { List cycleChartVoList = new ArrayList<>(); //精确两位有效数字 DecimalFormat decimalFormat = new DecimalFormat("0.00"); double drive = voList.stream().filter(o -> o.getStsFlg() == 1).mapToDouble(CarPowerVo::getDrvEngy).sum(); double ptc = voList.stream().filter(o -> o.getStsFlg() == 1).mapToDouble(CarPowerVo::getPtcEngy).sum(); double total = voList.stream().filter(o -> o.getStsFlg() == 1).mapToDouble(CarPowerVo::getVehEngy).sum(); PowerConsumeTypeEnum[] enums = PowerConsumeTypeEnum.values(); for (PowerConsumeTypeEnum en : enums) { //除了动力驱动和PTC热管理 其他均为0 BaseCycleChartFloatVo baseCycleChartVo = new BaseCycleChartFloatVo(); baseCycleChartVo.setName(en.message()); if (en.code() == 0) { BigDecimal percent = total != 0 ? BigDecimal.valueOf(drive).divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; baseCycleChartVo.setPercent(percent); baseCycleChartVo.setCount(Double.parseDouble(decimalFormat.format(drive))); } else if (en.code() == 1) { BigDecimal percent = total != 0 ? BigDecimal.valueOf(ptc).divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; baseCycleChartVo.setPercent(percent); baseCycleChartVo.setCount(Double.parseDouble(decimalFormat.format(ptc))); } else { baseCycleChartVo.setPercent(BigDecimal.ZERO); baseCycleChartVo.setCount(0d); } cycleChartVoList.add(baseCycleChartVo); } return cycleChartVoList; } /** * 获取flink数据 * * @param vin 参数 * @return java.util.List */ private List getCarPowerFlinkData(String vin) throws SQLException { List carPowerVoList = new ArrayList<>(); Connection conn = null; PreparedStatement psSelect = null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder builder = new StringBuilder(); String snKey = Math.abs(vin.hashCode()) + "_" + vin + "_"; String snKeyMin = snKey + "0"; String snKeyMax = snKey + "a"; builder.append("select * from ").append(behaviorTable) .append(" where id >= '").append(snKeyMin) .append("' and id <= '").append(snKeyMax).append("' order by id"); conn = PhoenixUtils.getConnection(); psSelect = conn.prepareStatement(" use " + database + " "); psSelect.setFetchSize(1000); psSelect.execute(); psSelect.close(); psSelect = conn.prepareStatement(builder.toString()); ResultSet resultSet = psSelect.executeQuery(); carPowerVoList = convertCarPowerVoList(resultSet); } catch (Exception e) { } finally { if (psSelect != null) { psSelect.close(); } if (conn != null) { conn.close(); } } return carPowerVoList; } public List> getFlinkMapList(String tableName, String resultId) throws SQLException { List> mapList = new ArrayList<>(); Connection conn = null; PreparedStatement psSelect = null; try { StringBuilder builder = new StringBuilder(); //SnKey = resultId的hashCode 绝对值 + resultId + long最大值 String snKey = Math.abs(resultId.hashCode()) + "_" + resultId + "_"; String snKeyMin = snKey + "0"; String snKeyMax = snKey + "a"; builder.append("select id,remain_odo from ").append(database + "." + tableName); builder.append(" where id > '").append(snKeyMin).append("' and id < '") .append(snKeyMax).append("'"); builder.append(" order by id limit 1 "); conn = PhoenixUtils.getConnection(); psSelect = conn.prepareStatement(builder.toString()); ResultSet resultSet = psSelect.executeQuery(); mapList = ResultSetToJson.toListMap(resultSet, false); } catch (Exception e) { } finally { if (psSelect != null) { psSelect.close(); } if (conn != null) { conn.close(); } } return mapList; } /** * lindrom数据转换为实体类 * * @param rs 参数 * @return java.util.List */ private static List convertCarPowerVoList(ResultSet rs) { List carPowerVoList = new ArrayList(); try { List> mapList = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } mapList.add(rowData); } carPowerVoList = JSONArray.parseArray(JSON.toJSONString(mapList), CarPowerVo.class); /*//按照结束时间倒序排列 List flinkList = carPowerVoList.stream() .sorted(Comparator.comparing(CarPowerVo::getTimeSp).reversed()) .collect(Collectors.toList());*/ } catch (Exception e) { } return carPowerVoList; } /** * 每日计算装机总量 */ @Transactional(rollbackFor = Exception.class) @Override public void calTotalElectricQuantity() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dateStr = sdf.format(new Date()); ElectricQuantity one = eqMapper.selectOne(new QueryWrapper() .select("date_info") .last(" limit 1 ") .orderByDesc("id") .eq("is_delete", 0)); if (one == null || (one.getDateInfo() != null && !one.getDateInfo().equals(dateStr))) { //计算当日装机总量 List> mapList = batteryMapper.calTotalElectricQuantity(); if (mapList.size() > 0) { List list = JSONArray.parseArray(JSON.toJSONString(mapList), QuantityItemVo.class); BigDecimal total = BigDecimal.ZERO; if (list.size() > 0) { total = list.stream() .map(QuantityItemVo::getQuantity) .reduce(BigDecimal.ZERO, BigDecimal::add); } QuantityItemVo vo = new QuantityItemVo(); vo.setQuantity(total); vo.setItem("total"); list.add(vo); //保存数据 if (list.size() > 0) { JSONObject object = new JSONObject(); list.forEach(o -> { object.put(o.getItem(), o.getQuantity()); }); ElectricQuantity entity = new ElectricQuantity(); entity.setDateInfo(dateStr); entity.setDataJson(object.toJSONString()); eqMapper.insert(entity); } } } KilometreCount kilometreCount = kilometreCountMapper.selectOne(new QueryWrapper() .select("date_info") .last("limit 1") .orderByDesc("id") .eq("is_delete", 0)); if (kilometreCount == null || (kilometreCount.getDateInfo() != null && !kilometreCount.getDateInfo().equals(dateStr))) { List kilometreCountVo = alarmMsgMapper.getKilometreCountVo(); if (kilometreCountVo.size() > 0) { kilometreCountVo.forEach(o -> { KilometreCount entity = new KilometreCount(); entity.setDateInfo(dateStr); entity.setKilometre(o.getKilometre()); entity.setName(o.getName()); entity.setRankOrder(o.getRankOrder()); kilometreCountMapper.insert(entity); }); } } // //计算soh占比 // SohItemQuantity sohItemQuantity = sohMapper.selectOne(new QueryWrapper() // .select("date_info") // .last(" limit 1 ") // .orderByDesc("id") // .eq("is_delete", 0)); // SimpleDateFormat sdff = new SimpleDateFormat("yyyyMM"); // String partNow = "p" + sdff.format(new Date()); // String partBefore = "p" + sdff.format(lastMonthEndDay()); // String partitions = partNow + "," + partBefore; // if (sohItemQuantity == null // || (sohItemQuantity.getDateInfo() != null && !sohItemQuantity.getDateInfo().equals(dateStr))) { // List sohDataList = batteryMapper.getSohData(partitions); // if (sohDataList.size() > 0) { // sohDataList.forEach(o -> { // SohItemQuantity entity = new SohItemQuantity(); // entity.setDateInfo(dateStr); // entity.setItem(o.getSohSection()); // entity.setQuantity(o.getElectricQuantity()); // sohMapper.insert(entity); // }); // } // } //计算soh里程分布 SohOdo sohOdo = sohOdoMapper.selectOne(new QueryWrapper() .select("date_info") .last(" limit 1 ") .orderByDesc("id") .eq("is_delete", 0)); if (sohOdo == null || (sohOdo.getDateInfo() != null && !sohOdo.getDateInfo().equals(dateStr))) { List sohMileageVoList = new ArrayList<>(); List> mapList = batteryMapper.getSohMileageData(); if (!CollectionUtils.isEmpty(mapList)) { List sohDataList = JSONArray.parseArray(JSON.toJSONString(mapList), SohOdoVo.class); //添加区间名称> for (SohOdoVo o : sohDataList) { //里程区间 if (o.getOdo().compareTo(BigDecimal.valueOf(50000)) < 0) { o.setOdoSection(SohMileageEnum.getDesc(0)); } else if (o.getOdo().compareTo(BigDecimal.valueOf(50000)) > 0 && o.getOdo().compareTo(BigDecimal.valueOf(50000 * 2)) <= 0) { o.setOdoSection(SohMileageEnum.getDesc(1)); } else if (o.getOdo().compareTo(BigDecimal.valueOf(50000 * 2)) > 0 && o.getOdo().compareTo(BigDecimal.valueOf(50000 * 3)) <= 0) { o.setOdoSection(SohMileageEnum.getDesc(2)); } else if (o.getOdo().compareTo(BigDecimal.valueOf(50000 * 3)) > 0 && o.getOdo().compareTo(BigDecimal.valueOf(50000 * 4)) <= 0) { o.setOdoSection(SohMileageEnum.getDesc(3)); } else if (o.getOdo().compareTo(BigDecimal.valueOf(50000 * 4)) > 0) { o.setOdoSection(SohMileageEnum.getDesc(4)); } //soh区间 if (o.getSoh().compareTo(BigDecimal.valueOf(80)) < 0) { o.setSohSection(SohPercentEnum.LESS_EIGHT.message()); } else if (o.getSoh().compareTo(BigDecimal.valueOf(80)) > 0 && o.getSoh().compareTo(BigDecimal.valueOf(90)) <= 0) { o.setSohSection(SohPercentEnum.EIGHT_TO_NINE.message()); } else if (o.getSoh().compareTo(BigDecimal.valueOf(90)) > 0 && o.getSoh().compareTo(BigDecimal.valueOf(100)) <= 0) { o.setSohSection(SohPercentEnum.NINE_TO_TEN.message()); } else { o.setSohSection(SohPercentEnum.MORE_THEN_TEN.message()); } } //按照soh区间+odo区间分别计算 Map map = sohDataList.stream() .collect(Collectors.groupingBy(x -> x.getSohSection() + "#" + x.getOdoSection(), Collectors.counting())); for (SohPercentEnum e : SohPercentEnum.values()) { SohMileageVo vo = new SohMileageVo(); vo.setTitle(SohPercentEnum.getDesc(e.code())); List list = new ArrayList<>(); //初始化 for (SohMileageEnum s : SohMileageEnum.values()) { list.add(0L); } map.forEach((key, value) -> { for (SohMileageEnum s : SohMileageEnum.values()) { if (key.startsWith(e.message()) && key.endsWith(s.message())) { long value1; value1 = value; list.set(s.code(), value1); break; } } }); vo.setCarTotalityList(list); sohMileageVoList.add(vo); } if (sohMileageVoList.size() > 0) { SohOdo entity = new SohOdo(); entity.setDateInfo(dateStr); entity.setData(JSON.toJSONString(sohMileageVoList)); sohOdoMapper.insert(entity); } } } } private void setYesWeekMonthData(TodayCompareOtherVo bsVo, List quantityItemVoList, Integer type, String today, String yesterday, String lastWeek, String todays, String yesterdays, String lastWeeks, String lastMonth, int total) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd020000"); bsVo.setCount("0"); bsVo.setYesterday("0"); bsVo.setYesterdayFlag(null); bsVo.setWeek("0"); bsVo.setWeekFlag(null); bsVo.setMonth("0"); bsVo.setMonthFlag(null); //当日数据提前准备 // if (quantityItemVoList.size() > 0) { BigDecimal tod = BigDecimal.ZERO; BigDecimal yes = BigDecimal.ZERO; BigDecimal law = BigDecimal.ZERO; BigDecimal lam = BigDecimal.ZERO; List list = quantityItemVoList.stream() .filter(o -> String.valueOf(type).equals(o.getItem())).collect(Collectors.toList()); for (QuantityItemDateStaticVo vo : list) { if (Long.valueOf(sdf.format(new Date())) > Long.valueOf(sdf2.format(new Date()))) { if (vo.getStaticDate().equals(today)) { tod = vo.getQuantity(); } if (vo.getStaticDate().equals(yesterday)) { yes = vo.getQuantity(); } if (vo.getStaticDate().equals(lastWeek)) { law = vo.getQuantity(); } } else { if (vo.getStaticDate().equals(todays)) { tod = vo.getQuantity(); } if (vo.getStaticDate().equals(yesterdays)) { yes = vo.getQuantity(); } if (vo.getStaticDate().equals(lastWeeks)) { law = vo.getQuantity(); } } if (vo.getStaticDate().equals(lastMonth)) { lam = vo.getQuantity(); } } if (type == 8) { bsVo.setCount(DecimalFormat.getNumberInstance().format(tod.divide(BigDecimal.valueOf(1000000L), 2, RoundingMode.HALF_UP))); } else { bsVo.setCount(DecimalFormat.getNumberInstance().format(tod)); } boolean percent = false; if (type.equals(BatteryOverviewEnum.ONLINE.code()) || type.equals(BatteryOverviewEnum.ALARM.code()) || type.equals(BatteryOverviewEnum.HIGH_VOLT.code()) || type.equals(BatteryOverviewEnum.SOH.code()) || type.equals(BatteryOverviewEnum.CAPACITY.code()) || type.equals(BatteryOverviewEnum.OPERATE_VEHICLE.code())) { percent = true; } if (percent) { bsVo.setYesterday(calculatePercent(tod, BigDecimal.valueOf(total))); int res = setFlag(tod, yes); bsVo.setYesterdayFlag(res); } else { if (law.compareTo(BigDecimal.ZERO) != 0 && yes.compareTo(BigDecimal.ZERO) != 0 && lam.compareTo(BigDecimal.ZERO) != 0) { bsVo.setYesterday(calculateRate(tod, yes)); int res = setFlag(tod, yes); bsVo.setYesterdayFlag(res); bsVo.setWeek(calculateRate(tod, law)); res = setFlag(tod, law); bsVo.setWeekFlag(res); bsVo.setMonth(calculateRate(tod, lam)); res = setFlag(tod, lam); bsVo.setMonthFlag(res); } else { bsVo.setYesterday("0"); bsVo.setWeek("0"); bsVo.setMonth("0"); bsVo.setYesterdayFlag(3); bsVo.setWeekFlag(3); bsVo.setMonthFlag(3); } } // } } /** * 批量添加电池标签 * * @param dto 参数 * @return java.lang.String */ @Override @Transactional(rollbackFor = Exception.class) public String batteryBatchAddTag(TagDto dto) { int count = 0; //先转换为列表 List dtoList = new ArrayList<>(); if (StringUtils.isNotBlank(dto.getBatchId())) { List list = Arrays.asList(dto.getBatchId().split(",")); if (list.size() > 0) { list.forEach(o -> { TagDto tagDto = new TagDto(); BeanUtils.copyProperties(dto, tagDto); tagDto.setBatteryId(Long.parseLong(o)); dtoList.add(tagDto); }); } } int size = dtoList.size(); if (size > 0) { //已有标签列表 Set idSet = new HashSet<>(); dtoList.forEach(o -> idSet.add(o.getBatteryId())); List batteryTagList = new ArrayList<>(); if (idSet.size() > 0) { batteryTagList = batteryTagMapper.selectList(new LambdaQueryWrapper() .eq(BatteryTag::getTagType, 0) .in(BatteryTag::getBatteryId, idSet) .eq(BatteryTag::getIsDelete, 0)); } for (TagDto tagDto : dtoList) { BatteryTag batteryTag = new BatteryTag(); BeanUtils.copyProperties(tagDto, batteryTag); batteryTag.setTagType(0); //已有的标签进行追加 if (batteryTagList.size() > 0) { batteryTagList.forEach(o -> { if (tagDto.getBatteryId().equals(o.getBatteryId()) && tagDto.getTagId().equals(o.getTagId())) { batteryTag.setId(o.getId()); List list = Arrays.asList(o.getChildTagList().split(",")); List batchList = Arrays.asList(tagDto.getChildTagList().split(",")); //有则加,无则用 if (list.size() > 0) { if (batchList.size() > 0) { batchList.forEach(m -> { if (!list.contains(m)) { o.setChildTagList(o.getChildTagList().concat("," + m)); } }); } } else { o.setChildTagList(tagDto.getChildTagList()); } } }); } //有id说明是追加,执行更改,否则执行新增 int num = batteryTag.getId() != null ? batteryTagMapper.updateById(batteryTag) : batteryTagMapper.insert(batteryTag); count = count + num; } } //执行数量和预估数量一致,认为成功 if (count == size && count > 0) { return Constants.OK; } else { return Constants.FAILED; } } @Override public void syncBatteryPackCode() { //获取t_battery中全部pack List packCodeEntitys = baseMapper.selectList(new LambdaQueryWrapper().select(Battery::getPackModelCode).groupBy(Battery::getPackModelCode)); //获取algo_adjustable_param中全部algo_id List algoIdEntitys = adjustableParamEntityMapper.selectList(new LambdaQueryWrapper().select(ModelAdjustableParamEntity::getAlgoId).groupBy(ModelAdjustableParamEntity::getAlgoId)); //获取到的pack,algo_id存入set Set packCodeList = packCodeEntitys.stream().map(Battery::getPackModelCode).collect(Collectors.toSet()); Set algoIdSet = algoIdEntitys.stream().map(ModelAdjustableParamEntity::getAlgoId).collect(Collectors.toSet()); //遍历全部的algo_id algoIdSet.forEach(id -> { //根据algo_id查询对应algo_id绑定的pack号 List getPacksByIdEntitys = adjustableParamEntityMapper.selectList(new LambdaQueryWrapper() .select(ModelAdjustableParamEntity::getAlgoId) .select(ModelAdjustableParamEntity::getPackCode) .eq(ModelAdjustableParamEntity::getAlgoId, id)); //获取到对应algo_id绑定的pack存入set Set packsSet = getPacksByIdEntitys.stream().map(ModelAdjustableParamEntity::getPackCode).collect(Collectors.toSet()); //收集t_battery中存在,algo_adjustable_param不存在的pack型号 List packsCollect = packCodeList.stream().filter(o -> !packsSet.contains(o)).collect(Collectors.toList()); //判断packsCollect非空 if (packsCollect != null) { //循环遍历packsCollect中的pack,存入algo_adjustable_param中对应的algo_id下 for (String pack : packsCollect) { ModelAdjustableParamEntity paramEntity = new ModelAdjustableParamEntity(); paramEntity.setAlgoId(id); paramEntity.setPackCode(pack); adjustableParamEntityMapper.insert(paramEntity); } } }); } @Override public void calSohQuantity() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dateStr = sdf.format(new Date()); //计算soh占比 List sohItemQuantities = sohMapper.selectList(new QueryWrapper() .select("date_info", "item", "quantity") .eq("date_info", dateStr) .eq("is_delete", 0)); SimpleDateFormat sdff = new SimpleDateFormat("yyyyMM"); String partNow = "p" + sdff.format(new Date()); String partBefore = "p" + sdff.format(lastMonthEndDay()); String partitions = partNow + "," + partBefore; List sohDataList = batteryMapper.getSohData(partitions); if (sohItemQuantities.isEmpty()) { if (sohDataList.size() > 0) { sohDataList.forEach(o -> { SohItemQuantity entity = new SohItemQuantity(); entity.setDateInfo(dateStr); entity.setItem(o.getSohSection()); entity.setQuantity(o.getElectricQuantity()); sohMapper.insert(entity); }); } } else { sohItemQuantities.forEach(o -> { sohDataList.forEach(v -> { if (o.getItem().equals(v.getSohSection()) && !o.getQuantity().equals(v.getElectricQuantity())) { SohItemQuantity entity = new SohItemQuantity(); entity.setDateInfo(dateStr); entity.setItem(v.getSohSection()); entity.setQuantity(v.getElectricQuantity()); sohMapper.updateByDateStr(entity); } }); }); } } }