DeviceInfoServiceImpl.java 77 KB

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