DeviceInfoServiceImpl.java 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  1. package com.xy.service;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollUtil;
  4. import cn.hutool.core.collection.ListUtil;
  5. import cn.hutool.core.date.DatePattern;
  6. import cn.hutool.core.date.DateTime;
  7. import cn.hutool.core.date.DateUtil;
  8. import cn.hutool.core.map.MapUtil;
  9. import cn.hutool.core.text.StrBuilder;
  10. import cn.hutool.core.util.BooleanUtil;
  11. import cn.hutool.core.util.NumberUtil;
  12. import cn.hutool.core.util.ObjectUtil;
  13. import cn.hutool.core.util.StrUtil;
  14. import cn.hutool.json.JSONUtil;
  15. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  16. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  17. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  18. import com.baomidou.mybatisplus.core.metadata.IPage;
  19. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  20. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  21. import com.xy.collections.list.JArrayList;
  22. import com.xy.collections.list.JList;
  23. import com.xy.collections.map.JMap;
  24. import com.xy.config.DeviceThreadPoolConfig;
  25. import com.xy.consts.DictConsts;
  26. import com.xy.device.*;
  27. import com.xy.dto.*;
  28. import com.xy.dto.api.biz.ContainerAddDTO;
  29. import com.xy.dto.be.MercDto;
  30. import com.xy.dto.common.MercPlaceDto;
  31. import com.xy.dto.device.DeviceQueryDTO;
  32. import com.xy.dto.device.DeviceRegDTO;
  33. import com.xy.entity.*;
  34. import com.xy.enums.FileExportType;
  35. import com.xy.error.CommRuntimeException;
  36. import com.xy.mapper.DeviceInfoMapper;
  37. import com.xy.mapper.entity.DeviceInfoQueryPage;
  38. import com.xy.service.be.MercFeignService;
  39. import com.xy.service.common.MercPlaceService;
  40. import com.xy.service.common.MercRegionService;
  41. import com.xy.sys.EnumDataClearSize;
  42. import com.xy.util.ExcelUtils;
  43. import com.xy.utils.*;
  44. import com.xy.utils.Enum.AlgorithmTypeEnum;
  45. import com.xy.utils.enums.DeviceActiveStateEnum;
  46. import com.xy.utils.enums.DeviceLockState;
  47. import com.xy.utils.enums.DeviceNetSateType;
  48. import com.xy.utils.enums.DeviceTypeEnum;
  49. import com.xy.vo.DeviceQueryVO;
  50. import io.swagger.annotations.Api;
  51. import io.swagger.annotations.ApiOperation;
  52. import jodd.introspector.MapperFunction;
  53. import lombok.RequiredArgsConstructor;
  54. import lombok.extern.slf4j.Slf4j;
  55. import org.springframework.stereotype.Service;
  56. import org.springframework.transaction.annotation.Transactional;
  57. import org.springframework.validation.annotation.Validated;
  58. import org.springframework.web.bind.annotation.PostMapping;
  59. import org.springframework.web.bind.annotation.RequestBody;
  60. import javax.servlet.http.HttpServletResponse;
  61. import javax.validation.Valid;
  62. import java.io.IOException;
  63. import java.math.BigDecimal;
  64. import java.time.LocalDateTime;
  65. import java.util.*;
  66. import java.util.stream.Collectors;
  67. import static com.xy.utils.PlusBeans.*;
  68. /**
  69. * <p>
  70. * 设备-信息 服务实现类
  71. * </p>
  72. *
  73. * @author lijin
  74. * @since 2022-12-23
  75. */
  76. @Slf4j
  77. @Service
  78. @RequiredArgsConstructor
  79. @Api(tags = "设备-信息")
  80. public class DeviceInfoServiceImpl extends ServiceImpl<DeviceInfoMapper, DeviceInfo> implements DeviceInfoService {
  81. private final CloudWalkApiService cloudWalkApiService;
  82. private final AlgorithmService algorithmService;
  83. private final CountApiService countApiService;
  84. private final TyApiService tyApiService;
  85. /**
  86. * 质检商户code
  87. */
  88. public static final String QA_MERC_CODE = "10001";
  89. private final MercFeignService mercFeignService;
  90. private final DeviceSysinfoServiceImpl deviceSysinfoService;
  91. private final DeviceStatusServiceImpl deviceStatusService;
  92. private final DeviceRegisterServiceImpl deviceRegisterService;
  93. private final DeviceEventMsgServiceImpl deviceEventMsgService;
  94. private final DeviceDataServiceImpl deviceDataService;
  95. private final DeviceTempRecordsServiceImpl deviceTempRecordsService;
  96. private final DeviceNetRecordServiceImpl deviceNetRecordService;
  97. private final GoodsDeviceService goodsDeviceService;
  98. private final FileExportService fileExportService;
  99. private final RedisService<String> redisService;
  100. private final GoodsService goodsService;
  101. private final AlipayDeviceService alipayDeviceService;
  102. private final String keyPrefix = "device:history:";
  103. private final MercRegionService mercRegionService;
  104. private final DeviceAlgorithmChargingServiceImpl deviceAlgorithmChargingService;
  105. private final MercPlaceService mercPlaceService;
  106. @Override
  107. @ApiOperation("设备列表-管理员")
  108. public R<List<DeviceInfoDto.ListByAdminName>> listByAdminName(@RequestBody @Validated DeviceInfoDto.GroupByAdminNameDto dto) {
  109. String noAdmin = "未分配管理员";
  110. List<DeviceInfoDto.ListByAdminName> deviceInfoList = baseMapper.listByAdminName(dto);
  111. deviceInfoList.forEach(i -> {
  112. SysDictRedis dictDeviceType = SysDictUtils.get(DictConsts.DEVICE_TYPE, String.valueOf(i.getDeviceType()));
  113. i.setDeviceTypeName(dictDeviceType.getMsg());
  114. if (!Emptys.check(i.getDeviceName())) {
  115. i.setDeviceName("");
  116. }
  117. });
  118. //没有管理员的的设置默认值
  119. deviceInfoList.stream().filter(s -> s.getAdminName() == null).forEach(s -> s.setAdminName(noAdmin));
  120. return R.ok(deviceInfoList);
  121. }
  122. //@Override
  123. @ApiOperation("设备分页-管理员")
  124. @Override
  125. public R<PageBean<DeviceInfoDto.ListByAdminName>> pageByAdminName(@RequestBody @Validated DeviceInfoDto.PageByAdminNameDto dto) {
  126. PageBean page = dto.getPage();
  127. String noAdmin = "未分配管理员";
  128. IPage<DeviceInfoDto.ListByAdminName> deviceInfoList = baseMapper.pageByAdminName(toIPage(page), dto);
  129. deviceInfoList.getRecords().forEach(i -> {
  130. SysDictRedis dictDeviceType = SysDictUtils.get(DictConsts.DEVICE_TYPE, String.valueOf(i.getDeviceType()));
  131. i.setDeviceTypeName(dictDeviceType.getMsg());
  132. if (!Emptys.check(i.getDeviceName())) {
  133. i.setDeviceName("");
  134. }
  135. });
  136. //没有管理员的的设置默认值
  137. deviceInfoList.getRecords().stream().filter(s -> s.getAdminName() == null).forEach(s -> s.setAdminName(noAdmin));
  138. return R.ok(toPageBean(DeviceInfoDto.ListByAdminName.class, deviceInfoList));
  139. }
  140. @Override
  141. @ApiOperation("设备分组-管理员")
  142. public R<List<DeviceInfoDto.GroupByAdminNameVo>> groupByAdminName(@RequestBody @Validated DeviceInfoDto.GroupByAdminNameDto dto) {
  143. String noAdmin = "未分配管理员";
  144. List<DeviceInfoDto.ListByAdminName> deviceInfoList = listByAdminName(dto).getData();
  145. //根据管理员名字分组
  146. Map<String, List<DeviceInfoDto.ListByAdminName>> deviceMap = deviceInfoList.stream().collect(Collectors.groupingBy(DeviceInfoDto.ListByAdminName::getAdminName));
  147. List<DeviceInfoDto.GroupByAdminNameVo> list = new ArrayList<>();
  148. //不包含未分配管理员的
  149. deviceMap.forEach(
  150. (k, i) -> {
  151. DeviceInfoDto.GroupByAdminNameVo vo = new DeviceInfoDto.GroupByAdminNameVo();
  152. if (!noAdmin.equals(k)) {
  153. vo.setAdminName(k)
  154. .setDeviceNum(i.size())
  155. .setDeviceInfos(i);
  156. list.add(vo);
  157. }
  158. }
  159. );
  160. //包含分配管理员的
  161. List<DeviceInfoDto.ListByAdminName> noAdminNamesList = deviceMap.get(noAdmin);
  162. if (Emptys.check(noAdminNamesList)) {
  163. DeviceInfoDto.GroupByAdminNameVo vo = new DeviceInfoDto.GroupByAdminNameVo();
  164. vo.setAdminName(noAdmin)
  165. .setDeviceNum(noAdminNamesList.size())
  166. .setDeviceInfos(noAdminNamesList);
  167. list.add(vo);
  168. }
  169. return R.ok(list);
  170. }
  171. @PostMapping("eventList")
  172. @ApiOperation("根据事件编码查询设备")
  173. public R<PageBean<DeviceInfoDto.EventListVo>> eventList(@RequestBody @Validated DeviceInfoDto.EventList eventList) {
  174. String countAs = "id";
  175. QueryWrapper<DeviceEventMsg> queryWrapper = new QueryWrapper<DeviceEventMsg>()
  176. .select(LambdaUtils.getUnderlineCaseName(DeviceEventMsg::getDeviceId) + " as " + LambdaUtils.getProperty(DeviceEventMsg::getDeviceId), "count(*) as " + countAs)
  177. .eq(LambdaUtils.getUnderlineCaseName(DeviceEventMsg::getCode), eventList.getCode())
  178. .between(LambdaUtils.getUnderlineCaseName(DeviceEventMsg::getCreateTime), eventList.getBeginTime(), eventList.getEndTime())
  179. .groupBy(LambdaUtils.getUnderlineCaseName(DeviceEventMsg::getDeviceId))
  180. .last("HAVING " + countAs + " >= " + eventList.getSize());
  181. IPage<DeviceEventMsg> iPage = deviceEventMsgService.page(toIPage(eventList.getPage()), queryWrapper);
  182. PageBean<DeviceInfoDto.EventListVo> pageBean = new PageBean<DeviceInfoDto.EventListVo>()
  183. .setSize(iPage.getSize())
  184. .setCurrent(iPage.getCurrent())
  185. .setTotal(iPage.getTotal());
  186. List<DeviceEventMsg> list = iPage.getRecords();
  187. if (!Emptys.check(list)) {
  188. return R.ok(pageBean);
  189. }
  190. List<DeviceInfo> deviceInfos = listByIds(new JArrayList<>(list).getProperty(DeviceEventMsg::getDeviceId));
  191. List<DeviceInfoDto.EventListVo> eventListVos = copy(DeviceInfoDto.EventListVo.class, deviceInfos);
  192. List<DeviceInfoDto.EventListVo> builder = copy(eventListVos)
  193. .target(list, DeviceInfoDto.EventListVo::getDeviceId, DeviceInfoDto.EventListVo::getSize, DeviceEventMsg::getDeviceId, DeviceEventMsg::getId)
  194. .builder();
  195. return R.ok(pageBean.setRecords(builder));
  196. }
  197. @ApiOperation("拓元算法设备列表")
  198. @PostMapping("tyDeviceList")
  199. public R<PageBean<DeviceInfoDto.Vo>> tyDeviceList(@RequestBody @Validated DeviceInfoDto.TyDeviceDTO dto) {
  200. PageBean pageBean = dto.getPage();
  201. String searchKey = dto.getSearchKey();
  202. Integer thirdStatus = dto.getThirdStatus();
  203. List<String> statusList = new ArrayList<>();
  204. //1待审核,2已审核
  205. if (thirdStatus != null && thirdStatus.intValue() == 1) {
  206. statusList = CollUtil.newArrayList("1000", "2000", "3000", "5000");
  207. }
  208. // 2已审核 4000: 设备登记成功
  209. if (thirdStatus != null && thirdStatus.intValue() == 2) {
  210. statusList.add("4000");
  211. }
  212. LambdaQueryWrapper<DeviceInfo> lqw = new MybatisPlusQuery().eqWrapper(dto, DeviceInfo.class)
  213. .build();
  214. lqw.eq(DeviceInfo::getAlgorithmId, AlgorithmTypeEnum.TY.getId());
  215. lqw.in(CollUtil.isNotEmpty(statusList), DeviceInfo::getThirdStatus, statusList);
  216. lqw.and(StrUtil.isNotEmpty(searchKey), wrapper -> wrapper
  217. .eq(DeviceInfo::getDeviceId, searchKey)
  218. .or()
  219. .likeRight(DeviceInfo::getDeviceName, searchKey));
  220. IPage<DeviceInfo> iPage = page(toIPage(pageBean), lqw);
  221. List<DeviceInfo> records = iPage.getRecords();
  222. if (CollUtil.isNotEmpty(records)) {
  223. records.forEach(r -> {
  224. Long deviceId = r.getDeviceId();
  225. /**
  226. * 请求状态码。
  227. * 1000: 未知的设备CPUID
  228. * 2000: 设备登记 审批中
  229. * 3000: 设备登记已拒绝
  230. * 4000: 设备登记成功
  231. * 5000: 设备已禁⽤
  232. */
  233. String tyStatus = r.getThirdStatus();
  234. if (!"4000".equals(tyStatus)) {
  235. //未登记成功的需要实时查询
  236. //查询登记设备
  237. DeviceQueryVO deviceQueryVO = tyApiService.deviceQuery(new DeviceQueryDTO().setCpuId(String.valueOf(deviceId)));
  238. Integer status = deviceQueryVO.getStatus();
  239. String message = deviceQueryVO.getMessage();
  240. r.setThirdStatus(String.valueOf(status));
  241. r.setThirdResult(message);
  242. updateById(r);
  243. }
  244. });
  245. }
  246. PageBean<DeviceInfoDto.Vo> voPageBean = toPageBean(DeviceInfoDto.Vo.class, iPage);
  247. return R.ok(voPageBean);
  248. }
  249. /**
  250. * 商户设备列表分页-穿梭框用
  251. *
  252. * @param dto
  253. * @return {@link R}<{@link List}<{@link DeviceInfoDto.MyDeviceInfo}>>
  254. */
  255. public R<PageBean<DeviceInfoDto.MyDeviceInfo>> myDeviceList(@RequestBody @Validated DeviceInfoDto.MyDeviceDTO dto) {
  256. PageBean pageBean = dto.getPage();
  257. String searchKey = dto.getSearchKey();
  258. Long mercId = dto.getMercId();
  259. Integer type = dto.getType();
  260. Long strategyId = dto.getStrategyId();
  261. GoodsDeviceDto.SelectList selectList = new GoodsDeviceDto.SelectList();
  262. //selectList.setMercId(mercId).setPriceStrategyId(strategyId);
  263. List<GoodsDeviceDto.Vo> goodsDevices = R.feignCheckData(goodsDeviceService.list(selectList));
  264. if (type == 2 && CollUtil.isEmpty(goodsDevices)) {
  265. //右侧已选的
  266. return R.ok(new PageBean<>());
  267. }
  268. List<Long> deviceIds = goodsDevices.stream().map(GoodsDeviceDto.Vo::getDeviceId).collect(Collectors.toList());
  269. LambdaQueryWrapper<DeviceInfo> lqw = new MybatisPlusQuery().eqWrapper(dto, DeviceInfo.class)
  270. .build();
  271. lqw.in(type == 2 && CollUtil.isNotEmpty(deviceIds), DeviceInfo::getDeviceId, deviceIds);
  272. //左侧排除掉已关联的
  273. lqw.notIn(type == 1 && CollUtil.isNotEmpty(deviceIds), DeviceInfo::getDeviceId, deviceIds);
  274. lqw.and(StrUtil.isNotEmpty(searchKey), wrapper -> wrapper
  275. .eq(DeviceInfo::getDeviceId, searchKey)
  276. .or()
  277. .likeRight(DeviceInfo::getDeviceName, searchKey));
  278. IPage<DeviceInfo> iPage = page(toIPage(pageBean), lqw);
  279. return R.ok(toPageBean(DeviceInfoDto.MyDeviceInfo.class, iPage));
  280. }
  281. @ApiOperation("点位设备数量查询")
  282. @Override
  283. public R<List<DeviceInfoDto.PlaceDeviceNumVo>> placeDeviceNum(@RequestBody @Validated DeviceInfoDto.PlaceDeviceNumDto dto) {
  284. return R.ok(baseMapper.placeDeviceNum(dto));
  285. }
  286. @Override
  287. @ApiOperation("设备列表带卡包数")
  288. public R<PageBean<DeviceInfoDto.AlgorithmChargingVo>> algorithmChargingDevice(@RequestBody @Validated DeviceInfoDto.AlgorithmCharging algorithmCharging) {
  289. PageBean pageBean = algorithmCharging.getPage();
  290. //查询设备
  291. Integer value = SysDictUtils.getValue(EnumDeviceActiveStatus.Code.CODE.getCode(), EnumDeviceActiveStatus.N_1.getCode(), Integer.class);
  292. LambdaUpdateWrapper<DeviceInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<DeviceInfo>()
  293. .eq(DeviceInfo::getMercId, algorithmCharging.getMercId())
  294. .eq(DeviceInfo::getActiveState, value)
  295. .in(Emptys.check(algorithmCharging.getDeviceIds()), DeviceInfo::getDeviceId, algorithmCharging.getDeviceIds())
  296. .orderByDesc(DeviceInfo::getCreateTime);
  297. IPage<DeviceInfo> page = page(toIPage(pageBean), lambdaUpdateWrapper);
  298. PageBean<DeviceInfoDto.AlgorithmChargingVo> algorithmChargingVoPageBean = toPageBean(DeviceInfoDto.AlgorithmChargingVo.class, page);
  299. List<DeviceInfoDto.AlgorithmChargingVo> algorithmChargingVos = algorithmChargingVoPageBean.getRecords();
  300. if (!Emptys.check(algorithmChargingVos)) {
  301. return R.ok(algorithmChargingVoPageBean);
  302. }
  303. //查询卡包数量
  304. List<DeviceAlgorithmChargingDto.CountVo> data = deviceAlgorithmChargingService.count(new DeviceAlgorithmChargingDto.Count()
  305. .setDeviceIds(new JArrayList<>(algorithmChargingVos).getProperty(DeviceInfoDto.AlgorithmChargingVo::getDeviceId))
  306. .setMercId(algorithmCharging.getMercId())
  307. ).getData();
  308. JMap<Long, DeviceAlgorithmChargingDto.CountVo> cover = new JArrayList<>(data).toMap(DeviceAlgorithmChargingDto.CountVo::getDeviceId).cover();
  309. algorithmChargingVos.forEach(algorithmChargingVo -> {
  310. DeviceAlgorithmChargingDto.CountVo countVo = cover.get(algorithmChargingVo.getDeviceId());
  311. Beans.copy(algorithmChargingVo, countVo);
  312. });
  313. return R.ok(algorithmChargingVoPageBean);
  314. }
  315. @Override
  316. @ApiOperation("设备在线数查询")
  317. public R<Map<Long, DeviceInfoDto.NetStateCountVo>> netStateCount(DeviceInfoDto.NetStateCountDto dto) {
  318. List<DeviceInfoDto.NetStateCount> netStateCountList = baseMapper.netStateCount(dto.getMercIdList());
  319. List<Long> netStateCountMercList = netStateCountList.stream().map(DeviceInfoDto.NetStateCount::getMercId).distinct().collect(Collectors.toList());
  320. Map<Long, DeviceInfoDto.NetStateCountVo> voMap = new HashMap<>();
  321. List<Long> mercIdList = Emptys.check(dto.getMercIdList()) ? dto.getMercIdList() : netStateCountMercList;
  322. if (!Emptys.check(mercIdList)) {
  323. return R.ok();
  324. }
  325. for (Long mercId : mercIdList) {
  326. Integer count = 0;
  327. Integer offline = 0;
  328. DeviceInfoDto.NetStateCountVo vo = new DeviceInfoDto.NetStateCountVo().setMercId(mercId);
  329. for (DeviceInfoDto.NetStateCount i : netStateCountList) {
  330. if (Objects.equals(i.getMercId(), mercId)) {
  331. count += i.getCount();
  332. if ("1".equals(i.getNetState())) {
  333. vo.setOnLineCount(i.getCount());
  334. } else {
  335. offline += i.getCount();
  336. }
  337. }
  338. }
  339. vo.setCount(count).setOffLineCount(offline);
  340. voMap.put(mercId, vo);
  341. }
  342. return R.ok(voMap);
  343. }
  344. @Override
  345. @ApiOperation("分页")
  346. public R<PageBean<DeviceInfoDto.Vo>> pageSingle(DeviceInfoDto.PageSingle dto) {
  347. PageBean pageBean = dto.getPage();
  348. LambdaQueryWrapper<DeviceInfo> lqw = new MybatisPlusQuery().eqWrapper(dto, DeviceInfo.class)
  349. .build();
  350. IPage<DeviceInfo> iPage = page(toIPage(pageBean), lqw);
  351. return R.ok(toPageBean(DeviceInfoDto.Vo.class, iPage));
  352. }
  353. @Override
  354. @ApiOperation("对象查询")
  355. public R<DeviceInfoDto.Vo> obj(DeviceInfoDto.Obj obj) {
  356. //设备信息
  357. LambdaQueryWrapper<DeviceInfo> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(obj, DeviceInfo.class).build();
  358. List<DeviceInfo> list = list(lambdaQueryWrapper);
  359. if (!Emptys.check(list)) {
  360. return R.ok();
  361. }
  362. DeviceInfoDto.Vo deviceInfo = copy(DeviceInfoDto.Vo.class, list.get(0));
  363. int num = 0;
  364. if (obj.getIsSysinfo()) {
  365. num++;
  366. }
  367. if (obj.getIsStatus()) {
  368. num++;
  369. }
  370. if (obj.getIsRegister()) {
  371. num++;
  372. }
  373. if (num > 0) {
  374. ThreadPoolUtils.Execute execute = ThreadPoolUtils.excPoll(DeviceThreadPoolConfig.DEVICE_COMMON_POLL, num);
  375. if (obj.getIsSysinfo()) {
  376. execute.execute(() -> {
  377. //系统信息
  378. DeviceSysinfoDto.Vo deviceSysinfo = deviceSysinfoService.get(new DeviceSysinfoDto.Vo().setDeviceId(deviceInfo.getDeviceId())).getData();
  379. deviceInfo.setDeviceSysinfo(deviceSysinfo);
  380. });
  381. }
  382. if (obj.getIsStatus()) {
  383. execute.execute(() -> {
  384. //状态信息
  385. DeviceStatusDto.Vo deviceStatus = deviceStatusService.obj(new DeviceStatusDto.Vo().setDeviceId(deviceInfo.getDeviceId())).getData();
  386. deviceInfo.setDeviceStatus(deviceStatus);
  387. });
  388. }
  389. if (obj.getIsRegister()) {
  390. execute.execute(() -> {
  391. //注册信息
  392. DeviceRegisterDto.Vo deviceRegister = deviceRegisterService.obj(new DeviceRegisterDto.Vo().setDeviceId(deviceInfo.getDeviceId())).getData();
  393. deviceInfo.setDeviceRegister(deviceRegister);
  394. });
  395. }
  396. execute.end();
  397. }
  398. return R.ok(deviceInfo);
  399. }
  400. @ApiOperation("反显设备名称")
  401. @Override
  402. public R<Map<Long, String>> getDeviceNameList(DeviceInfoDto.DeviceIdDto dto) {
  403. LambdaQueryWrapper<DeviceInfo> lqw = new LambdaQueryWrapper<DeviceInfo>()
  404. .in(DeviceInfo::getDeviceId, dto.getDeviceId())
  405. .select(DeviceInfo::getDeviceId, DeviceInfo::getDeviceName);
  406. List<DeviceInfo> deviceInfoList = list(lqw);
  407. return R.ok(deviceInfoList.stream().collect(Collectors.toMap(DeviceInfo::getDeviceId, i -> Optional.ofNullable(i.getDeviceName()).orElse(""))));
  408. }
  409. @Override
  410. public R<DeviceSysinfoDto.Vo> getDeviceSysinfo(DeviceSysinfoDto.DeviceSysInfo dto) {
  411. String dtoDeviceSN = dto.getDeviceSN();
  412. DeviceSysinfo one = deviceSysinfoService.getOne(Wrappers.<DeviceSysinfo>lambdaQuery().eq(DeviceSysinfo::getDeviceSn, dtoDeviceSN));
  413. return R.ok(BeanUtil.copyProperties(one, DeviceSysinfoDto.Vo.class));
  414. }
  415. @Override
  416. @ApiOperation("设备访问历史添加")
  417. public R history(DeviceInfoDto.Obj obj) {
  418. //获取字典
  419. SysDictRedis sysDictRedis = SysDictUtils.get(EnumDataClearSize.Code.CODE.getCode(), EnumDataClearSize.DEVICE_HISTORY_TWIG.getCode());
  420. Integer value = Integer.valueOf(sysDictRedis.getValue());
  421. //获取redis
  422. String key = keyPrefix + AuthorizeUtils.getLoginId(Long.class);
  423. List<String> list = redisService.getList(key);
  424. list.add(0, String.valueOf(obj.getDeviceId()));
  425. //去重
  426. List<String> redisList = new ArrayList<>();
  427. JList<String> comparing = new JArrayList<>(list).comparing();
  428. if (comparing.size() > value) {
  429. for (int i = 0; i < value; i++) {
  430. redisList.add(comparing.get(i));
  431. }
  432. } else {
  433. redisList = comparing;
  434. }
  435. redisService.removeList(key);
  436. redisService.setList(key, redisList);
  437. return R.ok();
  438. }
  439. @Override
  440. @ApiOperation("开门检测")
  441. public R<DeviceInfoDto.Vo> checkOpenDoor(DeviceInfoDto.Obj obj) {
  442. DeviceInfoDto.Vo deviceInfo = obj(new DeviceInfoDto.Obj()
  443. .setDeviceId(obj.getDeviceId())
  444. .setIsStatus(true)
  445. ).getData();
  446. if (deviceInfo == null) {
  447. return R.fail("设备不存在");
  448. }
  449. DeviceStatusDto.Vo deviceStatus = deviceInfo.getDeviceStatus();
  450. SysDictRedis qualitySets = SysDictUtils.get(EnumQualityMercSets.Code.CODE.getCode(), EnumQualityMercSets.MERC_CODE.getCode());
  451. //设备当前商户是质检时不检查
  452. if (!qualitySets.getValue().equals(deviceInfo.getMercCode())) {
  453. check(deviceInfo.getActiveState(), 2, "设备未激活");
  454. check(deviceInfo.getFreezeStatus(), 2, "设备已冻结");
  455. check(obj.getDoor() != null && obj.getDoor() == 1 ? deviceStatus.getLockStateR() : deviceStatus.getLockStateL(), 2, "设备已锁机");
  456. check(deviceStatus.getIsPay(), Boolean.FALSE, "设备不可交易");
  457. check(deviceInfo.getBusyState(), 2, "设备已停运");
  458. SysDictRedis sysDictRedis = SysDictUtils.get(EnumDeviceFaultLevelPayThreshold.Code.CODE.getCode(), EnumDeviceFaultLevelPayThreshold.NOT_PAY.getCode());
  459. check(deviceInfo.getFaultLevel(), sysDictRedis.getValue(), "设备故障");
  460. }
  461. check(deviceStatus.getNetState(), 2, "设备已离线");
  462. check(obj.getDoor() != null && obj.getDoor() == 1 ? deviceStatus.getDoorStateR() : deviceStatus.getDoorStateL(), 1, "设备正在使用中,请稍后");
  463. return R.ok(deviceInfo);
  464. }
  465. @PostMapping("historyList")
  466. @ApiOperation("设备访问历史查询")
  467. public R<List<DeviceInfoDto.Vo>> historyList() {
  468. //获取redis
  469. String key = keyPrefix + AuthorizeUtils.getLoginId(Long.class);
  470. List<String> deviceIds = redisService.getList(key);
  471. if (!Emptys.check(deviceIds)) {
  472. return R.ok();
  473. }
  474. //查询数据库
  475. List<DeviceInfo> list = list(new LambdaQueryWrapper<DeviceInfo>().in(DeviceInfo::getDeviceId, deviceIds));
  476. return R.ok(copy(DeviceInfoDto.Vo.class, list));
  477. }
  478. @ApiOperation("修改")
  479. @PostMapping("update")
  480. public R update(@RequestBody @Validated DeviceInfoDto.Update update) {
  481. DeviceInfo deviceInfo = copy(DeviceInfo.class, update)
  482. .setUpdateTime(LocalDateTime.now());
  483. updateById(deviceInfo);
  484. Long deviceId = deviceInfo.getDeviceId();
  485. DeviceInfoDto.Vo device = R.feignCheckData(this.obj(new DeviceInfoDto.Obj().setDeviceId(deviceId).setIsSysinfo(true)));
  486. Long algorithmId = update.getAlgorithmId();
  487. if (algorithmId != null && AlgorithmTypeEnum.CLOUD.getId() == algorithmId) {
  488. //云从算法
  489. boolean b = cloudWalkApiService.checkDeviceExist(deviceId);
  490. if (!b) {
  491. //货柜不存在,新增
  492. cloudWalkApiService.containerAdd(new ContainerAddDTO().setContainerCode(String.valueOf(deviceId)));
  493. }
  494. } else if (algorithmId != null && AlgorithmTypeEnum.TY.getId() == algorithmId) {
  495. //拓元算法
  496. //查询登记设备
  497. DeviceQueryVO deviceQueryVO = tyApiService.deviceQuery(new DeviceQueryDTO().setCpuId(String.valueOf(deviceId)));
  498. Integer status = deviceQueryVO.getStatus();
  499. if (status != null && 1000 == status.intValue()) {
  500. //未知的设备CPUID,进行登记
  501. tyApiService.deviceReg(new DeviceRegDTO()
  502. .setCpuId(String.valueOf(deviceId))
  503. .setDeviceNumber(String.valueOf(deviceId))
  504. );
  505. }
  506. }
  507. Integer deviceType = device.getDeviceType();
  508. if (ObjectUtil.equals(DeviceTypeEnum.TYPE5.getCode(), deviceType)) {
  509. DeviceUpdateDTO deviceUpdateDTO = new DeviceUpdateDTO();
  510. if (StrUtil.isNotEmpty(update.getDeviceName())) {
  511. deviceUpdateDTO.setDeviceName(update.getDeviceName());
  512. }
  513. String deviceSn = device.getDeviceSysinfo().getDeviceSn();
  514. if (deviceUpdateDTO != null) {
  515. deviceUpdateDTO.setTerminalId(String.valueOf(update.getDeviceId()));
  516. deviceUpdateDTO.setBoardSn(deviceSn);
  517. alipayDeviceService.deviceUpdate(deviceUpdateDTO);
  518. }
  519. }
  520. return R.ok();
  521. }
  522. @Override
  523. @ApiOperation("批量修改")
  524. public R updateBatch(@RequestBody List<DeviceInfoDto.Update> updates) {
  525. LocalDateTime now = LocalDateTime.now();
  526. List<DeviceInfo> deviceInfos = new ArrayList<>(updates.size());
  527. updates.forEach(update -> deviceInfos.add(copy(DeviceInfo.class, update).setUpdateTime(now)));
  528. updateBatchById(deviceInfos);
  529. return R.ok();
  530. }
  531. @Override
  532. @ApiOperation("更新商户线路")
  533. public R updateLine(@RequestBody @Validated DeviceInfoDto.UpdateLine updateLine) {
  534. LambdaUpdateWrapper<DeviceInfo> luw = new LambdaUpdateWrapper<DeviceInfo>().eq(DeviceInfo::getMercId, updateLine.getMercId());
  535. //绑定线路,更换线路
  536. if (DeviceInfoDto.UPDATE.equals(updateLine.getType())) {
  537. DeviceInfo deviceInfo = new DeviceInfo();
  538. deviceInfo.setPlaceLineId(updateLine.getPlaceLineId());
  539. luw.in(DeviceInfo::getDeviceId, updateLine.getDeviceIds());
  540. baseMapper.update(deviceInfo, luw);
  541. }
  542. //删除线路
  543. if (DeviceInfoDto.DEL.equals(updateLine.getType())) {
  544. luw.eq(DeviceInfo::getPlaceLineId, updateLine.getWherePlaceLineId());
  545. luw.set(DeviceInfo::getPlaceLineId, null);
  546. baseMapper.update(null, luw);
  547. }
  548. //解绑线路 设置线路ID为null
  549. if (DeviceInfoDto.CLEAR.equals(updateLine.getType())) {
  550. luw.in(DeviceInfo::getDeviceId, updateLine.getDeviceIds());
  551. luw.set(DeviceInfo::getPlaceLineId, null);
  552. baseMapper.update(null, luw);
  553. }
  554. return R.ok();
  555. }
  556. @Override
  557. @ApiOperation("更新商户点位")
  558. public R updatePlace(@RequestBody @Validated DeviceInfoDto.UpdatePlace updatePlace) {
  559. LambdaUpdateWrapper<DeviceInfo> luw = new LambdaUpdateWrapper<DeviceInfo>().eq(DeviceInfo::getMercId, updatePlace.getMercId());
  560. //绑定点位,更换点位
  561. if (DeviceInfoDto.UPDATE.equals(updatePlace.getType())) {
  562. DeviceInfo deviceInfo = new DeviceInfo();
  563. deviceInfo.setPlaceId(updatePlace.getPlaceId());
  564. luw.in(DeviceInfo::getDeviceId, updatePlace.getDeviceIds());
  565. baseMapper.update(deviceInfo, luw);
  566. }
  567. //删除点位
  568. if (DeviceInfoDto.DEL.equals(updatePlace.getType())) {
  569. luw.eq(DeviceInfo::getPlaceId, updatePlace.getWherePlaceId());
  570. luw.set(DeviceInfo::getPlaceId, null);
  571. baseMapper.update(null, luw);
  572. }
  573. //解绑点位 设置点位ID为null
  574. if (DeviceInfoDto.CLEAR.equals(updatePlace.getType())) {
  575. luw.in(DeviceInfo::getDeviceId, updatePlace.getDeviceIds());
  576. luw.set(DeviceInfo::getPlaceId, null);
  577. baseMapper.update(null, luw);
  578. }
  579. return R.ok();
  580. }
  581. @ApiOperation("分页查询")
  582. @Override
  583. public R<PageBean<DeviceInfoDto.Vo2>> page(@RequestBody DeviceInfoDto.Page page) {
  584. return R.ok(queryPage(page));
  585. }
  586. @ApiOperation("导出设备列表")
  587. @PostMapping("exportDevices")
  588. public void exportDevices(HttpServletResponse response, @RequestBody @Valid DeviceInfoDto.Page page) throws IOException {
  589. PageBean<DeviceInfoDto.Vo2> pageBean = queryPage(page);
  590. List<DeviceInfoDto.Vo2> records = pageBean.getRecords();
  591. List<DeviceInfoDto.DeviceExcelVO> deviceExcelVOS = BeanUtil.copyToList(records, DeviceInfoDto.DeviceExcelVO.class);
  592. // 输出
  593. ExcelUtils.write(response, "设备列表.xls", "设备列表", DeviceInfoDto.DeviceExcelVO.class, deviceExcelVOS);
  594. }
  595. @ApiOperation("导出设备(异步)")
  596. @PostMapping("exportDevices/async")
  597. public void exportDevicesAsync(@RequestBody @Validated DeviceInfoDto.Page page) {
  598. PageBean<DeviceInfoDto.Vo2> pageBean = queryPage(page);
  599. List<DeviceInfoDto.Vo2> records = pageBean.getRecords();
  600. List<DeviceInfoDto.DeviceExcelVO> deviceExcelVOS = BeanUtil.copyToList(records, DeviceInfoDto.DeviceExcelVO.class);
  601. //异步导出参数封装
  602. ExcelDTO<DeviceInfoDto.DeviceExcelVO> excelDTO = new ExcelDTO<>();
  603. excelDTO.setData(deviceExcelVOS);
  604. excelDTO.setHead(DeviceInfoDto.DeviceExcelVO.class);
  605. excelDTO.setSheetName(FileExportType.DEVICE_INFO.getDescription());
  606. excelDTO.setFileExportType(FileExportType.DEVICE_INFO);
  607. //执行导出
  608. fileExportService.exportExcelAsync(excelDTO);
  609. }
  610. @PostMapping("nearbyPage")
  611. @ApiOperation("附近设备分页查询")
  612. public R<PageBean<DeviceInfoDto.Vo2>> nearbyPage(@RequestBody DeviceInfoDto.Page page) {
  613. if (!Emptys.check(page.getLon()) || !Emptys.check(page.getLat())) {
  614. throw new CommRuntimeException("经纬度不能为空");
  615. }
  616. return R.ok(queryPage(page));
  617. }
  618. @ApiOperation(value = "商户设备授权", hidden = true)
  619. @Override
  620. @Transactional(rollbackFor = Exception.class)
  621. public R<Boolean> mercDeviceAuth(DeviceInfoDto.MercDeviceAuthDto auth) {
  622. Long mercId = auth.getMercId();
  623. String mercCode = auth.getMercCode();
  624. Long algorithmId = auth.getAlgorithmId();
  625. String mercName = auth.getMercName();
  626. //商户最终设备列表
  627. List<Long> deviceIds = auth.getDeviceIds();
  628. List<DeviceInfo> devices = getDevicesByMercId(mercId);
  629. //取消商户设备授权
  630. if (CollUtil.isEmpty(deviceIds)) {
  631. if (CollUtil.isEmpty(devices)) {
  632. return R.ok(Boolean.TRUE);
  633. }
  634. }
  635. //更新商户设备授权
  636. List<DeviceInfo> deviceInfos = this.listByIds(deviceIds);
  637. List<DeviceStatus> deviceStatuses = new ArrayList<>();
  638. for (DeviceInfo deviceInfo : deviceInfos) {
  639. Integer deviceType = deviceInfo.getDeviceType();
  640. Long deviceId = deviceInfo.getDeviceId();
  641. if (ObjectUtil.equals(deviceType, DeviceTypeEnum.TYPE5.getCode())) {
  642. //支付宝设备算法
  643. algorithmId = AlgorithmTypeEnum.ALIPAY.getId();
  644. } else {
  645. //非支付宝算法
  646. if (AlgorithmTypeEnum.CLOUD.getId() == algorithmId) {
  647. //云从算法
  648. boolean b = cloudWalkApiService.checkDeviceExist(deviceId);
  649. if (!b) {
  650. //货柜不存在,新增
  651. cloudWalkApiService.containerAdd(new ContainerAddDTO().setContainerCode(String.valueOf(deviceId)));
  652. }
  653. } else if (AlgorithmTypeEnum.TY.getId() == algorithmId) {
  654. //拓元算法
  655. //查询登记设备
  656. DeviceQueryVO deviceQueryVO = tyApiService.deviceQuery(new DeviceQueryDTO().setCpuId(String.valueOf(deviceId)));
  657. Integer status = deviceQueryVO.getStatus();
  658. if (status != null && 1000 == status.intValue()) {
  659. //未知的设备CPUID,进行登记
  660. tyApiService.deviceReg(new DeviceRegDTO()
  661. .setCpuId(String.valueOf(deviceId))
  662. .setDeviceNumber(String.valueOf(deviceId))
  663. );
  664. }
  665. }
  666. }
  667. int refMercId = deviceInfo.getMercId().intValue();
  668. String refMercCode = deviceInfo.getMercCode();
  669. // 只有解绑后,才能给顶级商户授权
  670. if (refMercId != -1 && refMercId != mercId.intValue()) {
  671. StrBuilder sb = StrBuilder.create();
  672. String errMsg = sb.append("设备[")
  673. .append(deviceInfo.getDeviceId())
  674. .append("]")
  675. .append("已被商户[")
  676. .append(deviceInfo.getMercName())
  677. .append("]绑定,请先进行解绑!")
  678. .toString();
  679. //非质检商户需要进行判断,质检商户跳过
  680. if (!QA_MERC_CODE.equals(refMercCode)) {
  681. //已关联别商户
  682. return R.fail(errMsg, Boolean.FALSE);
  683. }
  684. }
  685. //绑定关系
  686. deviceInfo.setMercId(mercId).setMercCode(mercCode).setAlgorithmId(algorithmId).setMercName(mercName);
  687. //标记机器可交易
  688. DeviceStatus deviceStatus = new DeviceStatus()
  689. .setDeviceId(deviceInfo.getDeviceId())
  690. .setIsPay(true);
  691. deviceStatuses.add(deviceStatus);
  692. }
  693. saveOrUpdateBatch(deviceInfos);
  694. if (Emptys.check(deviceStatuses)) {
  695. deviceStatusService.updateBatchById(deviceStatuses);
  696. }
  697. return R.ok(Boolean.TRUE);
  698. }
  699. /**
  700. * 解绑机器 回收
  701. *
  702. * @param dto
  703. * @return
  704. */
  705. @Override
  706. public R<Boolean> unBindMercDevice(DeviceInfoDto.MercDeviceUnBindDto dto) {
  707. List<DeviceInfo> deviceInfos = this.listByIds(dto.getDeviceIds());
  708. return R.ok(removeMerRefDevicesToTopMerc(deviceInfos));
  709. }
  710. /**
  711. * 回收机器
  712. *
  713. * @param deviceInfos
  714. * @return
  715. */
  716. private Boolean removeMerRefDevicesToTopMerc(List<DeviceInfo> deviceInfos) {
  717. MercDto.Vo mercCheck = R.feignCheckData(mercFeignService.obj(new MercDto.ListDTO().setMercCode(QA_MERC_CODE)));
  718. if (CollUtil.isNotEmpty(deviceInfos)) {
  719. deviceInfos.forEach(deviceInfo -> {
  720. //回收
  721. deviceInfo.setMercId(mercCheck.getId());
  722. deviceInfo.setMercDeviceCode(StrUtil.EMPTY);
  723. deviceInfo.setMercName(mercCheck.getName());
  724. deviceInfo.setMercCode(QA_MERC_CODE);
  725. });
  726. //批量更新
  727. return updateBatchById(deviceInfos);
  728. }
  729. return Boolean.FALSE;
  730. }
  731. /**
  732. * 批量移除商户设备绑定关系
  733. *
  734. * @param deviceInfos
  735. * @return
  736. */
  737. private Boolean removeMerRefDevices(List<DeviceInfo> deviceInfos, Long parentId) {
  738. if (CollUtil.isNotEmpty(deviceInfos) && parentId != null) {
  739. deviceInfos.forEach(deviceInfo -> {
  740. //非顶级兴元商户,解绑后,机器归父商户
  741. if (parentId != 1) {
  742. MercDto.Vo mercParent = R.feignCheckData(mercFeignService.obj(new MercDto.ListDTO().setId(parentId)));
  743. if (mercParent != null) {
  744. deviceInfo.setMercId(mercParent.getId());
  745. deviceInfo.setMercName(mercParent.getName());
  746. deviceInfo.setMercCode(mercParent.getMercCode());
  747. } else {
  748. deviceInfo.setMercId(-1L);
  749. deviceInfo.setMercName(StrUtil.EMPTY);
  750. deviceInfo.setMercCode(StrUtil.EMPTY);
  751. }
  752. }
  753. //一级商户,解绑后,直接释放
  754. if (parentId == 0) {
  755. MercDto.Vo mercCheck = R.feignCheckData(mercFeignService.obj(new MercDto.ListDTO().setMercCode(QA_MERC_CODE)));
  756. if (mercCheck != null) {
  757. deviceInfo.setMercId(mercCheck.getId());
  758. deviceInfo.setMercName(mercCheck.getName());
  759. deviceInfo.setMercCode(mercCheck.getMercCode());
  760. } else {
  761. deviceInfo.setMercId(-1L);
  762. deviceInfo.setMercName(StrUtil.EMPTY);
  763. deviceInfo.setMercCode(StrUtil.EMPTY);
  764. }
  765. }
  766. });
  767. //批量更新
  768. return updateBatchById(deviceInfos);
  769. }
  770. return Boolean.FALSE;
  771. }
  772. @ApiOperation("集合查询")
  773. @Override
  774. public R<List<DeviceInfoDto.Vo>> list(DeviceInfoDto.ListDto dto) {
  775. List<DeviceInfo> list = list(new LambdaQueryWrapper<DeviceInfo>()
  776. .eq(Emptys.check(dto.getFreezeStatus()), DeviceInfo::getFreezeStatus, dto.getFreezeStatus())
  777. .in(CollUtil.isNotEmpty(dto.getDeviceIds()), DeviceInfo::getDeviceId, dto.getDeviceIds())
  778. .eq(Emptys.check(dto.getMercId()), DeviceInfo::getMercId, dto.getMercId())
  779. );
  780. return R.ok(copy(DeviceInfoDto.Vo.class, list));
  781. }
  782. @Override
  783. @ApiOperation("通用集合查询")
  784. public R<List<DeviceInfoDto.Vo>> listCommon(DeviceInfoDto.ListCommon dto) {
  785. String deviceSearch = dto.getDeviceSearch();
  786. DeviceInfoDto.Vo vo = dto.getVo();
  787. QueryWrapper<DeviceInfo> queryWrapper = new MybatisPlusQuery().eqWrapper(vo == null ? new DeviceInfoDto.Vo() : vo, DeviceInfo.class).buildQW();
  788. // List<Long> placeLineIds = dto.getPlaceLineIds();
  789. List<Long> deviceIds = dto.getDeviceIds();
  790. List<String> columnList = dto.getColumnList();
  791. // if (CollUtil.isNotEmpty(placeLineIds)) {
  792. // queryWrapper.in(LambdaUtils.getUnderlineCaseName(DeviceInfo::getPlaceLineId), placeLineIds);
  793. // }
  794. //fixed
  795. if (StrUtil.isNotEmpty(deviceSearch)) {
  796. queryWrapper.and(wrapper -> wrapper.likeRight(LambdaUtils.getUnderlineCaseName(DeviceInfo::getDeviceName), deviceSearch).or()
  797. .eq(LambdaUtils.getUnderlineCaseName(DeviceInfo::getDeviceId), deviceSearch));
  798. }
  799. if (CollUtil.isNotEmpty(columnList)) {
  800. queryWrapper.select(columnList.stream().toArray(String[]::new));
  801. }
  802. if (CollUtil.isNotEmpty(deviceIds)) {
  803. queryWrapper.in(LambdaUtils.getUnderlineCaseName(DeviceInfo::getDeviceId), deviceIds);
  804. }
  805. return R.ok(copy(DeviceInfoDto.Vo.class, list(queryWrapper)));
  806. }
  807. @Override
  808. @ApiOperation("商户设备算法列表")
  809. public R<List<Long>> mercAlgorithmIdList(DeviceInfoDto.MercAlgorithmIdListDto dto) {
  810. String algorithmIdStr = LambdaUtils.getProperty(DeviceInfo::getAlgorithmId);
  811. String mercStr = StringTools.humpToLine(LambdaUtils.getProperty(DeviceInfo::getMercId));
  812. QueryWrapper<DeviceInfo> lqw = new QueryWrapper<DeviceInfo>()
  813. .isNotNull(StringTools.humpToLine(algorithmIdStr))
  814. .eq(mercStr, dto.getMercId())
  815. .select(String.format("DISTINCT (%s) as %s", StringTools.humpToLine(algorithmIdStr), algorithmIdStr));
  816. List<Long> list = listObjs(lqw, (MapperFunction<Object, Long>) o -> (Long) o);
  817. return R.ok(list);
  818. }
  819. @Override
  820. @ApiOperation("小程序-商户设备首页统计")
  821. public R<DeviceInfoDto.MercHomeStatisticalVO> mercHomeStatistical(DeviceInfoDto.MercHomeQueryDTO dto) {
  822. Long mercId = dto.getMercId();
  823. List<Long> myDeviceIds = dto.getMyDeviceIds();
  824. //初始化数据
  825. DeviceInfoDto.MercHomeStatisticalVO mercHomeStatisticalVO = new DeviceInfoDto.MercHomeStatisticalVO()
  826. .setClosedNum(0).setOfflineNum(0)
  827. .setOnlineNum(0).setOperatingNum(0).setNeedToFillNum(0);
  828. if (CollUtil.isEmpty(myDeviceIds)) {
  829. return R.ok(mercHomeStatisticalVO);
  830. }
  831. List<DeviceInfo> mercDevices = listByIds(myDeviceIds);
  832. if (CollUtil.isEmpty(mercDevices)) {
  833. return R.ok(mercHomeStatisticalVO);
  834. }
  835. //在线、离线
  836. List<DeviceStatus> deviceStatuses = deviceStatusService.listByIds(myDeviceIds);
  837. //分组统计
  838. Map<Integer, Long> countNetstateMap = deviceStatuses.stream().collect(Collectors
  839. .groupingBy(DeviceStatus::getNetState, Collectors.counting()));
  840. Integer onlineDictValue = SysDictUtils.getValue(EnumDeviceOnlineStatus.Code.CODE.getCode(), EnumDeviceOnlineStatus.CONNECTED.getCode(), Integer.class);
  841. Integer offlineDictValue = SysDictUtils.getValue(EnumDeviceOnlineStatus.Code.CODE.getCode(), EnumDeviceOnlineStatus.DISCONNECT.getCode(), Integer.class);
  842. int onlineNum = countNetstateMap.get(onlineDictValue) == null ? 0 : countNetstateMap.get(onlineDictValue).intValue();
  843. int offlineNum = countNetstateMap.get(offlineDictValue) == null ? 0 : countNetstateMap.get(offlineDictValue).intValue();
  844. mercHomeStatisticalVO.setOnlineNum(onlineNum);
  845. mercHomeStatisticalVO.setOfflineNum(offlineNum);
  846. //锁机、未锁机
  847. Map<Integer, Long> countLockLstateMap = deviceStatuses.stream().collect(Collectors
  848. .groupingBy(DeviceStatus::getLockStateL, Collectors.counting()));
  849. Long lockLStateNum = countLockLstateMap.get(DeviceLockState.LOCK.getCode());
  850. Long unLockLStateNum = countLockLstateMap.get(DeviceLockState.UN_LOCK.getCode());
  851. mercHomeStatisticalVO.setOperatingNum(unLockLStateNum == null ? 0 : unLockLStateNum.intValue());
  852. mercHomeStatisticalVO.setClosedNum(lockLStateNum == null ? 0 : lockLStateNum.intValue());
  853. //待补货
  854. Integer deviceNum = R.feignCheckData(goodsDeviceService.countOutOfStockDevice(new GoodsDeviceDto.CountOutOfStockDevice().setMercId(mercId)));
  855. mercHomeStatisticalVO.setNeedToFillNum(deviceNum);
  856. return R.ok(mercHomeStatisticalVO);
  857. }
  858. @Override
  859. @ApiOperation("小程序-商户设备首页列表")
  860. public R<List<DeviceInfoDto.MercHomeListVO>> mercHomeList(DeviceInfoDto.MercHomeQueryDTO dto) {
  861. String searchKey = dto.getSearchKey();
  862. Long mercId = dto.getMercId();
  863. String deviceName = dto.getDeviceName();
  864. Long deviceId = dto.getDeviceId();
  865. List<Long> searchPlaceIdList = new ArrayList<>();
  866. //根据管理员名字查询点位ID列表
  867. if (Emptys.check(dto.getAdminName())) {
  868. MercPlaceDto.ListDto placeDto = new MercPlaceDto.ListDto();
  869. placeDto.setMercId(mercId).setAdminName(dto.getAdminName());
  870. List<MercPlaceDto.Vo> searchPlaceList = mercPlaceService.list(placeDto).getData();
  871. if (Emptys.check(searchPlaceList)) {
  872. searchPlaceIdList = searchPlaceList.stream().map(MercPlaceDto.Vo::getId).distinct().collect(Collectors.toList());
  873. } else {
  874. return R.ok();
  875. }
  876. }
  877. boolean isQa = false;
  878. if ("393010594508869".equals(String.valueOf(mercId))) {
  879. isQa = true;
  880. } else {
  881. dto.setActiveState("1");
  882. }
  883. List<Long> searchDeviceIds = new ArrayList<>();
  884. if (StrUtil.isNotEmpty(searchKey) || StrUtil.isNotEmpty(dto.getAdminName())) {
  885. //名称或者编号搜索设备
  886. LambdaQueryWrapper<DeviceInfo> deviceLqw = Wrappers.<DeviceInfo>lambdaQuery()
  887. .eq(DeviceInfo::getMercId, mercId)
  888. .in(Emptys.check(searchPlaceIdList), DeviceInfo::getPlaceId, searchPlaceIdList);
  889. if (Emptys.check(searchKey)) {
  890. deviceLqw.and(wrapper -> wrapper
  891. .eq(Emptys.check(searchKey), DeviceInfo::getDeviceId, searchKey)
  892. .or()
  893. .like(Emptys.check(searchKey), DeviceInfo::getDeviceName, searchKey)
  894. );
  895. }
  896. List<DeviceInfo> list = list(deviceLqw);
  897. if (CollUtil.isEmpty(list)) {
  898. return R.ok(new ArrayList<>());
  899. }
  900. searchDeviceIds = list.stream().map(DeviceInfo::getDeviceId).collect(Collectors.toList());
  901. }
  902. List<Long> myDeviceIds = dto.getDeviceIdList();
  903. Integer busyStatus = dto.getBusyStatus();
  904. Integer onlineStatus = dto.getOnlineStatus();
  905. Integer deviceType = dto.getDeviceType();
  906. //条件查询 在线状态,运营状态,设备类型,
  907. List<Long> deviceIdList = new ArrayList<>();
  908. if (deviceId != null && myDeviceIds.indexOf(deviceId) > 0) {
  909. deviceIdList.add(deviceId);
  910. }
  911. if (CollUtil.isNotEmpty(myDeviceIds) && deviceId == null) {
  912. deviceIdList.addAll(myDeviceIds);
  913. }
  914. if (CollUtil.isNotEmpty(deviceIdList)) {
  915. dto.setDeviceIdList(deviceIdList);
  916. List<Long> queryDeviceIds = new ArrayList<>();
  917. if (CollUtil.isNotEmpty(searchDeviceIds)) {
  918. for (Long id : searchDeviceIds) {
  919. int index = deviceIdList.indexOf(id);
  920. if (index >= 0) {
  921. queryDeviceIds.add(id);
  922. }
  923. }
  924. //无符合权限的搜索设备,返空
  925. if (CollUtil.isEmpty(queryDeviceIds)) {
  926. return R.ok(new ArrayList<>());
  927. } else {
  928. deviceIdList = queryDeviceIds;
  929. dto.setDeviceIdList(queryDeviceIds);
  930. }
  931. }
  932. } else {
  933. return R.ok(new ArrayList<>());
  934. }
  935. if (onlineStatus != null) {
  936. List<DeviceStatus> deviceStatusList = deviceStatusService.list(Wrappers.<DeviceStatus>lambdaQuery()
  937. .eq(DeviceStatus::getNetState, onlineStatus)
  938. .in(CollUtil.isNotEmpty(myDeviceIds), DeviceStatus::getDeviceId, deviceIdList)
  939. );
  940. if (CollUtil.isNotEmpty(deviceStatusList)) {
  941. List<Long> dbDeviceIdList = deviceStatusList.stream().map(DeviceStatus::getDeviceId).collect(Collectors.toList());
  942. deviceIdList = dbDeviceIdList;
  943. } else {
  944. return R.ok(new ArrayList<>());
  945. }
  946. }
  947. List<DeviceInfoDto.MercHomeCountVO> list = this.baseMapper.merHomeCountList(dto);
  948. if (CollUtil.isEmpty(list)) {
  949. return R.ok(Collections.emptyList());
  950. }
  951. List<DeviceInfoDto.MercHomeListVO> dataList = new ArrayList<>(list.size());
  952. LambdaQueryWrapper<DeviceInfo> lqw = new LambdaQueryWrapper<>();
  953. //非质检商户才需要激活
  954. lqw.eq(!isQa, DeviceInfo::getActiveState, DeviceActiveStateEnum.TRUE.getCode());
  955. lqw.eq(mercId != null, DeviceInfo::getMercId, mercId);
  956. lqw.eq(busyStatus != null, DeviceInfo::getBusyState, busyStatus);
  957. lqw.eq(deviceType != null, DeviceInfo::getDeviceType, deviceType);
  958. lqw.in(CollUtil.isNotEmpty(deviceIdList), DeviceInfo::getDeviceId, deviceIdList);
  959. lqw.like(StrUtil.isNotEmpty(deviceName), DeviceInfo::getDeviceName, deviceName).orderByAsc(true, DeviceInfo::getDeviceName, DeviceInfo::getDeviceId);
  960. List<DeviceInfoDto.Vo> deviceInfoList = copy(DeviceInfoDto.Vo.class, this.list(lqw));
  961. //根据点位ID查询管理员名字
  962. List<Long> placeIdList = deviceInfoList.stream().map(DeviceInfoDto.Vo::getPlaceId).distinct().filter(Objects::nonNull).collect(Collectors.toList());
  963. List<MercPlaceDto.Vo> mercPlaceList = mercPlaceService.list(new MercPlaceDto.ListDto().setIds(placeIdList)).getData();
  964. if (Emptys.check(mercPlaceList)) {
  965. //Map<Long, String> mercPlaceMap = mercPlaceList.stream().collect(Collectors.toMap(i -> i.getId(), i -> i.getAdminName()));
  966. Map<Long, String> mercPlaceMap = mercPlaceList.stream().collect(HashMap::new, (map, item) -> map.put(item.getId(), item.getAdminName()), HashMap::putAll);
  967. deviceInfoList.forEach(i -> i.setAdminName(mercPlaceMap.get(i.getPlaceId())));
  968. }
  969. //没有管理员的的设置默认值
  970. deviceInfoList.stream().filter(s -> s.getAdminName() == null).forEach(s -> s.setAdminName("未分配管理员"));
  971. List<String> adminNameList = deviceInfoList.stream().map(DeviceInfoDto.Vo::getAdminName).distinct().collect(Collectors.toList());
  972. //根据管理员名字分组
  973. Map<String, List<DeviceInfoDto.Vo>> deviceMap = deviceInfoList.stream().collect(Collectors.groupingBy(DeviceInfoDto.Vo::getAdminName));
  974. DateTime date = DateTime.now();
  975. DateTime start = DateUtil.beginOfDay(date);
  976. DateTime end = DateUtil.endOfDay(date);
  977. for (String adminName : adminNameList) {
  978. DeviceInfoDto.MercHomeListVO vo = new DeviceInfoDto.MercHomeListVO();
  979. vo.setAdminName(adminName);
  980. //区域下的设备列表
  981. List<DeviceInfoDto.MercHomeDeviceVo> deviceInfos = BeanUtil.copyToList(deviceMap.get(adminName), DeviceInfoDto.MercHomeDeviceVo.class);
  982. vo.setDeviceNum(deviceInfos.size());
  983. if (CollUtil.isEmpty(deviceInfos)) {
  984. continue;
  985. }
  986. //设备销售统计
  987. List<Long> deviceIds = deviceInfos.stream().map(DeviceInfoDto.MercHomeDeviceVo::getDeviceId).collect(Collectors.toList());
  988. //设备状态查询
  989. List<DeviceStatusDto.Vo> deviceStatusList = deviceStatusService.list(new DeviceStatusDto.SelectList().setDeviceIds(deviceIds)).getData();
  990. Map<Long, DeviceStatusDto.Vo> datdeviceStatusMap = new HashMap<>();
  991. if (CollUtil.isNotEmpty(deviceStatusList)) {
  992. datdeviceStatusMap = deviceStatusList.stream().collect(Collectors.toMap(DeviceStatusDto.Vo::getDeviceId, d -> d));
  993. }
  994. List<GoodsDeviceDto.Vo> goodsDeviceList = R.feignCheckData(goodsService.queryGoodsDeviceInfo(new GoodsDto.QueryGoodsDeviceInfo().setMercId(mercId).setDeviceIds(deviceIds)));
  995. Map<Long, List<GoodsDeviceDto.Vo>> deviceIdGoodsMap = goodsDeviceList.stream()
  996. .collect(Collectors.groupingBy(GoodsDeviceDto.Vo::getDeviceId));
  997. List<AlgorithmDto.ListNameId> algorithmList = R.feignCheckData(algorithmService.ListNameId());
  998. Map<Long, String> algorithmListMap = algorithmList.stream().collect(Collectors.toMap(AlgorithmDto.ListNameId::getId, AlgorithmDto.ListNameId::getAlias));
  999. for (DeviceInfoDto.MercHomeDeviceVo device : deviceInfos) {
  1000. Long dId = device.getDeviceId();
  1001. //设备类型 反显
  1002. SysDictRedis dictDeviceType = SysDictUtils.get(DictConsts.DEVICE_TYPE, String.valueOf(device.getDeviceType()));
  1003. device.setDeviceTypeName(dictDeviceType.getMsg());
  1004. //运营状态 反显
  1005. SysDictRedis dictBusyState = SysDictUtils.get(DictConsts.DEVICE_BUSY_STATUS, String.valueOf(device.getBusyState()));
  1006. device.setBusyStateName(dictBusyState.getMsg());
  1007. Integer zero = new Integer(0);
  1008. CountDto.OrderByCreateTimeAndMercId orderByCreateTimeAndMercId = new CountDto.OrderByCreateTimeAndMercId()
  1009. .setMerdId(mercId).setBeginTime(start).setEndTime(end).setDeviceIds(CollUtil.newArrayList(dId));
  1010. log.info("设备订单统计:{}", JSONUtil.toJsonPrettyStr(orderByCreateTimeAndMercId));
  1011. //完成订单
  1012. CountDto.SuccessVo successVo = R.feignCheckData(countApiService.orderBySuccess(orderByCreateTimeAndMercId));
  1013. //今日销售、库存情况 反显
  1014. device.setDayOrderNum(successVo != null ? successVo.getOrdersSize() : zero);
  1015. device.setDaySalesPrice(successVo != null ? successVo.getOrderTotalMoney() : zero);
  1016. DeviceStatusDto.Vo deviceStatus = datdeviceStatusMap.get(device.getDeviceId());
  1017. if (CollUtil.isNotEmpty(deviceIdGoodsMap)) {
  1018. List<GoodsDeviceDto.Vo> goodsDevice = deviceIdGoodsMap.get(dId);
  1019. if (CollUtil.isNotEmpty(goodsDevice)) {
  1020. device.setOnSaleNum(goodsDevice.stream().mapToInt(GoodsDeviceDto.Vo::getStock).sum());
  1021. device.setFillNum(goodsDevice.stream().mapToInt(GoodsDeviceDto.Vo::getFillCount).sum());
  1022. }
  1023. }
  1024. //算法類型
  1025. Long algorithmId = device.getAlgorithmId();
  1026. if (algorithmId != null) {
  1027. String name = algorithmListMap.get(algorithmId);
  1028. device.setAlgorithmAlias(name);
  1029. }
  1030. //联网状态
  1031. Integer netState = deviceStatus == null ? DeviceNetSateType.DISCONNECT.getCode() : deviceStatus.getNetState();
  1032. device.setNetState(netState);
  1033. if (netState == null) {
  1034. device.setNetStateName(StrUtil.EMPTY);
  1035. } else {
  1036. device.setNetStateName(DeviceNetSateType.getEnumByCode(netState).getDescription());
  1037. }
  1038. if (deviceStatus != null) {
  1039. Integer deviceStateL = deviceStatus.getLockStateL();
  1040. Integer deviceStateR = deviceStatus.getLockStateR();
  1041. device.setTempValue(deviceStatus.getTempValue());
  1042. device.setDeviceStateL(deviceStateL);
  1043. device.setDeviceStateR(deviceStateR);
  1044. Boolean isUseBattery = deviceStatus.getIsUseBattery();
  1045. if (BooleanUtil.isTrue(isUseBattery)) {
  1046. //使用电池。即断电状态
  1047. device.setSysPower(2);
  1048. } else {
  1049. device.setSysPower(1);
  1050. }
  1051. DeviceLockState deviceLockStateL = DeviceLockState.getEnumByCode(deviceStateL);
  1052. DeviceLockState deviceLockStateR = DeviceLockState.getEnumByCode(deviceStateR);
  1053. device.setDeviceStateRName(deviceLockStateR == null ? "未知" : deviceLockStateR.getDescription());
  1054. device.setDeviceStateLName(deviceLockStateL == null ? "未知" : deviceLockStateL.getDescription());
  1055. }
  1056. }
  1057. //名称排序
  1058. if (CollUtil.isNotEmpty(deviceInfos)) {
  1059. deviceInfos = ListUtil.sortByProperty(deviceInfos, LambdaUtils.getProperty(DeviceInfoDto.MercHomeDeviceVo::getDeviceName));
  1060. deviceInfos = ListUtil.sortByProperty(deviceInfos, LambdaUtils.getProperty(DeviceInfoDto.MercHomeDeviceVo::getDeviceId));
  1061. }
  1062. vo.setDeviceInfos(deviceInfos);
  1063. dataList.add(vo);
  1064. }
  1065. DeviceInfoDto.MercHomeListVO orderTemp = null;
  1066. for (int i = 0; i < dataList.size(); i++) {
  1067. if ("未分配管理员".equals(dataList.get(i).getAdminName())) {
  1068. orderTemp = dataList.get(i);
  1069. dataList.remove(i);
  1070. dataList.add(orderTemp);
  1071. break;
  1072. }
  1073. }
  1074. return R.ok(dataList);
  1075. }
  1076. /**
  1077. * 获取商户设备列表
  1078. *
  1079. * @param mercId
  1080. * @return
  1081. */
  1082. private List<DeviceInfo> getDevicesByMercId(Long mercId) {
  1083. return list(Wrappers.<DeviceInfo>lambdaQuery().eq(DeviceInfo::getMercId, mercId).eq(DeviceInfo::getActiveState, DeviceActiveStateEnum.TRUE.getCode()));
  1084. }
  1085. /**
  1086. * 小程序商户设备搜索
  1087. *
  1088. * @param page
  1089. * @return
  1090. */
  1091. @Override
  1092. public R<PageBean<DeviceInfoDto.MerHomeSearchVO>> mercDeviceSearchPage(@RequestBody DeviceInfoDto.Page page) {
  1093. PageBean<DeviceInfoDto.MerHomeSearchVO> pageData = new PageBean<>();
  1094. //小程序独有查询字段 缺货状态:stockStatus ,是否查故障设备:fault
  1095. Boolean fault = page.getFault();
  1096. Long mercId = page.getMercId();
  1097. List<Long> myDeviceIds = page.getMyDeviceIds();
  1098. if (CollUtil.isEmpty(myDeviceIds)) {
  1099. //无设备
  1100. return R.ok(pageData);
  1101. }
  1102. if (BooleanUtil.isTrue(fault)) {
  1103. //查询故障设备
  1104. List<DeviceEventMsg> deviceEventMsgs = deviceEventMsgService.list(Wrappers.<DeviceEventMsg>lambdaQuery()
  1105. .eq(mercId != null, DeviceEventMsg::getMercId, page.getMercId())
  1106. .in(DeviceEventMsg::getDeviceId, myDeviceIds));
  1107. List<Long> deviceIdList = deviceEventMsgs.stream().map(DeviceEventMsg::getDeviceId).collect(Collectors.toList());
  1108. if (CollUtil.isEmpty(deviceIdList)) {
  1109. return R.ok(new PageBean<>());
  1110. }
  1111. page.setDeviceIdList(deviceIdList);
  1112. } else {
  1113. page.setDeviceIdList(myDeviceIds);
  1114. }
  1115. PageBean<DeviceInfoDto.Vo2> pageBean = queryPage(page);
  1116. List<DeviceInfoDto.Vo2> records = pageBean.getRecords();
  1117. if (CollUtil.isEmpty(records)) {
  1118. return R.ok(pageData);
  1119. }
  1120. List<DeviceInfoDto.MerHomeSearchVO> merHomeSearchRecords = new ArrayList<>();
  1121. BeanUtil.copyProperties(pageBean, pageData);
  1122. if (CollUtil.isNotEmpty(records)) {
  1123. List<Long> deviceIds = records.stream().map(DeviceInfoDto.Vo2::getDeviceId).collect(Collectors.toList());
  1124. String type = EnumDeviceDataType.DAY.getCode();
  1125. String todayDate = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
  1126. //查询当天
  1127. DeviceDataDto.ListDTO dto = new DeviceDataDto.ListDTO()
  1128. .setDeviceIds(deviceIds).setType(type).setDateValue(Integer.valueOf(todayDate)).setMercId(mercId);
  1129. List<DeviceDataDto.Vo> deviceDataList = deviceDataService.list(dto);
  1130. Map<Long, DeviceDataDto.Vo> dataMap = MapUtil.newHashMap();
  1131. //统计数据反显
  1132. if (CollUtil.isNotEmpty(deviceDataList)) {
  1133. dataMap = deviceDataList.stream().collect(Collectors.toMap(DeviceDataDto.Vo::getDeviceId, d -> d));
  1134. }
  1135. for (DeviceInfoDto.Vo2 v : records) {
  1136. DeviceInfoDto.MerHomeSearchVO merHomeSearchVO = new DeviceInfoDto.MerHomeSearchVO();
  1137. Long deviceId = v.getDeviceId();
  1138. DeviceDataDto.Vo vo = dataMap.get(deviceId);
  1139. if (vo != null) {
  1140. //今日订单数
  1141. v.setDayOrderNum(vo != null ? vo.getSalesCount() : 0);
  1142. v.setDaySalesPrice(vo != null ? vo.getSalesMoney() : 0);
  1143. BeanUtil.copyProperties(vo, merHomeSearchVO);
  1144. }
  1145. DeviceSysinfoDto.Vo deviceSysinfo = v.getDeviceSysinfo();
  1146. DeviceStatusDto.Vo deviceStatus = v.getDeviceStatus();
  1147. merHomeSearchVO.setAppUpmVersion(deviceSysinfo.getAppUpmVersion());
  1148. merHomeSearchVO.setTempValue(deviceStatus.getTempValue());
  1149. merHomeSearchVO.setNetDbm(deviceStatus.getNetDbm());
  1150. Integer deviceStateL = deviceStatus.getLockStateL();
  1151. Integer deviceStateR = deviceStatus.getLockStateR();
  1152. merHomeSearchVO.setDeviceStateL(deviceStateL);
  1153. merHomeSearchVO.setDeviceStateR(deviceStateR);
  1154. DeviceLockState deviceLockStateL = DeviceLockState.getEnumByCode(deviceStateL);
  1155. DeviceLockState deviceLockStateR = DeviceLockState.getEnumByCode(deviceStateR);
  1156. merHomeSearchVO.setDeviceStateRName(deviceLockStateR == null ? "未知" : deviceLockStateR.getDescription());
  1157. merHomeSearchVO.setDeviceStateLName(deviceLockStateL == null ? "未知" : deviceLockStateL.getDescription());
  1158. merHomeSearchRecords.add(merHomeSearchVO);
  1159. }
  1160. pageData.setRecords(merHomeSearchRecords);
  1161. }
  1162. return R.ok(pageData);
  1163. }
  1164. /**
  1165. * 小程序商户设备详情-数据统计
  1166. *
  1167. * @param dto
  1168. * @return
  1169. */
  1170. @Override
  1171. @ApiOperation("商户设备详情-数据统计")
  1172. public R<DeviceInfoDto.DeviceDataCountVO> dataCount(DeviceInfoDto.DeviceDataCountDTO dto) {
  1173. // 统计类型(1=经营数据,2=经营图表,3=温度图表,4=信号图表,5=商品管理)
  1174. Integer type = dto.getType();
  1175. switch (type) {
  1176. case 1:
  1177. //经营数据
  1178. return R.ok(dataCount1(dto));
  1179. case 2:
  1180. //经营图表
  1181. return R.ok(dataCount2(dto));
  1182. case 3:
  1183. //温度图表
  1184. return R.ok(dataCount3(dto));
  1185. case 4:
  1186. //信号图表
  1187. return R.ok(dataCount4(dto));
  1188. case 5:
  1189. //商品管理
  1190. return R.ok(dataCount5(dto));
  1191. default:
  1192. break;
  1193. }
  1194. return R.ok();
  1195. }
  1196. /**
  1197. * 经营数据
  1198. *
  1199. * @param dto
  1200. * @return
  1201. */
  1202. private DeviceInfoDto.DeviceDataCountVO dataCount1(DeviceInfoDto.DeviceDataCountDTO dto) {
  1203. Long deviceId = dto.getDeviceId();
  1204. Long mercId = dto.getMercId();
  1205. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  1206. //当天
  1207. DateTime date = DateTime.now();
  1208. DateTime start = DateUtil.beginOfDay(date);
  1209. DateTime end = DateUtil.endOfDay(date);
  1210. List<Long> deviceIds = CollUtil.newArrayList(deviceId);
  1211. CountDto.OrderByCreateTimeAndMercId orderByCreateTimeAndMercId = new CountDto.OrderByCreateTimeAndMercId()
  1212. .setMerdId(mercId).setBeginTime(start).setEndTime(end).setDeviceIds(deviceIds);
  1213. //完成订单
  1214. CountDto.SuccessVo successVo = R.feignCheckData(countApiService.orderBySuccess(orderByCreateTimeAndMercId));
  1215. DeviceDataDto.Vo dayData = new DeviceDataDto.Vo();
  1216. if (successVo != null) {
  1217. dayData.setSalesMoney(successVo.getOrderTotalMoney());
  1218. dayData.setRefundMoney(successVo.getRefundMoney());
  1219. dayData.setSalesCount(successVo.getOrdersSize());
  1220. }
  1221. //当月
  1222. DeviceDataDto.Vo monthData = new DeviceDataDto.Vo();
  1223. //月度统计
  1224. DateTime startM = DateUtil.beginOfMonth(date);
  1225. DateTime endM = DateUtil.endOfMonth(date);
  1226. CountDto.OrderByCreateTimeAndMercId monthOrder = new CountDto.OrderByCreateTimeAndMercId()
  1227. .setMerdId(mercId).setBeginTime(startM).setEndTime(endM).setDeviceIds(deviceIds);
  1228. //完成订单
  1229. CountDto.SuccessVo successVoM = R.feignCheckData(countApiService.orderBySuccess(monthOrder));
  1230. if (monthData != null) {
  1231. monthData.setRefundMoney(successVoM.getRefundMoney());
  1232. monthData.setSalesMoney(successVoM.getOrderTotalMoney());
  1233. monthData.setSalesCount(successVoM.getOrdersSize());
  1234. }
  1235. vo.setDayBusinessData(copy(DeviceInfoDto.BusinessData.class, dayData));
  1236. vo.setMonthBusinessData(copy(DeviceInfoDto.BusinessData.class, monthData));
  1237. return vo;
  1238. }
  1239. /**
  1240. * 经营图表
  1241. *
  1242. * @param dto
  1243. * @return
  1244. */
  1245. private DeviceInfoDto.DeviceDataCountVO dataCount2(DeviceInfoDto.DeviceDataCountDTO dto) {
  1246. Long deviceId = dto.getDeviceId();
  1247. //近一个月 (销售额,订单数,退款金额,退款数)
  1248. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  1249. DeviceInfoDto.BusinessChart businessChart = new DeviceInfoDto.BusinessChart();
  1250. List<String> categories = DataTime.dayListByLastDay(30);
  1251. List<Integer> dateList = new ArrayList<>(30);
  1252. businessChart.setCategories(categories);
  1253. categories.forEach(d -> {
  1254. dateList.add(Integer.valueOf(d.replaceAll(StrUtil.DASHED, StrUtil.EMPTY)));
  1255. });
  1256. Integer startDay = dateList.get(0);
  1257. Integer endDay = dateList.get(categories.size() - 1);
  1258. List<DeviceDataDto.Vo> listByDay = deviceDataService.getListByDay(deviceId, startDay, endDay);
  1259. if (CollUtil.isEmpty(listByDay)) {
  1260. return vo;
  1261. }
  1262. //每天的数据
  1263. Map<Integer, DeviceDataDto.Vo> dataDayMap = listByDay.stream().collect(Collectors.toMap(DeviceDataDto.Vo::getDateValue, i -> i));
  1264. List<DeviceInfoDto.MyChartSeries3> series = new ArrayList<>();
  1265. String[] names = {"销售额", "订单数", "退款金额", "退款数"};
  1266. for (int i = 0; i < names.length; i++) {
  1267. DeviceInfoDto.MyChartSeries3 myChartSeries = new DeviceInfoDto.MyChartSeries3();
  1268. //某个类型每天的数据
  1269. List<String> data = new ArrayList<>();
  1270. if (i == 0) {
  1271. //销售额
  1272. dateList.forEach(d -> {
  1273. //每日数据填充
  1274. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  1275. if (deviceData == null) {
  1276. data.add(String.valueOf(BigDecimal.ZERO));
  1277. } else {
  1278. Integer salesMoney = deviceData.getSalesMoney() == null ? 0 : deviceData.getSalesMoney();
  1279. BigDecimal day = BigDecimal.valueOf(salesMoney).divide(BigDecimal.valueOf(100));
  1280. data.add(String.valueOf(day));
  1281. }
  1282. });
  1283. } else if (i == 1) {
  1284. //订单数
  1285. dateList.forEach(d -> {
  1286. //每日数据填充
  1287. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  1288. String value = "0";
  1289. if (deviceData == null) {
  1290. data.add(value);
  1291. } else {
  1292. data.add(deviceData == null ? value : String.valueOf(deviceData.getSalesCount()));
  1293. }
  1294. });
  1295. } else if (i == 2) {
  1296. //退款金额
  1297. dateList.forEach(d -> {
  1298. //每日数据填充
  1299. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  1300. if (deviceData == null) {
  1301. data.add(String.valueOf(BigDecimal.ZERO));
  1302. } else {
  1303. Integer refundMoney = deviceData.getRefundMoney() == null ? 0 : deviceData.getRefundMoney();
  1304. BigDecimal day = BigDecimal.valueOf(refundMoney).divide(BigDecimal.valueOf(100));
  1305. data.add(String.valueOf(day));
  1306. }
  1307. });
  1308. } else if (i == 3) {
  1309. //退款数
  1310. dateList.forEach(d -> {
  1311. //每日数据填充
  1312. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  1313. if (deviceData == null) {
  1314. data.add("0");
  1315. } else {
  1316. data.add(deviceData == null ? "0" : String.valueOf(deviceData.getRefundCount()));
  1317. }
  1318. });
  1319. }
  1320. myChartSeries.setName(names[i]);
  1321. myChartSeries.setData(data);
  1322. series.add(myChartSeries);
  1323. }
  1324. businessChart.setSeries(series);
  1325. vo.setBusinessChart(businessChart);
  1326. return vo;
  1327. }
  1328. /**
  1329. * 温度图表
  1330. *
  1331. * @param dto
  1332. * @return
  1333. */
  1334. private DeviceInfoDto.DeviceDataCountVO dataCount3(DeviceInfoDto.DeviceDataCountDTO dto) {
  1335. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  1336. Long deviceId = dto.getDeviceId();
  1337. String choosDate = dto.getChoosDate();
  1338. if (StrUtil.isEmpty(choosDate)) {
  1339. choosDate = DateUtil.formatDate(new Date());
  1340. }
  1341. String startTime = choosDate + " 00:00:00";
  1342. String endTime = choosDate + " 23:59:59";
  1343. //查询选定日期的温度数据
  1344. List<DeviceTempRecords> deviceTempRecords = deviceTempRecordsService.list(Wrappers.<DeviceTempRecords>lambdaQuery()
  1345. .eq(DeviceTempRecords::getDeviceId, deviceId).between(DeviceTempRecords::getCreateTime, startTime, endTime)
  1346. .orderBy(true, true, DeviceTempRecords::getCreateTime));
  1347. if (CollUtil.isEmpty(deviceTempRecords)) {
  1348. return vo;
  1349. }
  1350. DeviceInfoDto.TemperatureChart temperatureChart = new DeviceInfoDto.TemperatureChart();
  1351. List<String> categories = new ArrayList<>();
  1352. String name = "温度";
  1353. List<DeviceInfoDto.MyChartSeries2> series = new ArrayList<>();
  1354. List<BigDecimal> data = new ArrayList<>();
  1355. deviceTempRecords.forEach(d -> {
  1356. Integer tempValue = d.getTempValue();
  1357. LocalDateTime createTime = d.getCreateTime();
  1358. String time = DateUtil.format(createTime, "HH:mm:ss");
  1359. categories.add(time);
  1360. data.add(tempValue == null ? null : NumberUtil.toBigDecimal(tempValue));
  1361. });
  1362. DeviceInfoDto.MyChartSeries2 myChartSeries = new DeviceInfoDto.MyChartSeries2();
  1363. myChartSeries.setName(name);
  1364. myChartSeries.setData(data);
  1365. series.add(myChartSeries);
  1366. temperatureChart.setSeries(series);
  1367. temperatureChart.setCategories(categories);
  1368. vo.setTemperatureChart(temperatureChart);
  1369. return vo;
  1370. }
  1371. /**
  1372. * 信号图表
  1373. *
  1374. * @param dto
  1375. * @return
  1376. */
  1377. private DeviceInfoDto.DeviceDataCountVO dataCount4(DeviceInfoDto.DeviceDataCountDTO dto) {
  1378. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  1379. Long deviceId = dto.getDeviceId();
  1380. String choosDate = dto.getChoosDate();
  1381. if (StrUtil.isEmpty(choosDate)) {
  1382. choosDate = DateUtil.formatDate(new Date());
  1383. }
  1384. String startTime = choosDate + " 00:00:00";
  1385. String endTime = choosDate + " 23:59:59";
  1386. //查询选定日期的温度数据
  1387. List<DeviceNetRecord> deviceNetRecords = deviceNetRecordService.list(Wrappers.<DeviceNetRecord>lambdaQuery()
  1388. .eq(DeviceNetRecord::getDeviceId, deviceId).between(DeviceNetRecord::getCreateTime, startTime, endTime)
  1389. .orderBy(true, true, DeviceNetRecord::getCreateTime));
  1390. if (CollUtil.isEmpty(deviceNetRecords)) {
  1391. return vo;
  1392. }
  1393. DeviceInfoDto.SignalChart signalChart = new DeviceInfoDto.SignalChart();
  1394. List<String> categories = new ArrayList<>();
  1395. String name = "信号";
  1396. List<DeviceInfoDto.MyChartSeries> series = new ArrayList<>();
  1397. List<Integer> data = new ArrayList<>();
  1398. deviceNetRecords.forEach(d -> {
  1399. Integer value = d.getSimDbm();
  1400. LocalDateTime createTime = d.getCreateTime();
  1401. String time = DateUtil.format(createTime, "HH:mm:ss");
  1402. categories.add(time);
  1403. data.add(value);
  1404. });
  1405. DeviceInfoDto.MyChartSeries myChartSeries = new DeviceInfoDto.MyChartSeries();
  1406. myChartSeries.setName(name);
  1407. myChartSeries.setData(data);
  1408. series.add(myChartSeries);
  1409. signalChart.setSeries(series);
  1410. signalChart.setCategories(categories);
  1411. vo.setSignalChart(signalChart);
  1412. return vo;
  1413. }
  1414. /**
  1415. * 商品管理
  1416. *
  1417. * @param dto
  1418. * @return
  1419. */
  1420. private DeviceInfoDto.DeviceDataCountVO dataCount5(DeviceInfoDto.DeviceDataCountDTO dto) {
  1421. Long deviceId = dto.getDeviceId();
  1422. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  1423. DeviceInfoDto.GoodsData goodsData = new DeviceInfoDto.GoodsData();
  1424. //在售商品种类
  1425. //根据设备ID查商品id
  1426. GoodsDeviceDto.SelectList selectList = new GoodsDeviceDto.SelectList();
  1427. selectList.setDeviceIds(CollUtil.newArrayList(deviceId));
  1428. selectList.setMercId(dto.getMercId());
  1429. R<List<GoodsDeviceDto.Vo>> r = R.feignCheck(goodsDeviceService.list(selectList));
  1430. List<GoodsDeviceDto.Vo> goodsDeviceList = r.getData();
  1431. Integer stock = 0;
  1432. Integer afterFillStock = 0;
  1433. if (CollUtil.isNotEmpty(goodsDeviceList)) {
  1434. stock = goodsDeviceList.stream().mapToInt(GoodsDeviceDto.Vo::getStock).sum();
  1435. afterFillStock = goodsDeviceList.stream().mapToInt(GoodsDeviceDto.Vo::getFillCount).sum();
  1436. }
  1437. goodsData.setAfterFillStock(afterFillStock);
  1438. goodsData.setStock(stock);
  1439. goodsData.setCategoryNum(CollUtil.isNotEmpty(goodsDeviceList) ? goodsDeviceList.size() : new Integer(0));
  1440. vo.setGoodsData(goodsData);
  1441. return vo;
  1442. }
  1443. public PageBean<DeviceInfoDto.Vo2> queryPage(DeviceInfoDto.Page page) {
  1444. IPage<DeviceInfoQueryPage> iPage = baseMapper.queryPage(toIPage(page.getPage()), page);
  1445. return toPageBean(DeviceInfoDto.Vo2.class, iPage);
  1446. }
  1447. private <T> void check(T value, T value2, String msg) {
  1448. if (value.toString().equals(value2.toString())) {
  1449. throw new CommRuntimeException(msg);
  1450. }
  1451. }
  1452. }