123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239 |
- 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<BatteryMapper, Battery> 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<String> batteryModelSet = new HashSet<>();
- batteryModelSet.add(model);
- List<BatteryModel> 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<BatteryCore> batteryCoreList = new ArrayList<>();
- if (vo.getBatteryCoreType() != null) {
- LambdaQueryWrapper<BatteryCore> 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<AlarmMsg> alarmMsgList = new ArrayList<>();
- if (vo.getSn() != null) {
- LambdaQueryWrapper<AlarmMsg> 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<Map<String, Object>> 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<Map<String, Object>> 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<Battery>()
- .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<String> batteryModelSet = new HashSet<>();
- batteryModelSet.add(model);
- List<BatteryModel> batteryModelList = new ArrayList<>();
- if (batteryModelSet.size() > 0) {
- batteryModelList = batteryModelMapper.getModel(model);
- }
- //翻译字段
- List<BatteryCore> batteryCoreList = new ArrayList<>();
- if (vo.getBatteryCoreType() != null) {
- LambdaQueryWrapper<BatteryCore> 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<AlarmMsg> alarmMsgList = new ArrayList<>();
- if (vo.getSn() != null) {
- LambdaQueryWrapper<AlarmMsg> 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<Map<String, Object>> 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<Map<String, Object>> 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<Battery>()
- .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<String> batteryModelSet = new HashSet<>();
- batteryModelSet.add(model);
- List<BatteryModel> batteryModelList = new ArrayList<>();
- if (batteryModelSet.size() > 0) {
- batteryModelList = batteryModelMapper.getModel(model);
- }
- //翻译字段
- List<BatteryCore> batteryCoreList = new ArrayList<>();
- if (vo.getBatteryCoreType() != null) {
- LambdaQueryWrapper<BatteryCore> 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<AlarmMsg> alarmMsgList = new ArrayList<>();
- if (vo.getSn() != null) {
- LambdaQueryWrapper<AlarmMsg> 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<BatteryVo> selectBatteryList(BatteryParam param) {
- //电池类型
- List<String> cellList = new ArrayList<>();
- List<String> packList = new ArrayList<>();
- if (!param.getBatteryModel().isEmpty()) {
- List<BatteryModel> batteryModel = batteryModelMapper.selectList(new LambdaQueryWrapper<BatteryModel>().in(!param.getBatteryModel().isEmpty(), BatteryModel::getId, param.getBatteryModel()));
- batteryModel.forEach(o -> {
- cellList.add(o.getCellModel());
- packList.add(o.getPackModel());
- });
- }
- //故障状态
- Set<String> snSet = new HashSet<>();
- List<Map<String, Object>> 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<AlarmMsg> wap = new LambdaQueryWrapper<>();
- wap.eq(AlarmMsg::getIsDelete, 0);
- wap.isNull(AlarmMsg::getAlarmFreeTime);
- wap.select(AlarmMsg::getSn);
- List<AlarmMsg> 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<Long> batteryIdSet = new HashSet<>();
- if (StringUtils.isNotBlank(param.getTag())) {
- List<String> tags = new ArrayList<>();
- tags = Arrays.asList(param.getTag().split(","));
- Set<Long> tagIdSet = new HashSet<>();
- tags.forEach(o -> tagIdSet.add(Long.parseLong(o)));
- if (tags.size() > 0) {
- LambdaQueryWrapper<BatteryTag> 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<BatteryTag> 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<Battery> 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<Battery> list = this.list(wrapper);
- PageInfo<Battery> orderPageInfo = new PageInfo<>(list);
- List<BatteryVo> batteryVoList = new ArrayList<>();
- //准备翻译
- List<Tag> tagList = new ArrayList<>();
- List<BatteryFolder> batteryFolderList = new ArrayList<>();
- List<BatteryModel> batteryModelList = new ArrayList<>();
- List<BatteryCore> batteryCorelList = new ArrayList<>();
- Set<String> batteryCoreSet = new HashSet<>();
- Set<Long> collectIdSet = new HashSet<>();
- Set<String> snFaultSet = new HashSet<>();
- List<ModelDetailVo> modelList = new ArrayList<>();
- List<String> 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<Map<String, Object>> 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<SysDictData> batteryCoreList = getDictDataByType("business_battery_core_type");
- if (batteryCoreSet.size() > 0) {
- LambdaQueryWrapper<BatteryCore> 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<BatteryFolder> 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<BatteryModel> finalBatteryModelList = batteryModelList;
- List<Tag> finalTagList = tagList;
- List<BatteryCore> finalBatteryCorelList = batteryCorelList;
- List<BatteryFolder> finalBatteryFolderList = batteryFolderList;
- List<ModelDetailVo> 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<String> tagIdList = new HashSet<>();
- Set<String> 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<BatteryVo> result = new PageInfo<>(batteryVoList);
- result.setTotal(orderPageInfo.getTotal());
- return result;
- }
- /**
- * 查询快充电池信息列表
- *
- * @param param 电池信息
- * @return 电池信息集合
- */
- @Override
- public PageInfo<FastChargeBatteryVo> selectFastChargeBatteryList(BatteryParam param) {
- //电池类型
- List<String> cellList = new ArrayList<>();
- List<String> packList = new ArrayList<>();
- if (!param.getBatteryModel().isEmpty()) {
- List<BatteryModel> batteryModel = batteryModelMapper.selectList(new LambdaQueryWrapper<BatteryModel>().in(!param.getBatteryModel().isEmpty(), BatteryModel::getId, param.getBatteryModel()));
- batteryModel.forEach(o -> {
- cellList.add(o.getCellModel());
- packList.add(o.getPackModel());
- });
- }
- //故障状态
- Set<String> snSet = new HashSet<>();
- List<Map<String, Object>> 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<AlarmMsg> wap = new LambdaQueryWrapper<>();
- wap.eq(AlarmMsg::getIsDelete, 0);
- wap.eq(AlarmMsg::getModelCode, FAST_CHARGE);
- wap.isNull(AlarmMsg::getAlarmFreeTime);
- wap.select(AlarmMsg::getSn);
- List<AlarmMsg> 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<Long> batteryIdSet = new HashSet<>();
- if (StringUtils.isNotBlank(param.getTag())) {
- List<String> tags = new ArrayList<>();
- tags = Arrays.asList(param.getTag().split(","));
- Set<Long> tagIdSet = new HashSet<>();
- tags.forEach(o -> tagIdSet.add(Long.parseLong(o)));
- if (tags.size() > 0) {
- LambdaQueryWrapper<BatteryTag> 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<BatteryTag> 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<FastChargeBattery> 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<FastChargeBattery> list = fastChargeBatteryMapper.selectList(wrapper);
- PageInfo<FastChargeBattery> orderPageInfo = new PageInfo<>(list);
- List<FastChargeBatteryVo> batteryVoList = new ArrayList<>();
- //准备翻译
- List<Tag> tagList = new ArrayList<>();
- List<BatteryFolder> batteryFolderList = new ArrayList<>();
- List<BatteryModel> batteryModelList = new ArrayList<>();
- List<BatteryCore> batteryCorelList = new ArrayList<>();
- Set<String> batteryCoreSet = new HashSet<>();
- Set<Long> collectIdSet = new HashSet<>();
- List<String> 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<BatteryCore> 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<BatteryFolder> 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<BatteryModel> finalBatteryModelList = batteryModelList;
- List<Tag> finalTagList = tagList;
- List<BatteryCore> finalBatteryCorelList = batteryCorelList;
- List<BatteryFolder> 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<String> tagIdList = new HashSet<>();
- Set<String> 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<FastChargeBatteryVo> result = new PageInfo<>(batteryVoList);
- result.setTotal(orderPageInfo.getTotal());
- return result;
- }
- private void setTotalBatteryTotal(TodayCompareOtherVo bsVo, BatteryOverviewParam param, List<String> 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<String> 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<String> 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<Map<String, Object>> mapList = batteryMapper.getHistoryData(carModel, param.getPackModel(), param.getCellModel(), strArray);
- List<QuantityItemDateStaticVo> 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<QuantityItemDateStaticVo> 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<QuantityItemDateStaticVo> 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<String> carModelList1 = new ArrayList<>();
- List<String> 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<Battery>()
- .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<Integer> ids = batteryOverviewParam.getBatteryModel();
- if (!ids.isEmpty()) {
- List<BatteryModel> batteryModelList = batteryModelMapper.getBatteryModelListByIds(ids);
- List<String> cellList = new ArrayList<>();
- List<String> 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<String> 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<String> 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<String> 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<ElectricQuantity> 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<String> 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<String> dateStrList = new ArrayList<>();
- dateStrList.add(yesterday);
- dateStrList.add(today);
- dateStrList.add(lastWeek);
- dateStrList.add(lastMonth);
- //找到了数据
- List<BatteryModelStatistics> 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<String> 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<String> carModelList, BigDecimal total) {
- //List<Battery> batteryList = this.list(new LambdaQueryWrapper<Battery>()
- // .select(Battery::getSn)
- // .in(carModelList.size() > 0, Battery::getModel, carModelList)
- // .eq(StringUtils.isNotBlank(param.getPackModel()), Battery::getPackModelCode, param.getPackModel())
- // .eq(Battery::getIsDelete, 0));
- //List<String> 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<String> carModelList) {
- if (!param.getCarModel().isEmpty()) {
- //找到了数据
- int fault = batteryMapper.selectCount(new LambdaQueryWrapper<Battery>()
- .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<Battery>()
- .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<SysDictData> getDictDataByType(String dictType) {
- List<SysDictData> 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<BaseCycleChartVo> carModelPercentList = new ArrayList<>();
- //soh最新信息
- // List<Battery> 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<SohItemQuantity> sohDataList = sohMapper.selectList(new LambdaQueryWrapper<SohItemQuantity>()
- .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<BaseCycleChartVo> carModelPercentList = new ArrayList<>();
- SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
- SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd020000");
- List<Battery> 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<HzCarModel> hzCarModelList = batteryModelMapper.getHzCarModelList();
- batteryList.forEach(o -> {
- hzCarModelList.forEach(v -> {
- if (v.getSModelCode().contains(o.getItem())) {
- o.setItem(v.getHzModelName());
- }
- });
- });
- Map<String, Long> 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<String> iterator = totalObject.keySet().iterator();
- // List<BaseCycleChartVo> batteryTypePercentList = new ArrayList<>();
- // BigDecimal total = BigDecimal.ZERO;
- // List<String> 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<BatteryModel> 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<BaseCycleChartVo> baseCycleChartVos = new ArrayList<>();
- List<BatteryModelCountVo> 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<Folder>()
- .eq(Folder::getUserId, SecurityUtils.getUserId())
- .eq(Folder::getId, dto.getFolderId())
- .eq(Folder::getIsDelete, 0));
- if (count <= 0) {
- return "收藏夹不存在";
- }
- count = batteryFolderMapper.selectCount(new LambdaQueryWrapper<BatteryFolder>()
- .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<com.hz.business.vo.BatteryTagVo>
- */
- @Override
- public BatteryHistoryFaultVo getHistoryFault(String sn) {
- return null;
- }
- /**
- * 查询电池标签
- *
- * @param param 电池id
- * @return java.util.List<com.hz.business.vo.BatteryTagVo>
- */
- @Override
- public PageInfo<BatteryTagVo> batteryQueryTag(BatteryTagParam param) {
- PageHelper.startPage(param.getPageIndex(), param.getPageSize());
- List<BatteryTagVo> batteryTagVoList = new ArrayList<>();
- List<BatteryTag> batteryTags = batteryTagMapper.selectList(new LambdaQueryWrapper<BatteryTag>()
- .eq(BatteryTag::getBatteryId, param.getId())
- .eq(BatteryTag::getTagType, 0)
- .eq(BatteryTag::getIsDelete, 0)
- .orderByDesc(BatteryTag::getUpdateTime));
- PageInfo<BatteryTag> orderPageInfo = new PageInfo<>(batteryTags);
- //准备翻译
- List<Tag> tagList = new ArrayList<>();
- List<TagChild> tagChildList = new ArrayList<>();
- Set<Long> tagSet = new HashSet<>();
- Set<Long> 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<String> childList = Arrays.asList(str);
- childList.forEach(m -> childTagSet.add(Long.parseLong(m)));
- }
- });
- if (tagSet.size() > 0) {
- LambdaQueryWrapper<Tag> 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<TagChild> 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<Tag> finalTagList = tagList;
- List<TagChild> 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<String> 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<BatteryTagVo> 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<TagChild> tagChildList = new ArrayList<>();
- String tagName = "";
- Set<Long> 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<TagChild> 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<String> 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<Tag>
- */
- @Override
- public List<Tag> getTagBattery(Integer type) {
- return tagMapper.selectList(new LambdaQueryWrapper<Tag>()
- .eq(Tag::getTagType, type)
- .eq(Tag::getIsDelete, 0));
- }
- /**
- * 电池概览
- *
- * @param param 参数
- * @return java.util.List<com.hz.business.domain.Tag>
- */
- @Override
- public BatteryOverviewVo getBatteryOverview(BatteryOverviewParam param) {
- return null;
- }
- /**
- * 我的故障收藏
- *
- * @param param 我的故障收藏
- * @return java.util.List<com.hz.business.vo.BatteryFolderVo>
- */
- @Override
- public PageInfo<BatteryFolderVo> getMyCollectData(BatteryFolderParam param) {
- if (param.getFolderId() == null) {
- return new PageInfo<>();
- }
- PageHelper.startPage(param.getPageIndex(), param.getPageSize());
- List<BatteryFolderVo> batteryTagVoList = new ArrayList<>();
- //查询
- List<BatteryFolder> batteryFolders = batteryFolderMapper.selectList(new LambdaQueryWrapper<BatteryFolder>()
- .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<BatteryFolder> orderPageInfo = new PageInfo<>(batteryFolders);
- //准备翻译
- orderPageInfo.getList().forEach(o -> {
- BatteryFolderVo vo = new BatteryFolderVo();
- BeanUtils.copyProperties(o, vo);
- vo.setCollectionTime(o.getCreateTime());
- batteryTagVoList.add(vo);
- });
- PageInfo<BatteryFolderVo> result = new PageInfo<>(batteryTagVoList);
- result.setTotal(orderPageInfo.getTotal());
- return result;
- }
- /**
- * 获取SOH里程分布图
- *
- * @return java.util.List<com.hz.business.vo.SohMileageVo>
- */
- @Override
- public List<SohMileageVo> getSohMileage() {
- List<SohMileageVo> 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<SohOdo> sohOdoList = sohOdoMapper.selectList(new LambdaQueryWrapper<SohOdo>()
- .eq(SohOdo::getDateInfo, Long.valueOf(sdf2.format(new Date())) > Long.valueOf(sdf3.format(new Date())) ? dateStr : dateStrs)
- .eq(SohOdo::getIsDelete, 0));
- //List<Map<String, Object>> 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<FlinkData> flinkDataList = getFlinkData(param);
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- //时间轴
- List<String> timeList = flinkDataList.stream().map(o -> sdf.format(o.getTime())).collect(Collectors.toList());
- //最高电压
- List<Float> maxVoltageList = new ArrayList<>();
- /*List<Float> maxVoltageList = flinkDataList.stream()
- .map(o -> (o.getCellMaxVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxVol() / 1000)
- .collect(Collectors.toList());*/
- //最低电压
- List<Float> minVoltageList = new ArrayList<>();
- /*List<Float> minVoltageList = flinkDataList.stream()
- .map(o -> (o.getCellMinVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinVol() / 1000)
- .collect(Collectors.toList());*/
- //最高温度
- List<Float> cellMaxTempList = new ArrayList<>();
- /*List<Float> cellMaxTempList = flinkDataList.stream()
- .map(o -> (o.getCellMaxTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxTemp())
- .collect(Collectors.toList());*/
- //最低温度
- List<Float> cellMinTempList = new ArrayList<>();
- /*List<Float> cellMinTempList = flinkDataList.stream()
- .map(o -> (o.getCellMinTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinTemp())
- .collect(Collectors.toList());*/
- //总电压
- List<Float> packVoltageList = flinkDataList.stream()
- .map(o -> (o.getPackVoltage().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackVoltage())
- .collect(Collectors.toList());
- //总电流
- List<Float> packCrntList = flinkDataList.stream()
- .map(o -> (o.getPackCrnt().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackCrnt())
- .collect(Collectors.toList());
- //SOC
- List<Float> packSocList = flinkDataList.stream()
- .map(o -> (o.getPackSoc().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackSoc())
- .collect(Collectors.toList());
- //绝缘电阻
- List<Float> insulationRssList = flinkDataList.stream()
- .map(o -> (o.getInsulationRss().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getInsulationRss())
- .collect(Collectors.toList());
- //压差
- List<Float> voltageDifferenceList = new ArrayList<>();
- /*List<Float> voltageDifferenceList = flinkDataList.stream()
- .map(p -> p.getBmsCellVoltDiff().floatValue())
- .collect(Collectors.toList());*/
- //车速
- List<Float> vehSpdList = flinkDataList.stream()
- .map(o -> (o.getVehSpd() == null || o.getVehSpd().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getVehSpd())
- .collect(Collectors.toList());
- //单体电压
- List<String> voltDiffList = flinkDataList.stream()
- .map(FlinkData::getCellVoltage)
- .collect(Collectors.toList());
- //单体温度
- List<String> 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<String> listTemp = Arrays.asList(s.split(","));
- List<String> 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<String> listTemp = Arrays.asList(s.split(","));
- List<String> 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<List<Float>> 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<List<Float>> 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<Float> list : bmsCellVoltDiffList) {
- if (list.size() > maxVoltageSize) {
- maxVoltageSize = list.size();
- }
- }
- for (List<Float> list : bmsCellVoltDiffList) {
- while (list.size() < maxVoltageSize) {
- list.add(null);
- }
- }
- int maxTemSize = 0;
- for (List<Float> list : bmsBatTempDiffList) {
- if (list.size() > maxTemSize) {
- maxTemSize = list.size();
- }
- }
- for (List<Float> 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<com.hz.business.domain.FlinkData>
- */
- private List<FlinkData> 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<FlinkData> 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<FlinkData> 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<String> 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<HealthScore> healthScoreList = batteryMapper.getHistoryHealthScore(param.getSn(), begin, end, partitions);
- List<DateValueVo> 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<DiagnosticVo> diagnosticVoList = setDiagnosticVoList(param.getSn());
- List<DiagnosticVo> 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<BigDecimal> odoList = new ArrayList<>();
- //当前电池健康度
- List<Battery> 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<Battery> 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<BigDecimal> allBatteryList = new ArrayList<>();
- if (singleList.size() > 0) {
- singleList.forEach(o -> {
- allBatteryList.add(new BigDecimal(o.getOdo()));
- });
- List<BigDecimal> 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<BigDecimal> 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<KindFloatValueListVo> kindList = new ArrayList<>();
- //本车电池soh
- KindFloatValueListVo kindValueVo = new KindFloatValueListVo();
- kindValueVo.setName("电池soh");
- //本车型电池平均soh
- KindFloatValueListVo kindValueVo1 = new KindFloatValueListVo();
- kindValueVo1.setName("车型电池平均soh");
- List<BigDecimal> singleSohList = new ArrayList<>();
- List<BigDecimal> 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<HealthScore> sohDiffList = batteryMapper.getSohLineChartVo(sn, begin, end, partitions);
- if (!CollectionUtils.isEmpty(sohDiffList)) {
- //时间轴
- List<String> 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<String, List<BigDecimal>> map = new HashMap<String, List<BigDecimal>>();
- for (int i = 0; i < len; i++) {
- map.put("cell-" + i, new ArrayList<BigDecimal>());
- }
- for (int i = 0; i < sohDiffList.size(); i++) {
- List<String> 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<KindFloatValueListVo> 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<String> tempList = new ArrayList<>();
- //填充时间段内的所有分区
- Set<String> 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<HealthScore> healthScoreList = batteryMapper.setResistanceChartVoList(sn, begin, end, partitions);
- List<DateValueVo> 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<HealthScore> healthScoreList = batteryMapper.setSohDiffVoList(sn, begin, end, partitions);
- List<DateValueVo> 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<HealthScore> healthScoreList = batteryMapper.setSocChartVoList(sn, begin, end, partitions);
- List<DateValueVo> 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<HealthScore> healthScoreList = batteryMapper.setTemperatureChartVoList(sn, begin, end, partitions);
- List<DateValueVo> 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<com.hz.business.vo.DiagnosticVo>
- */
- private List<DiagnosticVo> setDiagnosticVoList(String sn) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
- String partNow = "p" + sdf.format(new Date());
- String partBefore = "p" + sdf.format(lastMonthEndDay());
- List<DiagnosticVo> diagnosticVoList = new ArrayList<>();
- //algo_soh —— cellsoh_diff soh
- List<HealthScore> 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<HealthScore> 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<HealthScore> 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<HealthScore> 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<HealthScore> 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<FlinkData> convertList(ResultSet rs) {
- List<FlinkData> flinkDataList = new ArrayList();
- try {
- List<Map<String, Object>> mapList = new ArrayList();
- ResultSetMetaData md = rs.getMetaData();
- int columnCount = md.getColumnCount();
- while (rs.next()) {
- Map<String, Object> 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<BaseExportExcelVo> maxVoltageList = new ArrayList<>();
- //最低电压
- List<BaseExportExcelVo> minVoltageList = new ArrayList<>();
- //最高温度
- List<BaseExportExcelVo> cellMaxTempList = new ArrayList<>();
- //最低温度
- List<BaseExportExcelVo> cellMinTempList = new ArrayList<>();
- //总电压
- List<BaseExportExcelVo> packVoltageList = new ArrayList<>();
- //总电流
- List<BaseExportExcelVo> packCrntList = new ArrayList<>();
- //压差
- List<BaseExportExcelVo> voltageDifferenceList = new ArrayList<>();
- //SOC
- List<BaseExportExcelVo> packSocList = new ArrayList<>();
- //单体电压
- List<BaseExportExcelStringVo> voltVoList = new ArrayList<>();
- //单体温度
- List<BaseExportExcelStringVo> tempVoList = new ArrayList<>();
- //绝缘电阻
- List<BaseExportExcelVo> insulationRssDiffList = new ArrayList<>();
- List<List<?>> indexList = new ArrayList<>();
- List<List<String>> headVoltList = new ArrayList<>();
- List<List<String>> headTempList = new ArrayList<>();
- List<List<String>> cellVoltObjectDiff = new ArrayList<>();
- List<List<String>> batTempObjectDiff = new ArrayList<>();
- List<String> 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<FlinkData> 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<String> listTemp = Arrays.asList(o.getCellVoltage().split(","));
- List<String> 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<String> listTemp = Arrays.asList(o.getCellTemp().split(","));
- List<String> 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<String> 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<String> result = Arrays.asList(split);
- batTempObjectDiff.add(result);
- });
- String[] split = tempVoList.get(0).getData().trim().split(",");
- lenTemp = split.length;
- }
- }
- List<String> timeList = Arrays.asList("日期时间");
- headVoltList.add(timeList);
- headTempList.add(timeList);
- for (int i = 1; i <= lenVolt; i++) {
- List<String> cellHeadList = Arrays.asList("cell-" + i);
- headVoltList.add(cellHeadList);
- }
- for (int i = 1; i <= lenTemp; i++) {
- List<String> 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<BaseExportExcelVo> healthScoreOverviewList = new ArrayList<>();
- //内阻一致性
- List<BaseExportExcelVo> resistanceChartVoList = new ArrayList<>();
- //SOH一致性
- List<BaseExportExcelVo> sohDiffVoList = new ArrayList<>();
- //SOC一致性
- List<BaseExportExcelVo> socChartVoList = new ArrayList<>();
- //温度一致性
- List<BaseExportExcelVo> temperatureChartVoList = new ArrayList<>();
- //SOH趋势图
- List<BaseExportExcelStringVo> 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<HealthScore> healthScoreList = batteryMapper.getHistoryHealthScore(param.getSn(), begin, end, partitions);
- List<DateValueVo> 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<BatteryLocationVo> getBatteryLocation() {
- List<Battery> list = batteryMapper.getBatteryLocation();
- List<BatteryLocationVo> 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<BatteryLocationVo> getBatteryChargingLocation() {
- List<Battery> list = batteryMapper.getBatteryChargingLocation();
- List<BatteryLocationVo> 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<FlinkData> flinkDataList = getFlinkData(param);
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- //时间轴
- List<String> timeList = flinkDataList.stream().map(o -> sdf.format(o.getTime())).collect(Collectors.toList());
- //单体压差
- List<Float> bmsCellVoltDiffList = new ArrayList<>();
- /*List<Float> bmsCellVoltDiffList = flinkDataList.stream()
- .map(o -> (o.getBmsCellVoltDiff().floatValue() == Constants.BATTERY_ERROR_CODE) ? null : o.getBmsCellVoltDiff().floatValue())
- .collect(Collectors.toList());*/
- //电池包Soc
- List<Float> packSocList = flinkDataList.stream()
- .map(o -> (o.getPackSoc().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackSoc())
- .collect(Collectors.toList());
- //电芯最高温度
- List<Float> cellMaxTempList = new ArrayList<>();
- /*List<Float> cellMaxTempList = flinkDataList.stream()
- .map(o -> (o.getCellMaxTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxTemp())
- .collect(Collectors.toList());*/
- //电芯最低温度
- List<Float> cellMinTempList = new ArrayList<>();
- /*List<Float> cellMinTempList = flinkDataList.stream()
- .map(o -> (o.getCellMinTemp().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinTemp())
- .collect(Collectors.toList());*/
- //最高电压
- List<Float> maxVoltList = new ArrayList<>();
- /*List<Float> maxVoltList = flinkDataList.stream()
- .map(o -> (o.getCellMaxVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMaxVol() / 1000)
- .collect(Collectors.toList());*/
- //最低电压
- List<Float> minVoltList = new ArrayList<>();
- /*List<Float> minVoltList = flinkDataList.stream()
- .map(o -> (o.getCellMinVol().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getCellMinVol() / 1000)
- .collect(Collectors.toList());*/
- //电池整包电压
- List<Float> packVoltageList = flinkDataList.stream()
- .map(o -> (o.getPackVoltage().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackVoltage())
- .collect(Collectors.toList());
- //电池包输出电流
- List<Float> packCrntList = flinkDataList.stream()
- .map(o -> (o.getPackCrnt() == null || o.getPackCrnt().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getPackCrnt())
- .collect(Collectors.toList());
- //车速
- List<Float> vehSpdList = flinkDataList.stream()
- .map(o -> (o.getVehSpd() == null || o.getVehSpd().equals(Constants.BATTERY_ERROR_CODE)) ? null : o.getVehSpd())
- .collect(Collectors.toList());
- //单体电压
- List<String> voltDiffList = flinkDataList.stream()
- .map(FlinkData::getCellVoltage)
- .collect(Collectors.toList());
- //单体电压
- List<String> tempDiffList = flinkDataList.stream()
- .map(FlinkData::getCellTemp)
- .collect(Collectors.toList());
- if (voltDiffList.size() > 0) {
- for (String s : voltDiffList) {
- List<String> listTemp = Arrays.asList(s.split(","));
- List<String> 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<String> listTemp = Arrays.asList(s.split(","));
- List<String> 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<List<Float>> 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<Float> list : bmsCellVoltList) {
- if (list.size() > maxVoltageSize) {
- maxVoltageSize = list.size();
- }
- }
- for (List<Float> 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<BaseExportExcelVo> maxVoltageList = new ArrayList<>();
- //最低电压
- List<BaseExportExcelVo> minVoltageList = new ArrayList<>();
- //最高温度
- List<BaseExportExcelVo> cellMaxTempList = new ArrayList<>();
- //最低温度
- List<BaseExportExcelVo> cellMinTempList = new ArrayList<>();
- //总电压
- List<BaseExportExcelVo> packVoltageList = new ArrayList<>();
- //总电流
- List<BaseExportExcelVo> packCrntList = new ArrayList<>();
- //压差
- List<BaseExportExcelVo> voltageDifferenceList = new ArrayList<>();
- //SOC
- List<BaseExportExcelVo> packSocList = new ArrayList<>();
- //单体电压
- List<BaseExportExcelStringVo> voltVoList = new ArrayList<>();
- //绝缘电阻
- List<BaseExportExcelVo> vehSpdList = new ArrayList<>();
- List<List<?>> indexList = new ArrayList<>();
- List<List<String>> headVoltList = new ArrayList<>();
- List<List<String>> cellVoltObjectDiff = new ArrayList<>();
- // 输出流
- OutputStream outputStream = null;
- List<FlinkData> 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<String> result = Arrays.asList(split);
- cellVoltObjectDiff.add(result);
- });
- String[] split = voltVoList.get(0).getData().trim().split(",");
- lenVolt = split.length;
- }
- }
- List<String> timeList = Arrays.asList("日期时间");
- headVoltList.add(timeList);
- for (int i = 1; i <= lenVolt; i++) {
- List<String> cellHeadList = Arrays.asList("cell-" + i);
- headVoltList.add(cellHeadList);
- }
- // 多sheel导出
- List<String> 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<BaseCycleChartVo>
- */
- @Override
- public BehaviorAnalysisVo getBehaviorAnalysis(String vin) throws SQLException {
- BehaviorAnalysisVo vo = new BehaviorAnalysisVo();
- List<CarPowerVo> carPowerVoList = getCarPowerFlinkData(vin);
- //计算最后一次放电详情
- setLastCycleChartVo(carPowerVoList, vo);
- //计算历史用电分布
- vo.setHistoryCycleChartVoList(getCycleChartList(carPowerVoList));
- return vo;
- }
- /**
- * 计算最后一次放电详情
- *
- * @param carPowerVoList 数据
- * @param vo 参数
- */
- private void setLastCycleChartVo(List<CarPowerVo> carPowerVoList, BehaviorAnalysisVo vo) {
- List<BaseCycleChartFloatVo> lastCycleChartVoList = new ArrayList<>();
- if (!CollectionUtils.isEmpty(carPowerVoList)) {
- List<CarPowerVo> 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<BaseCycleChartFloatVo>
- */
- private List<BaseCycleChartFloatVo> getCycleChartList(List<CarPowerVo> voList) {
- List<BaseCycleChartFloatVo> 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<com.hz.business.domain.FlinkData>
- */
- private List<CarPowerVo> getCarPowerFlinkData(String vin) throws SQLException {
- List<CarPowerVo> 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<Map<String, Object>> getFlinkMapList(String tableName, String resultId) throws SQLException {
- List<Map<String, Object>> 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<com.hz.business.vo.CarPowerVo>
- */
- private static List<CarPowerVo> convertCarPowerVoList(ResultSet rs) {
- List<CarPowerVo> carPowerVoList = new ArrayList();
- try {
- List<Map<String, Object>> mapList = new ArrayList();
- ResultSetMetaData md = rs.getMetaData();
- int columnCount = md.getColumnCount();
- while (rs.next()) {
- Map<String, Object> 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<CarPowerVo> 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<ElectricQuantity>()
- .select("date_info")
- .last(" limit 1 ")
- .orderByDesc("id")
- .eq("is_delete", 0));
- if (one == null
- || (one.getDateInfo() != null && !one.getDateInfo().equals(dateStr))) {
- //计算当日装机总量
- List<Map<String, Object>> mapList = batteryMapper.calTotalElectricQuantity();
- if (mapList.size() > 0) {
- List<QuantityItemVo> 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<KilometreCount>()
- .select("date_info")
- .last("limit 1")
- .orderByDesc("id")
- .eq("is_delete", 0));
- if (kilometreCount == null || (kilometreCount.getDateInfo() != null && !kilometreCount.getDateInfo().equals(dateStr))) {
- List<KilometreCountVo> 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<SohItemQuantity>()
- // .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<Battery> 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<SohOdo>()
- .select("date_info")
- .last(" limit 1 ")
- .orderByDesc("id")
- .eq("is_delete", 0));
- if (sohOdo == null
- || (sohOdo.getDateInfo() != null && !sohOdo.getDateInfo().equals(dateStr))) {
- List<SohMileageVo> sohMileageVoList = new ArrayList<>();
- List<Map<String, Object>> mapList = batteryMapper.getSohMileageData();
- if (!CollectionUtils.isEmpty(mapList)) {
- List<SohOdoVo> 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<String, Long> 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<Long> 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<QuantityItemDateStaticVo> 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<QuantityItemDateStaticVo> 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<TagDto> dtoList = new ArrayList<>();
- if (StringUtils.isNotBlank(dto.getBatchId())) {
- List<String> 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<Long> idSet = new HashSet<>();
- dtoList.forEach(o -> idSet.add(o.getBatteryId()));
- List<BatteryTag> batteryTagList = new ArrayList<>();
- if (idSet.size() > 0) {
- batteryTagList = batteryTagMapper.selectList(new LambdaQueryWrapper<BatteryTag>()
- .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<String> list = Arrays.asList(o.getChildTagList().split(","));
- List<String> 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<Battery> packCodeEntitys = baseMapper.selectList(new LambdaQueryWrapper<Battery>().select(Battery::getPackModelCode).groupBy(Battery::getPackModelCode));
- //获取algo_adjustable_param中全部algo_id
- List<ModelAdjustableParamEntity> algoIdEntitys = adjustableParamEntityMapper.selectList(new LambdaQueryWrapper<ModelAdjustableParamEntity>().select(ModelAdjustableParamEntity::getAlgoId).groupBy(ModelAdjustableParamEntity::getAlgoId));
- //获取到的pack,algo_id存入set
- Set<String> packCodeList = packCodeEntitys.stream().map(Battery::getPackModelCode).collect(Collectors.toSet());
- Set<Long> algoIdSet = algoIdEntitys.stream().map(ModelAdjustableParamEntity::getAlgoId).collect(Collectors.toSet());
- //遍历全部的algo_id
- algoIdSet.forEach(id -> {
- //根据algo_id查询对应algo_id绑定的pack号
- List<ModelAdjustableParamEntity> getPacksByIdEntitys = adjustableParamEntityMapper.selectList(new LambdaQueryWrapper<ModelAdjustableParamEntity>()
- .select(ModelAdjustableParamEntity::getAlgoId)
- .select(ModelAdjustableParamEntity::getPackCode)
- .eq(ModelAdjustableParamEntity::getAlgoId, id));
- //获取到对应algo_id绑定的pack存入set
- Set<String> packsSet = getPacksByIdEntitys.stream().map(ModelAdjustableParamEntity::getPackCode).collect(Collectors.toSet());
- //收集t_battery中存在,algo_adjustable_param不存在的pack型号
- List<String> 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<SohItemQuantity> sohItemQuantities = sohMapper.selectList(new QueryWrapper<SohItemQuantity>()
- .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<Battery> 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);
- }
- });
- });
- }
- }
- }
|