DeviceInfoServiceImpl.java 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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.StrUtil;
  13. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  14. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  15. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  16. import com.baomidou.mybatisplus.core.metadata.IPage;
  17. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  18. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  19. import com.xy.collections.list.JArrayList;
  20. import com.xy.collections.list.JList;
  21. import com.xy.config.DeviceThreadPoolConfig;
  22. import com.xy.consts.DictConsts;
  23. import com.xy.dto.*;
  24. import com.xy.dto.be.MercDto;
  25. import com.xy.entity.*;
  26. import com.xy.enums.FileExportType;
  27. import com.xy.error.CommRuntimeException;
  28. import com.xy.mapper.DeviceInfoMapper;
  29. import com.xy.mapper.entity.DeviceInfoQueryPage;
  30. import com.xy.service.be.MercFeignService;
  31. import com.xy.util.ExcelUtils;
  32. import com.xy.utils.*;
  33. import com.xy.utils.enums.*;
  34. import io.swagger.annotations.Api;
  35. import io.swagger.annotations.ApiOperation;
  36. import jodd.introspector.MapperFunction;
  37. import lombok.RequiredArgsConstructor;
  38. import org.springframework.stereotype.Service;
  39. import org.springframework.transaction.annotation.Transactional;
  40. import org.springframework.validation.annotation.Validated;
  41. import org.springframework.web.bind.annotation.PostMapping;
  42. import org.springframework.web.bind.annotation.RequestBody;
  43. import javax.servlet.http.HttpServletResponse;
  44. import javax.validation.Valid;
  45. import java.io.IOException;
  46. import java.math.BigDecimal;
  47. import java.time.LocalDateTime;
  48. import java.util.*;
  49. import java.util.stream.Collectors;
  50. import static com.xy.utils.PlusBeans.*;
  51. /**
  52. * <p>
  53. * 设备-信息 服务实现类
  54. * </p>
  55. *
  56. * @author lijin
  57. * @since 2022-12-23
  58. */
  59. @Service
  60. @RequiredArgsConstructor
  61. @Api(tags = "设备-信息")
  62. public class DeviceInfoServiceImpl extends ServiceImpl<DeviceInfoMapper, DeviceInfo> implements DeviceInfoService {
  63. private final MercFeignService mercFeignService;
  64. private final DeviceSysinfoServiceImpl deviceSysinfoService;
  65. private final DeviceStatusServiceImpl deviceStatusService;
  66. private final DeviceRegisterServiceImpl deviceRegisterService;
  67. private final DeviceEventMsgServiceImpl deviceEventMsgService;
  68. private final DeviceDataServiceImpl deviceDataService;
  69. private final DeviceTempRecordsServiceImpl deviceTempRecordsService;
  70. private final DeviceNetRecordServiceImpl deviceNetRecordService;
  71. private final GoodsDeviceService goodsDeviceService;
  72. private final FileExportService fileExportService;
  73. private final RedisService<String> redisService;
  74. private final GoodsService goodsService;
  75. private final OrderRefundService refundService;
  76. private final String keyPrefix = "device:history:";
  77. /**
  78. * 质检商户code
  79. */
  80. public static final String QA_MERC_CODE = "10001";
  81. @Override
  82. @ApiOperation("分页")
  83. public R<PageBean<DeviceInfoDto.Vo>> pageSingle(DeviceInfoDto.PageSingle dto) {
  84. PageBean pageBean = dto.getPage();
  85. LambdaQueryWrapper<DeviceInfo> lqw = new MybatisPlusQuery().eqWrapper(dto,DeviceInfo.class)
  86. .build();
  87. IPage<DeviceInfo> iPage = page(toIPage(pageBean), lqw);
  88. return R.ok(toPageBean(DeviceInfoDto.Vo.class, iPage));
  89. }
  90. @Override
  91. @ApiOperation("对象查询")
  92. public R<DeviceInfoDto.Vo> obj(DeviceInfoDto.Obj obj) {
  93. //设备信息
  94. LambdaQueryWrapper<DeviceInfo> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(obj, DeviceInfo.class).build();
  95. List<DeviceInfo> list = list(lambdaQueryWrapper);
  96. if (!Emptys.check(list)) {
  97. return R.ok();
  98. }
  99. DeviceInfoDto.Vo deviceInfo = copy(DeviceInfoDto.Vo.class, list.get(0));
  100. int num = 0;
  101. if (obj.getIsSysinfo()) {
  102. num++;
  103. }
  104. if (obj.getIsStatus()) {
  105. num++;
  106. }
  107. if (obj.getIsRegister()) {
  108. num++;
  109. }
  110. if (num > 0) {
  111. ThreadPoolUtils.Execute execute = ThreadPoolUtils.excPoll(DeviceThreadPoolConfig.DEVICE_COMMON_POLL, num);
  112. if (obj.getIsSysinfo()) {
  113. execute.execute(() -> {
  114. //系统信息
  115. DeviceSysinfoDto.Vo deviceSysinfo = deviceSysinfoService.get(new DeviceSysinfoDto.Vo().setDeviceId(deviceInfo.getDeviceId())).getData();
  116. deviceInfo.setDeviceSysinfo(deviceSysinfo);
  117. });
  118. }
  119. if (obj.getIsStatus()) {
  120. execute.execute(() -> {
  121. //状态信息
  122. DeviceStatusDto.Vo deviceStatus = deviceStatusService.obj(new DeviceStatusDto.Vo().setDeviceId(deviceInfo.getDeviceId())).getData();
  123. deviceInfo.setDeviceStatus(deviceStatus);
  124. });
  125. }
  126. if (obj.getIsRegister()) {
  127. execute.execute(() -> {
  128. //注册信息
  129. DeviceRegisterDto.Vo deviceRegister = deviceRegisterService.obj(new DeviceRegisterDto.Vo().setDeviceId(deviceInfo.getDeviceId())).getData();
  130. deviceInfo.setDeviceRegister(deviceRegister);
  131. });
  132. }
  133. execute.end();
  134. }
  135. return R.ok(deviceInfo);
  136. }
  137. @ApiOperation("反显设备名称")
  138. @Override
  139. public R<Map<Long, String>> getDeviceNameList(DeviceInfoDto.DeviceIdDto dto) {
  140. LambdaQueryWrapper<DeviceInfo> lqw = new LambdaQueryWrapper<DeviceInfo>()
  141. .in(DeviceInfo::getDeviceId, dto.getDeviceId())
  142. .select(DeviceInfo::getDeviceId, DeviceInfo::getDeviceName);
  143. List<DeviceInfo> deviceInfoList = list(lqw);
  144. return R.ok(deviceInfoList.stream().collect(Collectors.toMap(DeviceInfo::getDeviceId, i -> Optional.ofNullable(i.getDeviceName()).orElse(""))));
  145. }
  146. @Override
  147. public R<DeviceSysinfoDto.Vo> getDeviceSysinfo(DeviceSysinfoDto.DeviceSysInfo dto) {
  148. String dtoDeviceSN = dto.getDeviceSN();
  149. DeviceSysinfo one = deviceSysinfoService.getOne(Wrappers.<DeviceSysinfo>lambdaQuery().eq(DeviceSysinfo::getDeviceSn, dtoDeviceSN));
  150. return R.ok(BeanUtil.copyProperties(one, DeviceSysinfoDto.Vo.class));
  151. }
  152. @Override
  153. @ApiOperation("设备访问历史添加")
  154. public R history(DeviceInfoDto.Obj obj) {
  155. //获取字典
  156. SysDictRedis sysDictRedis = SysDictUtils.get(DictsEnum.DATA_CLEAR_SIZE.getKey(), "device_history_twig");
  157. Integer value = Integer.valueOf(sysDictRedis.getValue());
  158. //获取redis
  159. String key = keyPrefix + AuthorizeUtils.getLoginId(Long.class);
  160. List<String> list = redisService.getList(key);
  161. list.add(0, String.valueOf(obj.getDeviceId()));
  162. //去重
  163. List<String> redisList = new ArrayList<>();
  164. JList<String> comparing = new JArrayList<>(list).comparing();
  165. if (comparing.size() > value) {
  166. for (int i = 0; i < value; i++) {
  167. redisList.add(comparing.get(i));
  168. }
  169. } else {
  170. redisList = comparing;
  171. }
  172. redisService.removeList(key);
  173. redisService.setList(key, redisList);
  174. return R.ok();
  175. }
  176. @Override
  177. @ApiOperation("开门检测")
  178. public R<DeviceInfoDto.Vo> checkOpenDoor(DeviceInfoDto.Obj obj) {
  179. DeviceInfoDto.Vo deviceInfo = obj(new DeviceInfoDto.Obj()
  180. .setDeviceId(obj.getDeviceId())
  181. .setIsStatus(true)
  182. ).getData();
  183. if (deviceInfo == null) {
  184. return R.fail("设备不存在");
  185. }
  186. DeviceStatusDto.Vo deviceStatus = deviceInfo.getDeviceStatus();
  187. check(deviceInfo.getFreezeStatus(), 2, "设备已冻结");
  188. SysDictRedis sysDictRedis = SysDictUtils.get(DictsEnum.DEVICE_FAULT_LEVEL_PAY_THRESHOLD.getKey(), DictsSonEnum.DEVICE_FAULT_LEVEL_PAY_THRESHOLD_NOT_PAY.getKey());
  189. if (deviceInfo.getFaultLevel() >= Integer.valueOf(sysDictRedis.getValue())) {
  190. return R.fail("设备故障");
  191. }
  192. check(deviceStatus.getNetState(), 2, "设备已离线");
  193. check(obj.getDoor() != null && obj.getDoor() == 1 ? deviceStatus.getDoorStateR() : deviceStatus.getDoorStateL(), 1, "设备正在使用中,请稍后");
  194. check(obj.getDoor() != null && obj.getDoor() == 1 ? deviceStatus.getLockStateR() : deviceStatus.getLockStateL(), 2, "设备已锁机");
  195. return R.ok(deviceInfo);
  196. }
  197. @PostMapping("historyList")
  198. @ApiOperation("设备访问历史查询")
  199. public R<List<DeviceInfoDto.Vo>> historyList() {
  200. //获取redis
  201. String key = keyPrefix + AuthorizeUtils.getLoginId(Long.class);
  202. List<String> deviceIds = redisService.getList(key);
  203. if (!Emptys.check(deviceIds)) {
  204. return R.ok();
  205. }
  206. //查询数据库
  207. List<DeviceInfo> list = list(new LambdaQueryWrapper<DeviceInfo>().in(DeviceInfo::getDeviceId, deviceIds));
  208. return R.ok(copy(DeviceInfoDto.Vo.class, list));
  209. }
  210. @ApiOperation("修改")
  211. @PostMapping("update")
  212. public R update(@RequestBody @Validated DeviceInfoDto.Update update) {
  213. DeviceInfo deviceInfo = copy(DeviceInfo.class, update)
  214. .setUpdateTime(LocalDateTime.now());
  215. updateById(deviceInfo);
  216. return R.ok();
  217. }
  218. @ApiOperation("批量修改")
  219. @PostMapping("updateBatch")
  220. public R updateBatch(@RequestBody List<DeviceInfoDto.Update> updates) {
  221. LocalDateTime now = LocalDateTime.now();
  222. List<DeviceInfo> deviceInfos = new ArrayList<>(updates.size());
  223. updates.forEach(update -> deviceInfos.add(copy(DeviceInfo.class, update).setUpdateTime(now)));
  224. updateBatchById(deviceInfos);
  225. return R.ok();
  226. }
  227. @Override
  228. @ApiOperation("更新商户线路")
  229. public R updateLine(@RequestBody @Validated DeviceInfoDto.UpdateLine updateLine) {
  230. LambdaUpdateWrapper<DeviceInfo> luw = new LambdaUpdateWrapper<DeviceInfo>().eq(DeviceInfo::getMercId, updateLine.getMercId());
  231. //绑定线路,更换线路
  232. if (DeviceInfoDto.UPDATE.equals(updateLine.getType())) {
  233. DeviceInfo deviceInfo = new DeviceInfo();
  234. deviceInfo.setPlaceLineId(updateLine.getPlaceLineId());
  235. luw.in(DeviceInfo::getDeviceId, updateLine.getDeviceIds());
  236. baseMapper.update(deviceInfo, luw);
  237. }
  238. //删除线路
  239. if (DeviceInfoDto.DEL.equals(updateLine.getType())) {
  240. luw.eq(DeviceInfo::getPlaceLineId, updateLine.getWherePlaceLineId());
  241. luw.set(DeviceInfo::getPlaceLineId, null);
  242. baseMapper.update(null, luw);
  243. }
  244. //解绑线路 设置线路ID为null
  245. if (DeviceInfoDto.CLEAR.equals(updateLine.getType())) {
  246. luw.in(DeviceInfo::getDeviceId, updateLine.getDeviceIds());
  247. luw.set(DeviceInfo::getPlaceLineId, null);
  248. baseMapper.update(null, luw);
  249. }
  250. return R.ok();
  251. }
  252. @Override
  253. @ApiOperation("更新商户点位")
  254. public R updatePlace(@RequestBody @Validated DeviceInfoDto.UpdatePlace updatePlace) {
  255. LambdaUpdateWrapper<DeviceInfo> luw = new LambdaUpdateWrapper<DeviceInfo>().eq(DeviceInfo::getMercId, updatePlace.getMercId());
  256. //绑定点位,更换点位
  257. if (DeviceInfoDto.UPDATE.equals(updatePlace.getType())) {
  258. DeviceInfo deviceInfo = new DeviceInfo();
  259. deviceInfo.setPlaceId(updatePlace.getPlaceId());
  260. luw.in(DeviceInfo::getDeviceId, updatePlace.getDeviceIds());
  261. baseMapper.update(deviceInfo, luw);
  262. }
  263. //删除点位
  264. if (DeviceInfoDto.DEL.equals(updatePlace.getType())) {
  265. luw.eq(DeviceInfo::getPlaceId, updatePlace.getWherePlaceId());
  266. luw.set(DeviceInfo::getPlaceId, null);
  267. baseMapper.update(null, luw);
  268. }
  269. //解绑点位 设置点位ID为null
  270. if (DeviceInfoDto.CLEAR.equals(updatePlace.getType())) {
  271. luw.in(DeviceInfo::getDeviceId, updatePlace.getDeviceIds());
  272. luw.set(DeviceInfo::getPlaceId, null);
  273. baseMapper.update(null, luw);
  274. }
  275. return R.ok();
  276. }
  277. @PostMapping("page")
  278. @ApiOperation("分页查询")
  279. public R<PageBean<DeviceInfoDto.Vo2>> page(@RequestBody DeviceInfoDto.Page page) {
  280. return R.ok(queryPage(page));
  281. }
  282. @ApiOperation("导出设备列表")
  283. @PostMapping("exportDevices")
  284. public void exportDevices(HttpServletResponse response, @RequestBody @Valid DeviceInfoDto.Page page) throws IOException {
  285. PageBean<DeviceInfoDto.Vo2> pageBean = queryPage(page);
  286. List<DeviceInfoDto.Vo2> records = pageBean.getRecords();
  287. List<DeviceInfoDto.DeviceExcelVO> deviceExcelVOS = BeanUtil.copyToList(records, DeviceInfoDto.DeviceExcelVO.class);
  288. // 输出
  289. ExcelUtils.write(response, "设备列表.xls", "设备列表", DeviceInfoDto.DeviceExcelVO.class, deviceExcelVOS);
  290. }
  291. @ApiOperation("导出设备(异步)")
  292. @PostMapping("exportDevices/async")
  293. public void exportDevicesAsync(@RequestBody @Validated DeviceInfoDto.Page page) {
  294. PageBean<DeviceInfoDto.Vo2> pageBean = queryPage(page);
  295. List<DeviceInfoDto.Vo2> records = pageBean.getRecords();
  296. List<DeviceInfoDto.DeviceExcelVO> deviceExcelVOS = BeanUtil.copyToList(records, DeviceInfoDto.DeviceExcelVO.class);
  297. //异步导出参数封装
  298. ExcelDTO<DeviceInfoDto.DeviceExcelVO> excelDTO = new ExcelDTO<>();
  299. excelDTO.setData(deviceExcelVOS);
  300. excelDTO.setHead(DeviceInfoDto.DeviceExcelVO.class);
  301. excelDTO.setSheetName(FileExportType.DEVICE_INFO.getDescription());
  302. excelDTO.setFileExportType(FileExportType.DEVICE_INFO);
  303. //执行导出
  304. fileExportService.exportExcelAsync(excelDTO);
  305. }
  306. @PostMapping("nearbyPage")
  307. @ApiOperation("附近设备分页查询")
  308. public R<PageBean<DeviceInfoDto.Vo2>> nearbyPage(@RequestBody DeviceInfoDto.Page page) {
  309. if (!Emptys.check(page.getLon()) || !Emptys.check(page.getLat())) {
  310. throw new CommRuntimeException("经纬度不能为空");
  311. }
  312. return R.ok(queryPage(page));
  313. }
  314. @ApiOperation(value = "商户设备授权", hidden = true)
  315. @Override
  316. @Transactional(rollbackFor = Exception.class)
  317. public R<Boolean> mercDeviceAuth(DeviceInfoDto.MercDeviceAuthDto auth) {
  318. Long mercId = auth.getMercId();
  319. String mercCode = auth.getMercCode();
  320. Long algorithmId = auth.getAlgorithmId();
  321. String mercName = auth.getMercName();
  322. //商户最终设备列表
  323. List<Long> deviceIds = auth.getDeviceIds();
  324. List<DeviceInfo> devices = getDevicesByMercId(mercId);
  325. //取消商户设备授权
  326. if (CollUtil.isEmpty(deviceIds)) {
  327. if (CollUtil.isEmpty(devices)) {
  328. return R.ok(Boolean.TRUE);
  329. }
  330. }
  331. //更新商户设备授权
  332. List<DeviceInfo> deviceInfos = this.listByIds(deviceIds);
  333. for (DeviceInfo deviceInfo : deviceInfos) {
  334. int refMercId = deviceInfo.getMercId().intValue();
  335. String refMercCode = deviceInfo.getMercCode();
  336. // 只有解绑后,才能给顶级商户授权
  337. if (refMercId != -1 && refMercId != mercId.intValue()) {
  338. StrBuilder sb = StrBuilder.create();
  339. String errMsg = sb.append("设备[")
  340. .append(deviceInfo.getDeviceId())
  341. .append("]")
  342. .append("已被商户[")
  343. .append(deviceInfo.getMercName())
  344. .append("]绑定,请先进行解绑!")
  345. .toString();
  346. //非质检商户需要进行判断,质检商户跳过
  347. if (!QA_MERC_CODE.equals(refMercCode)) {
  348. //已关联别商户
  349. return R.fail(errMsg, Boolean.FALSE);
  350. }
  351. }
  352. //绑定关系
  353. deviceInfo.setMercId(mercId).setMercCode(mercCode).setAlgorithmId(algorithmId).setMercName(mercName);
  354. }
  355. saveOrUpdateBatch(deviceInfos);
  356. // //原来存在的设备关系,不在最终设备列表中的移除
  357. // if (CollUtil.isNotEmpty(devices)) {
  358. // List<Long> oldIds = new ArrayList<>();
  359. // List<Long> removeIds = new ArrayList<>();
  360. // devices.forEach(device -> oldIds.add(device.getDeviceId()));
  361. // oldIds.forEach(deviceId -> {
  362. // //不在最终设备列表中的待移除
  363. // if (!deviceIds.contains(deviceId)) {
  364. // removeIds.add(deviceId);
  365. // }
  366. // });
  367. // if (CollUtil.isNotEmpty(removeIds)) {
  368. // List<DeviceInfo> removeList = this.listByIds(removeIds);
  369. // removeMerRefDevices(removeList, parentId);
  370. // }
  371. // }
  372. return R.ok(Boolean.TRUE);
  373. }
  374. /**
  375. * 解绑机器 回收
  376. *
  377. * @param dto
  378. * @return
  379. */
  380. @Override
  381. public R<Boolean> unBindMercDevice(DeviceInfoDto.MercDeviceUnBindDto dto) {
  382. List<DeviceInfo> deviceInfos = this.listByIds(dto.getDeviceIds());
  383. return R.ok(removeMerRefDevicesToTopMerc(deviceInfos));
  384. }
  385. /**
  386. * 回收机器
  387. *
  388. * @param deviceInfos
  389. * @return
  390. */
  391. private Boolean removeMerRefDevicesToTopMerc(List<DeviceInfo> deviceInfos) {
  392. MercDto.Vo mercCheck = R.feignCheckData(mercFeignService.obj(new MercDto.ListDTO().setMercCode(QA_MERC_CODE)));
  393. if (CollUtil.isNotEmpty(deviceInfos)) {
  394. deviceInfos.forEach(deviceInfo -> {
  395. //回收
  396. deviceInfo.setMercId(mercCheck.getId());
  397. deviceInfo.setMercDeviceCode(StrUtil.EMPTY);
  398. deviceInfo.setMercName(mercCheck.getName());
  399. deviceInfo.setMercCode(QA_MERC_CODE);
  400. });
  401. //批量更新
  402. return updateBatchById(deviceInfos);
  403. }
  404. return Boolean.FALSE;
  405. }
  406. /**
  407. * 批量移除商户设备绑定关系
  408. *
  409. * @param deviceInfos
  410. * @return
  411. */
  412. private Boolean removeMerRefDevices(List<DeviceInfo> deviceInfos, Long parentId) {
  413. if (CollUtil.isNotEmpty(deviceInfos) && parentId != null) {
  414. deviceInfos.forEach(deviceInfo -> {
  415. //非顶级兴元商户,解绑后,机器归父商户
  416. if (parentId != 1) {
  417. MercDto.Vo mercParent = R.feignCheckData(mercFeignService.obj(new MercDto.ListDTO().setId(parentId)));
  418. if (mercParent != null) {
  419. deviceInfo.setMercId(mercParent.getId());
  420. deviceInfo.setMercName(mercParent.getName());
  421. deviceInfo.setMercCode(mercParent.getMercCode());
  422. } else {
  423. deviceInfo.setMercId(-1L);
  424. deviceInfo.setMercName(StrUtil.EMPTY);
  425. deviceInfo.setMercCode(StrUtil.EMPTY);
  426. }
  427. }
  428. //一级商户,解绑后,直接释放
  429. if (parentId == 0) {
  430. MercDto.Vo mercCheck = R.feignCheckData(mercFeignService.obj(new MercDto.ListDTO().setMercCode(QA_MERC_CODE)));
  431. if (mercCheck != null) {
  432. deviceInfo.setMercId(mercCheck.getId());
  433. deviceInfo.setMercName(mercCheck.getName());
  434. deviceInfo.setMercCode(mercCheck.getMercCode());
  435. } else {
  436. deviceInfo.setMercId(-1L);
  437. deviceInfo.setMercName(StrUtil.EMPTY);
  438. deviceInfo.setMercCode(StrUtil.EMPTY);
  439. }
  440. }
  441. });
  442. //批量更新
  443. return updateBatchById(deviceInfos);
  444. }
  445. return Boolean.FALSE;
  446. }
  447. @ApiOperation("集合查询")
  448. @Override
  449. public R<List<DeviceInfoDto.Vo>> list(DeviceInfoDto.ListDto dto) {
  450. List<DeviceInfo> list = list(new LambdaQueryWrapper<DeviceInfo>()
  451. .in(CollUtil.isNotEmpty(dto.getDeviceIds()), DeviceInfo::getDeviceId, dto.getDeviceIds())
  452. .eq(Emptys.check(dto.getMercId()),DeviceInfo::getMercId,dto.getMercId())
  453. );
  454. return R.ok(copy(DeviceInfoDto.Vo.class, list));
  455. }
  456. @Override
  457. @ApiOperation("通用集合查询")
  458. public R<List<DeviceInfoDto.Vo>> listCommon(DeviceInfoDto.ListCommon dto) {
  459. String deviceSearch = dto.getDeviceSearch();
  460. DeviceInfoDto.Vo vo = dto.getVo();
  461. QueryWrapper<DeviceInfo> queryWrapper = new MybatisPlusQuery().eqWrapper(vo == null ? new DeviceInfoDto.Vo() : vo, DeviceInfo.class).buildQW();
  462. List<Long> placeLineIds = dto.getPlaceLineIds();
  463. List<Long> deviceIds = dto.getDeviceIds();
  464. List<String> columnList = dto.getColumnList();
  465. if (CollUtil.isNotEmpty(placeLineIds)) {
  466. queryWrapper.in(LambdaUtils.getUnderlineCaseName(DeviceInfo::getPlaceLineId), placeLineIds);
  467. }
  468. //fixed
  469. if (StrUtil.isNotEmpty(deviceSearch)) {
  470. queryWrapper.and(wrapper -> wrapper.likeRight(LambdaUtils.getUnderlineCaseName(DeviceInfo::getDeviceName), deviceSearch).or()
  471. .eq(LambdaUtils.getUnderlineCaseName(DeviceInfo::getDeviceId), deviceSearch));
  472. }
  473. if (CollUtil.isNotEmpty(columnList)) {
  474. queryWrapper.select(columnList.stream().toArray(String[]::new));
  475. }
  476. if (CollUtil.isNotEmpty(deviceIds)) {
  477. queryWrapper.in(LambdaUtils.getUnderlineCaseName(DeviceInfo::getDeviceId), deviceIds);
  478. }
  479. return R.ok(copy(DeviceInfoDto.Vo.class, list(queryWrapper)));
  480. }
  481. @Override
  482. @ApiOperation("商户设备算法列表")
  483. public R<List<Long>> mercAlgorithmIdList(DeviceInfoDto.MercAlgorithmIdListDto dto) {
  484. String algorithmIdStr = LambdaUtils.getProperty(DeviceInfo::getAlgorithmId);
  485. String mercStr = StringTools.humpToLine(LambdaUtils.getProperty(DeviceInfo::getMercId));
  486. QueryWrapper<DeviceInfo> lqw = new QueryWrapper<DeviceInfo>()
  487. .isNotNull(StringTools.humpToLine(algorithmIdStr))
  488. .eq(mercStr, dto.getMercId())
  489. .select(String.format("DISTINCT (%s) as %s", StringTools.humpToLine(algorithmIdStr), algorithmIdStr));
  490. List<Long> list = listObjs(lqw, (MapperFunction<Object, Long>) o -> (Long) o);
  491. return R.ok(list);
  492. }
  493. @Override
  494. @ApiOperation("小程序-商户设备首页统计")
  495. public R<DeviceInfoDto.MercHomeStatisticalVO> mercHomeStatistical(DeviceInfoDto.MercHomeQueryDTO dto) {
  496. Long mercId = dto.getMercId();
  497. List<Long> myDeviceIds = dto.getMyDeviceIds();
  498. //初始化数据
  499. DeviceInfoDto.MercHomeStatisticalVO mercHomeStatisticalVO = new DeviceInfoDto.MercHomeStatisticalVO()
  500. .setClosedNum(0).setOfflineNum(0)
  501. .setOnlineNum(0).setOperatingNum(0).setNeedToFillNum(0);
  502. if (CollUtil.isEmpty(myDeviceIds)) {
  503. return R.ok(mercHomeStatisticalVO);
  504. }
  505. List<DeviceInfo> mercDevices = listByIds(myDeviceIds);
  506. if (CollUtil.isEmpty(mercDevices)) {
  507. return R.ok(mercHomeStatisticalVO);
  508. }
  509. //在线、离线
  510. List<DeviceStatus> deviceStatuses = deviceStatusService.listByIds(myDeviceIds);
  511. //分组统计
  512. Map<Integer, Long> countNetstateMap = deviceStatuses.stream().collect(Collectors
  513. .groupingBy(DeviceStatus::getNetState, Collectors.counting()));
  514. Integer onlineDictValue = SysDictUtils.getValue(DictsEnum.DEVICE_ONLINE_STATUS.getKey(), DictsSonEnum.DEVICE_ONLINE_STATUS_CONNECTED.getKey(), Integer.class);
  515. Integer offlineDictValue = SysDictUtils.getValue(DictsEnum.DEVICE_ONLINE_STATUS.getKey(), DictsSonEnum.DEVICE_ONLINE_STATUS_DISCONNECT.getKey(), Integer.class);
  516. int onlineNum = countNetstateMap.get(onlineDictValue) == null ? 0 : countNetstateMap.get(onlineDictValue).intValue();
  517. int offlineNum = countNetstateMap.get(offlineDictValue) == null ? 0 : countNetstateMap.get(offlineDictValue).intValue();
  518. mercHomeStatisticalVO.setOnlineNum(onlineNum);
  519. mercHomeStatisticalVO.setOfflineNum(offlineNum);
  520. //锁机、未锁机
  521. Map<Integer, Long> countLockLstateMap = deviceStatuses.stream().collect(Collectors
  522. .groupingBy(DeviceStatus::getLockStateL, Collectors.counting()));
  523. Long lockLStateNum = countLockLstateMap.get(DeviceLockState.LOCK.getCode());
  524. Long unLockLStateNum = countLockLstateMap.get(DeviceLockState.UN_LOCK.getCode());
  525. mercHomeStatisticalVO.setOperatingNum(unLockLStateNum == null ? 0 : unLockLStateNum.intValue());
  526. mercHomeStatisticalVO.setClosedNum(lockLStateNum == null ? 0 : lockLStateNum.intValue());
  527. //待补货
  528. Integer deviceNum = R.feignCheckData(goodsDeviceService.countOutOfStockDevice(new GoodsDeviceDto.CountOutOfStockDevice().setMercId(mercId)));
  529. mercHomeStatisticalVO.setNeedToFillNum(deviceNum);
  530. return R.ok(mercHomeStatisticalVO);
  531. }
  532. @Override
  533. @ApiOperation("小程序-商户设备首页列表")
  534. public R<List<DeviceInfoDto.MercHomeListVO>> mercHomeList(DeviceInfoDto.MercHomeQueryDTO dto) {
  535. Long mercId = dto.getMercId();
  536. String deviceName = dto.getDeviceName();
  537. Long deviceId = dto.getDeviceId();
  538. List<DeviceInfoDto.MercHomeCountVO> list = this.baseMapper.merHomeCountList(dto);
  539. if (CollUtil.isEmpty(list)) {
  540. return R.ok(Collections.emptyList());
  541. }
  542. List<DeviceInfoDto.MercHomeListVO> dataList = new ArrayList<>(list.size());
  543. LambdaQueryWrapper<DeviceInfo> lqw = new LambdaQueryWrapper<>();
  544. lqw.eq(DeviceInfo::getActiveState, DeviceActiveStateEnum.TRUE.getCode());
  545. lqw.eq(mercId != null, DeviceInfo::getMercId, mercId);
  546. lqw.eq(deviceId != null, DeviceInfo::getDeviceId, deviceId);
  547. lqw.like(StrUtil.isNotEmpty(deviceName), DeviceInfo::getDeviceName, deviceName);
  548. List<DeviceInfo> deviceInfoList = this.list(lqw);
  549. //未分配线路的设置默认值
  550. deviceInfoList.stream().filter(s -> s.getPlaceLineId() == null).forEach(s -> s.setPlaceLineId(-1L));
  551. //根据线路id分组
  552. Map<Long, List<DeviceInfo>> deviceMap = deviceInfoList.stream().collect(Collectors.groupingBy(DeviceInfo::getPlaceLineId));
  553. for (DeviceInfoDto.MercHomeCountVO v : list) {
  554. DeviceInfoDto.MercHomeListVO vo = new DeviceInfoDto.MercHomeListVO();
  555. Long placeLineId = v.getPlaceLineId();
  556. vo.setDeviceNum(v.getDeviceNum());
  557. vo.setPlaceLineId(v.getPlaceLineId());
  558. //线路下的设备列表
  559. List<DeviceInfoDto.MercHomeDeviceVo> deviceInfos = BeanUtil.copyToList(deviceMap.get(placeLineId), DeviceInfoDto.MercHomeDeviceVo.class);
  560. if (CollUtil.isEmpty(deviceInfos)) {
  561. continue;
  562. }
  563. //设备销售统计
  564. String todayDate = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
  565. List<Long> deviceIds = deviceInfos.stream().map(DeviceInfoDto.MercHomeDeviceVo::getDeviceId).collect(Collectors.toList());
  566. //统计条件:当天
  567. DeviceDataDto.ListDTO deviceDataListDTO = new DeviceDataDto.ListDTO()
  568. .setDeviceIds(deviceIds).setType(DictsSonEnum.DEVICE_DATA_TYPE_DAY.getKey()).setDateValue(Integer.valueOf(todayDate)).setMercId(mercId);
  569. List<DeviceDataDto.Vo> deviceDataList = deviceDataService.list(deviceDataListDTO);
  570. Map<Long, DeviceDataDto.Vo> dataMap = new HashMap<>();
  571. if (CollUtil.isNotEmpty(deviceDataList)) {
  572. dataMap = deviceDataList.stream().collect(Collectors.toMap(DeviceDataDto.Vo::getDeviceId, d -> d));
  573. }
  574. //设备状态查询
  575. List<DeviceStatusDto.Vo> deviceStatusList = deviceStatusService.list(new DeviceStatusDto.SelectList().setDeviceIds(deviceIds)).getData();
  576. Map<Long, DeviceStatusDto.Vo> datdeviceStatusMap = new HashMap<>();
  577. if (CollUtil.isNotEmpty(deviceStatusList)) {
  578. datdeviceStatusMap = deviceStatusList.stream().collect(Collectors.toMap(DeviceStatusDto.Vo::getDeviceId, d -> d));
  579. }
  580. List<GoodsDeviceDto.Vo> goodsDeviceList = R.feignCheckData(goodsService.queryGoodsDeviceInfo(new GoodsDto.QueryGoodsDeviceInfo().setMercId(mercId).setDeviceIds(deviceIds)));
  581. Map<Long, List<GoodsDeviceDto.Vo>> deviceIdGoodsMap = goodsDeviceList.stream()
  582. .collect(Collectors.groupingBy(GoodsDeviceDto.Vo::getDeviceId));
  583. for (DeviceInfoDto.MercHomeDeviceVo device : deviceInfos) {
  584. Long dId = device.getDeviceId();
  585. //设备类型 反显
  586. SysDictRedis dictDeviceType = SysDictUtils.get(DictConsts.DEVICE_TYPE, String.valueOf(device.getDeviceType()));
  587. device.setDeviceTypeName(dictDeviceType.getMsg());
  588. //运营状态 反显
  589. SysDictRedis dictBusyState = SysDictUtils.get(DictConsts.DEVICE_BUSY_STATUS, String.valueOf(device.getBusyState()));
  590. device.setBusyStateName(dictBusyState.getMsg());
  591. DeviceDataDto.Vo deviceData = dataMap.get(dId);
  592. Integer zero = new Integer(0);
  593. //今日销售、库存情况 反显
  594. device.setDayOrderNum(deviceData != null ? deviceData.getSalesCount() : zero);
  595. device.setDaySalesPrice(deviceData != null ? deviceData.getSalesMoney() : zero);
  596. DeviceStatusDto.Vo deviceStatus = datdeviceStatusMap.get(device.getDeviceId());
  597. if (CollUtil.isNotEmpty(deviceIdGoodsMap)) {
  598. List<GoodsDeviceDto.Vo> goodsDevice = deviceIdGoodsMap.get(dId);
  599. if (CollUtil.isNotEmpty(goodsDevice)) {
  600. device.setOnSaleNum(goodsDevice.stream().mapToInt(GoodsDeviceDto.Vo::getStock).sum());
  601. device.setFillNum(goodsDevice.stream().mapToInt(GoodsDeviceDto.Vo::getFillCount).sum());
  602. }
  603. }
  604. //联网状态
  605. Integer netState = deviceStatus == null ? DeviceNetSateType.DISCONNECT.getCode() : deviceStatus.getNetState();
  606. device.setNetState(netState);
  607. if (netState == null) {
  608. device.setNetStateName(StrUtil.EMPTY);
  609. } else {
  610. device.setNetStateName(DeviceNetSateType.getEnumByCode(deviceStatus.getNetState()).getDescription());
  611. }
  612. Integer deviceStateL = deviceStatus.getLockStateL();
  613. Integer deviceStateR = deviceStatus.getLockStateR();
  614. device.setDeviceStateL(deviceStateL);
  615. device.setDeviceStateR(deviceStateR);
  616. DeviceLockState deviceLockStateL = DeviceLockState.getEnumByCode(deviceStateL);
  617. DeviceLockState deviceLockStateR = DeviceLockState.getEnumByCode(deviceStateR);
  618. device.setDeviceStateRName(deviceLockStateR == null ? "未知" : deviceLockStateR.getDescription());
  619. device.setDeviceStateLName(deviceLockStateL == null ? "未知" : deviceLockStateL.getDescription());
  620. }
  621. //在线排序
  622. if (CollUtil.isNotEmpty(deviceInfos)) {
  623. deviceInfos = ListUtil.sortByProperty(deviceInfos, LambdaUtils.getProperty(DeviceInfoDto.MercHomeDeviceVo::getNetState));
  624. }
  625. vo.setDeviceInfos(deviceInfos);
  626. dataList.add(vo);
  627. }
  628. return R.ok(dataList);
  629. }
  630. /**
  631. * 获取商户设备列表
  632. *
  633. * @param mercId
  634. * @return
  635. */
  636. private List<DeviceInfo> getDevicesByMercId(Long mercId) {
  637. return list(Wrappers.<DeviceInfo>lambdaQuery().eq(DeviceInfo::getMercId, mercId).eq(DeviceInfo::getActiveState, DeviceActiveStateEnum.TRUE.getCode()));
  638. }
  639. /**
  640. * 小程序商户设备搜索
  641. *
  642. * @param page
  643. * @return
  644. */
  645. @Override
  646. public R<PageBean<DeviceInfoDto.MerHomeSearchVO>> mercDeviceSearchPage(@RequestBody DeviceInfoDto.Page page) {
  647. PageBean<DeviceInfoDto.MerHomeSearchVO> pageData = new PageBean<>();
  648. //小程序独有查询字段 缺货状态:stockStatus ,是否查故障设备:fault
  649. Boolean fault = page.getFault();
  650. Long mercId = page.getMercId();
  651. List<Long> myDeviceIds = page.getMyDeviceIds();
  652. if (CollUtil.isEmpty(myDeviceIds)) {
  653. //无设备
  654. return R.ok(pageData);
  655. }
  656. if (BooleanUtil.isTrue(fault)) {
  657. //查询故障设备
  658. List<DeviceEventMsg> deviceEventMsgs = deviceEventMsgService.list(Wrappers.<DeviceEventMsg>lambdaQuery()
  659. .eq(mercId != null, DeviceEventMsg::getMercId, page.getMercId())
  660. .in(DeviceEventMsg::getDeviceId, myDeviceIds));
  661. List<Long> deviceIdList = deviceEventMsgs.stream().map(DeviceEventMsg::getDeviceId).collect(Collectors.toList());
  662. if (CollUtil.isEmpty(deviceIdList)) {
  663. return R.ok(new PageBean<>());
  664. }
  665. page.setDeviceIdList(deviceIdList);
  666. } else {
  667. page.setDeviceIdList(myDeviceIds);
  668. }
  669. PageBean<DeviceInfoDto.Vo2> pageBean = queryPage(page);
  670. List<DeviceInfoDto.Vo2> records = pageBean.getRecords();
  671. if (CollUtil.isEmpty(records)) {
  672. return R.ok(pageData);
  673. }
  674. List<DeviceInfoDto.MerHomeSearchVO> merHomeSearchRecords = new ArrayList<>();
  675. BeanUtil.copyProperties(pageBean, pageData);
  676. if (CollUtil.isNotEmpty(records)) {
  677. List<Long> deviceIds = records.stream().map(DeviceInfoDto.Vo2::getDeviceId).collect(Collectors.toList());
  678. String type = SysDictUtils.getValue(DictsEnum.DEVICE_DATA_TYPE.getKey(), DictsSonEnum.DEVICE_DATA_TYPE_DAY.getKey(), String.class);
  679. String todayDate = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
  680. //查询当天
  681. DeviceDataDto.ListDTO dto = new DeviceDataDto.ListDTO()
  682. .setDeviceIds(deviceIds).setType(type).setDateValue(Integer.valueOf(todayDate)).setMercId(mercId);
  683. List<DeviceDataDto.Vo> deviceDataList = deviceDataService.list(dto);
  684. Map<Long, DeviceDataDto.Vo> dataMap = MapUtil.newHashMap();
  685. //统计数据反显
  686. if (CollUtil.isNotEmpty(deviceDataList)) {
  687. dataMap = deviceDataList.stream().collect(Collectors.toMap(DeviceDataDto.Vo::getDeviceId, d -> d));
  688. }
  689. for (DeviceInfoDto.Vo2 v : records) {
  690. DeviceInfoDto.MerHomeSearchVO merHomeSearchVO = new DeviceInfoDto.MerHomeSearchVO();
  691. Long deviceId = v.getDeviceId();
  692. DeviceDataDto.Vo vo = dataMap.get(deviceId);
  693. if (vo != null) {
  694. //今日订单数
  695. v.setDayOrderNum(vo != null ? vo.getSalesCount() : 0);
  696. v.setDaySalesPrice(vo != null ? vo.getSalesMoney() : 0);
  697. BeanUtil.copyProperties(vo, merHomeSearchVO);
  698. }
  699. DeviceSysinfoDto.Vo deviceSysinfo = v.getDeviceSysinfo();
  700. DeviceStatusDto.Vo deviceStatus = v.getDeviceStatus();
  701. merHomeSearchVO.setAppUpmVersion(deviceSysinfo.getAppUpmVersion());
  702. merHomeSearchVO.setTempValue(deviceStatus.getTempValue());
  703. merHomeSearchVO.setNetDbm(deviceStatus.getNetDbm());
  704. Integer deviceStateL = deviceStatus.getLockStateL();
  705. Integer deviceStateR = deviceStatus.getLockStateR();
  706. merHomeSearchVO.setDeviceStateL(deviceStateL);
  707. merHomeSearchVO.setDeviceStateR(deviceStateR);
  708. DeviceLockState deviceLockStateL = DeviceLockState.getEnumByCode(deviceStateL);
  709. DeviceLockState deviceLockStateR = DeviceLockState.getEnumByCode(deviceStateR);
  710. merHomeSearchVO.setDeviceStateRName(deviceLockStateR == null ? "未知" : deviceLockStateR.getDescription());
  711. merHomeSearchVO.setDeviceStateLName(deviceLockStateL == null ? "未知" : deviceLockStateL.getDescription());
  712. merHomeSearchRecords.add(merHomeSearchVO);
  713. }
  714. pageData.setRecords(merHomeSearchRecords);
  715. }
  716. return R.ok(pageData);
  717. }
  718. /**
  719. * 小程序商户设备详情-数据统计
  720. *
  721. * @param dto
  722. * @return
  723. */
  724. @Override
  725. public R<DeviceInfoDto.DeviceDataCountVO> dataCount(@RequestBody DeviceInfoDto.DeviceDataCountDTO dto) {
  726. // 统计类型(1=经营数据,2=经营图表,3=温度图表,4=信号图表,5=商品管理)
  727. Integer type = dto.getType();
  728. switch (type) {
  729. case 1:
  730. //经营数据
  731. return R.ok(dataCount1(dto));
  732. case 2:
  733. //经营图表
  734. return R.ok(dataCount2(dto));
  735. case 3:
  736. //温度图表
  737. return R.ok(dataCount3(dto));
  738. case 4:
  739. //信号图表
  740. return R.ok(dataCount4(dto));
  741. case 5:
  742. //商品管理
  743. return R.ok(dataCount5(dto));
  744. default:
  745. break;
  746. }
  747. return R.ok();
  748. }
  749. /**
  750. * 经营数据
  751. *
  752. * @param dto
  753. * @return
  754. */
  755. private DeviceInfoDto.DeviceDataCountVO dataCount1(DeviceInfoDto.DeviceDataCountDTO dto) {
  756. Long deviceId = dto.getDeviceId();
  757. Long mercId = dto.getMercId();
  758. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  759. //当天
  760. DeviceDataDto.Vo dayData = deviceDataService.getByDay(deviceId, mercId, DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
  761. if (dayData != null) {
  762. //今日退款成功订单金额
  763. OrderRefundDto.CountByDateVO countByDateVO = R.feignCheckData(
  764. refundService.countByDate(new OrderRefundDto.CountByDateDTO()
  765. .setDate(DateTime.now())
  766. .setMercId(mercId).setDeviceId(deviceId)));
  767. Integer hisRefundMoney = countByDateVO.getHisRefundMoney();
  768. Integer todayRefundMoney = countByDateVO.getTodayRefundMoney();
  769. //今日销售额 (扣除今日的订单的退款金额)
  770. if (dayData.getSalesMoney() == null) {
  771. dayData.setSalesMoney(0);
  772. } else {
  773. dayData.setSalesMoney(dayData.getSalesMoney() - todayRefundMoney);
  774. }
  775. dayData.setRefundMoney(hisRefundMoney + todayRefundMoney);
  776. }
  777. //当月
  778. DeviceDataDto.Vo monthData = deviceDataService.getByMonth(deviceId, mercId, DateUtil.format(new Date(), DatePattern.SIMPLE_MONTH_PATTERN));
  779. if (monthData != null) {
  780. OrderRefundDto.CountByMonthVO countByMonthVO = R.feignCheckData(refundService.countByMonth(new OrderRefundDto.CountByMonthDTO().setCurMonthDate(DateTime.now()).setMercId(mercId).setDeviceId(deviceId)));
  781. Integer hisMonthRefundMoney = countByMonthVO.getHisMonthRefundMoney();
  782. Integer monthRefundMoney = countByMonthVO.getMonthRefundMoney();
  783. monthData.setRefundMoney(hisMonthRefundMoney + monthRefundMoney);
  784. if (monthData.getSalesMoney() == null) {
  785. monthData.setSalesMoney(0);
  786. } else {
  787. monthData.setSalesMoney(monthData.getSalesMoney() - monthRefundMoney);
  788. }
  789. }
  790. vo.setDayBusinessData(copy(DeviceInfoDto.BusinessData.class, dayData));
  791. vo.setMonthBusinessData(copy(DeviceInfoDto.BusinessData.class, monthData));
  792. return vo;
  793. }
  794. /**
  795. * 经营图表
  796. *
  797. * @param dto
  798. * @return
  799. */
  800. private DeviceInfoDto.DeviceDataCountVO dataCount2(DeviceInfoDto.DeviceDataCountDTO dto) {
  801. Long deviceId = dto.getDeviceId();
  802. //近一个月 (销售额,订单数,退款金额,退款数)
  803. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  804. DeviceInfoDto.BusinessChart businessChart = new DeviceInfoDto.BusinessChart();
  805. List<String> categories = DataTime.dayListByLastDay(30);
  806. List<Integer> dateList = new ArrayList<>(30);
  807. businessChart.setCategories(categories);
  808. categories.forEach(d -> {
  809. dateList.add(Integer.valueOf(d.replaceAll(StrUtil.DASHED, StrUtil.EMPTY)));
  810. });
  811. Integer startDay = dateList.get(0);
  812. Integer endDay = dateList.get(categories.size() - 1);
  813. List<DeviceDataDto.Vo> listByDay = deviceDataService.getListByDay(deviceId, startDay, endDay);
  814. if (CollUtil.isEmpty(listByDay)) {
  815. return vo;
  816. }
  817. //每天的数据
  818. Map<Integer, DeviceDataDto.Vo> dataDayMap = listByDay.stream().collect(Collectors.toMap(DeviceDataDto.Vo::getDateValue, i -> i));
  819. List<DeviceInfoDto.MyChartSeries3> series = new ArrayList<>();
  820. String[] names = {"销售额", "订单数", "退款金额", "退款数"};
  821. for (int i = 0; i < names.length; i++) {
  822. DeviceInfoDto.MyChartSeries3 myChartSeries = new DeviceInfoDto.MyChartSeries3();
  823. //某个类型每天的数据
  824. List<String> data = new ArrayList<>();
  825. if (i == 0) {
  826. //销售额
  827. dateList.forEach(d -> {
  828. //每日数据填充
  829. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  830. if (deviceData == null) {
  831. data.add(String.valueOf(BigDecimal.ZERO));
  832. } else {
  833. Integer salesMoney = deviceData.getSalesMoney() == null ? 0 : deviceData.getSalesMoney();
  834. BigDecimal day = BigDecimal.valueOf(salesMoney).divide(BigDecimal.valueOf(100));
  835. data.add(String.valueOf(day));
  836. }
  837. });
  838. } else if (i == 1) {
  839. //订单数
  840. dateList.forEach(d -> {
  841. //每日数据填充
  842. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  843. String value = "0";
  844. if (deviceData == null) {
  845. data.add(value);
  846. } else {
  847. data.add(deviceData == null ? value : String.valueOf(deviceData.getSalesCount()));
  848. }
  849. });
  850. } else if (i == 2) {
  851. //退款金额
  852. dateList.forEach(d -> {
  853. //每日数据填充
  854. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  855. if (deviceData == null) {
  856. data.add(String.valueOf(BigDecimal.ZERO));
  857. } else {
  858. Integer refundMoney = deviceData.getRefundMoney() == null ? 0 : deviceData.getRefundMoney();
  859. BigDecimal day = BigDecimal.valueOf(refundMoney).divide(BigDecimal.valueOf(100));
  860. data.add(String.valueOf(day));
  861. }
  862. });
  863. } else if (i == 3) {
  864. //退款数
  865. dateList.forEach(d -> {
  866. //每日数据填充
  867. DeviceDataDto.Vo deviceData = dataDayMap.get(d);
  868. if (deviceData == null) {
  869. data.add("0");
  870. } else {
  871. data.add(deviceData == null ? "0" : String.valueOf(deviceData.getRefundCount()));
  872. }
  873. });
  874. }
  875. myChartSeries.setName(names[i]);
  876. myChartSeries.setData(data);
  877. series.add(myChartSeries);
  878. }
  879. businessChart.setSeries(series);
  880. vo.setBusinessChart(businessChart);
  881. return vo;
  882. }
  883. /**
  884. * 温度图表
  885. *
  886. * @param dto
  887. * @return
  888. */
  889. private DeviceInfoDto.DeviceDataCountVO dataCount3(DeviceInfoDto.DeviceDataCountDTO dto) {
  890. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  891. Long deviceId = dto.getDeviceId();
  892. String choosDate = dto.getChoosDate();
  893. if (StrUtil.isEmpty(choosDate)) {
  894. choosDate = DateUtil.formatDate(new Date());
  895. }
  896. String startTime = choosDate + " 00:00:00";
  897. String endTime = choosDate + " 23:59:59";
  898. //查询选定日期的温度数据
  899. List<DeviceTempRecords> deviceTempRecords = deviceTempRecordsService.list(Wrappers.<DeviceTempRecords>lambdaQuery()
  900. .eq(DeviceTempRecords::getDeviceId, deviceId).between(DeviceTempRecords::getCreateTime, startTime, endTime)
  901. .orderBy(true, true, DeviceTempRecords::getCreateTime));
  902. if (CollUtil.isEmpty(deviceTempRecords)) {
  903. return vo;
  904. }
  905. DeviceInfoDto.TemperatureChart temperatureChart = new DeviceInfoDto.TemperatureChart();
  906. List<String> categories = new ArrayList<>();
  907. String name = "温度";
  908. List<DeviceInfoDto.MyChartSeries2> series = new ArrayList<>();
  909. List<BigDecimal> data = new ArrayList<>();
  910. deviceTempRecords.forEach(d -> {
  911. int tempValue = d.getTempValue();
  912. LocalDateTime createTime = d.getCreateTime();
  913. String time = DateUtil.format(createTime, "HH:mm:ss");
  914. categories.add(time);
  915. data.add(NumberUtil.toBigDecimal(tempValue));
  916. });
  917. DeviceInfoDto.MyChartSeries2 myChartSeries = new DeviceInfoDto.MyChartSeries2();
  918. myChartSeries.setName(name);
  919. myChartSeries.setData(data);
  920. series.add(myChartSeries);
  921. temperatureChart.setSeries(series);
  922. temperatureChart.setCategories(categories);
  923. vo.setTemperatureChart(temperatureChart);
  924. return vo;
  925. }
  926. /**
  927. * 信号图表
  928. *
  929. * @param dto
  930. * @return
  931. */
  932. private DeviceInfoDto.DeviceDataCountVO dataCount4(DeviceInfoDto.DeviceDataCountDTO dto) {
  933. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  934. Long deviceId = dto.getDeviceId();
  935. String choosDate = dto.getChoosDate();
  936. if (StrUtil.isEmpty(choosDate)) {
  937. choosDate = DateUtil.formatDate(new Date());
  938. }
  939. String startTime = choosDate + " 00:00:00";
  940. String endTime = choosDate + " 23:59:59";
  941. //查询选定日期的温度数据
  942. List<DeviceNetRecord> deviceNetRecords = deviceNetRecordService.list(Wrappers.<DeviceNetRecord>lambdaQuery()
  943. .eq(DeviceNetRecord::getDeviceId, deviceId).between(DeviceNetRecord::getCreateTime, startTime, endTime)
  944. .orderBy(true, true, DeviceNetRecord::getCreateTime));
  945. if (CollUtil.isEmpty(deviceNetRecords)) {
  946. return vo;
  947. }
  948. DeviceInfoDto.SignalChart signalChart = new DeviceInfoDto.SignalChart();
  949. List<String> categories = new ArrayList<>();
  950. String name = "信号";
  951. List<DeviceInfoDto.MyChartSeries> series = new ArrayList<>();
  952. List<Integer> data = new ArrayList<>();
  953. deviceNetRecords.forEach(d -> {
  954. Integer value = d.getSimDbm();
  955. LocalDateTime createTime = d.getCreateTime();
  956. String time = DateUtil.format(createTime, "HH:mm:ss");
  957. categories.add(time);
  958. data.add(value);
  959. });
  960. DeviceInfoDto.MyChartSeries myChartSeries = new DeviceInfoDto.MyChartSeries();
  961. myChartSeries.setName(name);
  962. myChartSeries.setData(data);
  963. series.add(myChartSeries);
  964. signalChart.setSeries(series);
  965. signalChart.setCategories(categories);
  966. vo.setSignalChart(signalChart);
  967. return vo;
  968. }
  969. /**
  970. * 商品管理
  971. *
  972. * @param dto
  973. * @return
  974. */
  975. private DeviceInfoDto.DeviceDataCountVO dataCount5(DeviceInfoDto.DeviceDataCountDTO dto) {
  976. Long deviceId = dto.getDeviceId();
  977. DeviceInfoDto.DeviceDataCountVO vo = new DeviceInfoDto.DeviceDataCountVO();
  978. DeviceInfoDto.GoodsData goodsData = new DeviceInfoDto.GoodsData();
  979. //在售商品种类
  980. //根据设备ID查商品id
  981. GoodsDeviceDto.SelectList selectList = new GoodsDeviceDto.SelectList();
  982. selectList.setDeviceIds(CollUtil.newArrayList(deviceId));
  983. selectList.setMercId(dto.getMercId());
  984. R<List<GoodsDeviceDto.Vo>> r = R.feignCheck(goodsDeviceService.list(selectList));
  985. List<GoodsDeviceDto.Vo> goodsDeviceList = r.getData();
  986. Integer stock = 0;
  987. Integer afterFillStock = 0;
  988. if (CollUtil.isNotEmpty(goodsDeviceList)) {
  989. stock = goodsDeviceList.stream().mapToInt(GoodsDeviceDto.Vo::getStock).sum();
  990. afterFillStock = goodsDeviceList.stream().mapToInt(GoodsDeviceDto.Vo::getFillCount).sum();
  991. }
  992. goodsData.setAfterFillStock(afterFillStock);
  993. goodsData.setStock(stock);
  994. goodsData.setCategoryNum(CollUtil.isNotEmpty(goodsDeviceList) ? goodsDeviceList.size() : new Integer(0));
  995. vo.setGoodsData(goodsData);
  996. return vo;
  997. }
  998. public PageBean<DeviceInfoDto.Vo2> queryPage(DeviceInfoDto.Page page) {
  999. IPage<DeviceInfoQueryPage> iPage = baseMapper.queryPage(toIPage(page.getPage()), page);
  1000. return toPageBean(DeviceInfoDto.Vo2.class, iPage);
  1001. }
  1002. private <T> void check(T value, T value2, String msg) {
  1003. if (value.toString().equals(value2.toString())) {
  1004. throw new CommRuntimeException(msg);
  1005. }
  1006. }
  1007. }