DeviceInfoServiceImpl.java 71 KB

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