MesDeviceController.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. package com.jeesite.modules.mes.web;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Map;
  4. import java.util.List;
  5. import java.util.Date;
  6. import java.util.Calendar;
  7. import java.util.stream.Collectors;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import com.alibaba.fastjson.JSON;
  11. import com.jeesite.common.entity.Page;
  12. import com.jeesite.common.lang.ObjectUtils;
  13. import com.jeesite.modules.mes.entity.MesDeviceCate;
  14. import com.jeesite.modules.mes.entity.MesDeviceForm;
  15. import com.jeesite.modules.mes.entity.MesDevicePreventTask;
  16. import com.jeesite.modules.mes.entity.MesDeviceState;
  17. import com.jeesite.modules.mes.entity.MesDeviceUrgency;
  18. import com.jeesite.modules.mes.entity.MesLineProcess;
  19. import com.jeesite.modules.mes.resp.CommonResp;
  20. import com.jeesite.modules.mes.service.MesDeviceCateService;
  21. import com.jeesite.modules.mes.service.MesDevicePreventTaskService;
  22. import com.jeesite.modules.mes.service.MesDeviceStateService;
  23. import com.jeesite.modules.mes.service.MesDeviceUrgencyService;
  24. import org.apache.shiro.authz.annotation.RequiresPermissions;
  25. import org.springframework.beans.factory.annotation.Autowired;
  26. import org.springframework.stereotype.Controller;
  27. import org.springframework.ui.Model;
  28. import org.springframework.validation.annotation.Validated;
  29. import org.springframework.web.bind.annotation.ModelAttribute;
  30. import org.springframework.web.bind.annotation.PostMapping;
  31. import org.springframework.web.bind.annotation.RequestMapping;
  32. import org.springframework.web.bind.annotation.ResponseBody;
  33. import com.jeesite.common.config.Global;
  34. import com.jeesite.common.collect.ListUtils;
  35. import com.jeesite.common.collect.MapUtils;
  36. import com.jeesite.common.lang.StringUtils;
  37. import com.jeesite.common.idgen.IdGen;
  38. import com.jeesite.modules.sys.utils.UserUtils;
  39. import com.jeesite.common.lang.DateUtils;
  40. import com.jeesite.common.utils.excel.ExcelExport;
  41. import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
  42. import org.springframework.web.multipart.MultipartFile;
  43. import com.jeesite.common.web.BaseController;
  44. import com.jeesite.modules.mes.entity.MesDevice;
  45. import com.jeesite.modules.mes.service.MesDeviceService;
  46. /**
  47. * 设备Controller
  48. * @author mes
  49. * @version 2023-07-12
  50. */
  51. @Controller
  52. @RequestMapping(value = "${adminPath}/mes/mesDevice")
  53. public class MesDeviceController extends BaseController {
  54. @Autowired
  55. private MesDeviceService mesDeviceService;
  56. @Autowired
  57. private MesDeviceCateService mesDeviceCateService;
  58. @Autowired
  59. private MesDevicePreventTaskService mesDevicePreventTaskService;
  60. @Autowired
  61. private MesDeviceStateService mesDeviceStateService;
  62. @Autowired
  63. private MesDeviceUrgencyService mesDeviceUrgencyService;
  64. /**
  65. * 获取数据
  66. */
  67. @ModelAttribute
  68. public MesDevice get(String treeCode, boolean isNewRecord) {
  69. return mesDeviceService.get(treeCode, isNewRecord);
  70. }
  71. /**
  72. * 管理主页
  73. */
  74. @RequiresPermissions("mes:mesDevice:view")
  75. @RequestMapping(value = "index")
  76. public String index(MesDevice mesDevice, Model model) {
  77. model.addAttribute("mesDevice", mesDevice);
  78. return "modules/mes/mesDeviceIndex";
  79. }
  80. /**
  81. * 查询列表
  82. */
  83. @RequiresPermissions("mes:mesDevice:view")
  84. @RequestMapping(value = {"list", ""})
  85. public String list(MesDevice mesDevice, MesDeviceCate mesDeviceCate, Model model) {
  86. model.addAttribute("mesDevice", mesDevice);
  87. model.addAttribute("mesDeviceCate", mesDeviceCateService.findList(mesDeviceCate));
  88. return "modules/mes/mesDeviceList";
  89. }
  90. /**
  91. * 查询列表数据
  92. */
  93. // @RequiresPermissions("mes:mesDevice:view")
  94. // @RequestMapping(value = "listData")
  95. // @ResponseBody
  96. // public List<MesDevice> listData(MesDevice mesDevice) {
  97. // if (StringUtils.isBlank(mesDevice.getParentCode())) {
  98. // mesDevice.setParentCode(MesDevice.ROOT_CODE);
  99. // }
  100. // if (StringUtils.isNotBlank(mesDevice.getRemark())){
  101. // mesDevice.setParentCode(null);
  102. // }
  103. // if (StringUtils.isNotBlank(mesDevice.getTreeName())){
  104. // mesDevice.setParentCode(null);
  105. // }
  106. // if (StringUtils.isNotBlank(mesDevice.getSn())){
  107. // mesDevice.setParentCode(null);
  108. // }
  109. // if (StringUtils.isNotBlank(mesDevice.getIp())){
  110. // mesDevice.setParentCode(null);
  111. // }
  112. // List<MesDevice> list = mesDeviceService.findList(mesDevice);
  113. // for (MesDevice i:list){
  114. // mesDevice.setTreeCode(i.getParentCode());
  115. // MesDevice parent = mesDeviceService.findByInfo(mesDevice);
  116. // if(parent==null){
  117. // i.setParentSn("");
  118. // }else {
  119. // i.setParentSn(parent.getSn());
  120. // }
  121. // }
  122. //
  123. // return list;
  124. // }
  125. @RequiresPermissions("mes:mesDevice:view")
  126. @RequestMapping(value = "listData")
  127. @ResponseBody
  128. public Page<MesDevice> listData(MesDevice mesDevice, HttpServletRequest request, HttpServletResponse response) {
  129. // System.out.println(request.getParameterMap());
  130. mesDevice.setPage(new Page<>(request, response));
  131. Page<MesDevice> page = mesDeviceService.findPage(mesDevice);
  132. return page;
  133. }
  134. /**
  135. * 查看编辑表单
  136. */
  137. @RequiresPermissions("mes:mesDevice:view")
  138. @RequestMapping(value = "form")
  139. public String form(MesDevice mesDevice,MesDeviceCate mesDeviceCate, Model model) {
  140. // 创建并初始化下一个节点信息
  141. mesDevice = createNextNode(mesDevice);
  142. logger.info(JSON.toJSONString(mesDevice));
  143. model.addAttribute("mesDevice", mesDevice);
  144. model.addAttribute("mesDeviceCate", mesDeviceCateService.findList(mesDeviceCate));
  145. return "modules/mes/mesDeviceForm";
  146. }
  147. /**
  148. * 详情
  149. */
  150. @RequiresPermissions("mes:mesDevice:view")
  151. @RequestMapping(value = "detail")
  152. public String detail(MesDevice mesDevice,MesDeviceCate mesDeviceCate, Model model) {
  153. // 创建并初始化下一个节点信息
  154. mesDevice.setTreeCode(mesDevice.getParentCode());
  155. MesDevice parent = mesDeviceService.findByInfo(mesDevice);
  156. if(parent==null){
  157. mesDevice.setParentSn("");
  158. }else {
  159. mesDevice.setParentSn(parent.getSn());
  160. }
  161. mesDevice = createNextNode(mesDevice);
  162. model.addAttribute("mesDevice", mesDevice);
  163. model.addAttribute("mesDeviceCate", mesDeviceCateService.findList(mesDeviceCate));
  164. return "modules/mes/mesDeviceDetail";
  165. }
  166. /**
  167. * 创建并初始化下一个节点信息,如:排序号、默认值
  168. */
  169. @RequiresPermissions("mes:mesDevice:edit")
  170. @RequestMapping(value = "createNextNode")
  171. @ResponseBody
  172. public MesDevice createNextNode(MesDevice mesDevice) {
  173. if (StringUtils.isNotBlank(mesDevice.getParentCode())){
  174. mesDevice.setParent(mesDeviceService.get(mesDevice.getParentCode()));
  175. }
  176. if (mesDevice.getIsNewRecord()) {
  177. MesDevice where = new MesDevice();
  178. where.setParentCode(mesDevice.getParentCode());
  179. MesDevice last = mesDeviceService.getLastByParentCode(where);
  180. // 获取到下级最后一个节点
  181. if (last != null){
  182. mesDevice.setTreeSort(last.getTreeSort() + 30);
  183. mesDevice.setTreeCode(IdGen.nextCode(last.getTreeCode()));
  184. }else if (mesDevice.getParent() != null){
  185. mesDevice.setTreeCode(mesDevice.getParent().getTreeCode() + "001");
  186. }
  187. }
  188. // 以下设置表单默认数据
  189. if (mesDevice.getTreeSort() == null){
  190. mesDevice.setTreeSort(MesDevice.DEFAULT_TREE_SORT);
  191. }
  192. return mesDevice;
  193. }
  194. /**
  195. * 保存数据
  196. */
  197. @RequiresPermissions("mes:mesDevice:edit")
  198. @PostMapping(value = "save")
  199. @ResponseBody
  200. public String save(@Validated MesDevice mesDevice) {
  201. logger.info(JSON.toJSONString(mesDevice));
  202. MesDevice mesDevice1 = new MesDevice();
  203. mesDevice1.setDeviceCode(mesDevice.getDeviceCode());
  204. MesDevice info = mesDeviceService.getByEntity(mesDevice1);
  205. if (info != null && !StringUtils.equals(info.getTreeCode(), mesDevice.getTreeCode())){
  206. return renderResult(Global.FALSE, text("保存失败,设备编码已存在!"));
  207. }
  208. mesDeviceService.save(mesDevice);
  209. return renderResult(Global.TRUE, text("保存设备成功!"));
  210. }
  211. /**
  212. * 导出数据
  213. */
  214. @RequiresPermissions("mes:mesDevice:view")
  215. @RequestMapping(value = "exportData")
  216. public void exportData(MesDevice mesDevice, HttpServletResponse response) {
  217. List<MesDevice> list = mesDeviceService.findList(mesDevice);
  218. String fileName = "设备" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
  219. try(ExcelExport ee = new ExcelExport("设备", MesDevice.class)){
  220. ee.setDataList(list).write(response, fileName);
  221. }
  222. }
  223. /**
  224. * 下载模板
  225. */
  226. @RequiresPermissions("mes:mesDevice:view")
  227. @RequestMapping(value = "importTemplate")
  228. public void importTemplate(HttpServletResponse response) {
  229. MesDevice mesDevice = new MesDevice();
  230. List<MesDevice> list = ListUtils.newArrayList(mesDevice);
  231. String fileName = "设备模板.xlsx";
  232. try(ExcelExport ee = new ExcelExport("设备", MesDevice.class, Type.IMPORT)){
  233. ee.setDataList(list).write(response, fileName);
  234. }
  235. }
  236. /**
  237. * 导入数据
  238. */
  239. @ResponseBody
  240. @RequiresPermissions("mes:mesDevice:edit")
  241. @PostMapping(value = "importData")
  242. public String importData(MultipartFile file) {
  243. try {
  244. String message = mesDeviceService.importData(file);
  245. return renderResult(Global.TRUE, "posfull:"+message);
  246. } catch (Exception ex) {
  247. return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
  248. }
  249. }
  250. /**
  251. * 停用数据
  252. */
  253. @RequiresPermissions("mes:mesDevice:edit")
  254. @RequestMapping(value = "disable")
  255. @ResponseBody
  256. public String disable(MesDevice mesDevice) {
  257. MesDevice where = new MesDevice();
  258. where.setStatus(MesDevice.STATUS_NORMAL);
  259. where.setParentCodes("," + mesDevice.getId() + ",");
  260. long count = mesDeviceService.findCount(where);
  261. if (count > 0) {
  262. return renderResult(Global.FALSE, text("该设备包含未停用的子设备!"));
  263. }
  264. mesDevice.setStatus(MesDevice.STATUS_DISABLE);
  265. mesDeviceService.updateStatus(mesDevice);
  266. return renderResult(Global.TRUE, text("停用设备成功"));
  267. }
  268. /**
  269. * 启用数据
  270. */
  271. @RequiresPermissions("mes:mesDevice:edit")
  272. @RequestMapping(value = "enable")
  273. @ResponseBody
  274. public String enable(MesDevice mesDevice) {
  275. mesDevice.setStatus(MesDevice.STATUS_NORMAL);
  276. mesDeviceService.updateStatus(mesDevice);
  277. return renderResult(Global.TRUE, text("启用设备成功"));
  278. }
  279. /**
  280. * 删除数据
  281. */
  282. @RequiresPermissions("mes:mesDevice:edit")
  283. @RequestMapping(value = "delete")
  284. @ResponseBody
  285. public String delete(MesDevice mesDevice) {
  286. mesDeviceService.delete(mesDevice);
  287. return renderResult(Global.TRUE, text("删除设备成功!"));
  288. }
  289. /**
  290. * 获取树结构数据
  291. * @param excludeCode 排除的Code
  292. * @param parentCode 设置父级编码返回一级
  293. * @param isShowCode 是否显示编码(true or 1:显示在左侧;2:显示在右侧;false or null:不显示)
  294. * @return
  295. */
  296. @RequiresPermissions("mes:mesDevice:view")
  297. @RequestMapping(value = "treeData")
  298. @ResponseBody
  299. public List<Map<String, Object>> treeData(String excludeCode, String parentCode, String isShowCode) {
  300. List<Map<String, Object>> mapList = ListUtils.newArrayList();
  301. MesDevice where = new MesDevice();
  302. where.setStatus(MesDevice.STATUS_NORMAL);
  303. if (StringUtils.isNotBlank(parentCode)){
  304. where.setParentCode(parentCode);
  305. }
  306. List<MesDevice> list = mesDeviceService.findList(where);
  307. for (int i=0; i<list.size(); i++){
  308. MesDevice e = list.get(i);
  309. // 过滤非正常的数据
  310. if (!MesDevice.STATUS_NORMAL.equals(e.getStatus())){
  311. continue;
  312. }
  313. // 过滤被排除的编码(包括所有子级)
  314. if (StringUtils.isNotBlank(excludeCode)){
  315. if (e.getId().equals(excludeCode)){
  316. continue;
  317. }
  318. if (e.getParentCodes().contains("," + excludeCode + ",")){
  319. continue;
  320. }
  321. }
  322. Map<String, Object> map = MapUtils.newHashMap();
  323. map.put("id", e.getId());
  324. map.put("pId", e.getParentCode());
  325. map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getTreeCode(), e.getTreeName()));
  326. map.put("isParent", !e.getIsTreeLeaf());
  327. mapList.add(map);
  328. }
  329. return mapList;
  330. }
  331. /**
  332. * 修复表结构相关数据
  333. */
  334. @RequiresPermissions("mes:mesDevice:edit")
  335. @RequestMapping(value = "fixTreeData")
  336. @ResponseBody
  337. public String fixTreeData(MesDevice mesDevice){
  338. if (!UserUtils.getUser().isAdmin()){
  339. return renderResult(Global.FALSE, "操作失败,只有管理员才能进行修复!");
  340. }
  341. mesDeviceService.fixTreeData();
  342. return renderResult(Global.TRUE, "数据修复成功");
  343. }
  344. /**
  345. * api列表数据
  346. */
  347. @RequestMapping(value = "getList")
  348. @ResponseBody
  349. public CommonResp getList(MesDevice mesDevice) {
  350. List<MesDevice> list = mesDeviceService.findList(mesDevice);
  351. CommonResp<List<MesDevice>> resp = new CommonResp<>();
  352. resp.setData(list);
  353. return resp;
  354. }
  355. @RequiresPermissions("mes:mesDevice:view")
  356. @RequestMapping(value = "qrcode")
  357. public String qrcode(MesDevice mesDevice, Model model) {
  358. model.addAttribute("mesDevice", mesDevice);
  359. return "modules/mes/mesDeviceQrcode";
  360. }
  361. @RequestMapping(value = "infoBySn")
  362. @ResponseBody
  363. public CommonResp infoBySn(MesDevice mesDevice) {
  364. CommonResp<MesDevice> resp = new CommonResp<>();
  365. MesDevice info = mesDeviceService.findInfoBySn(mesDevice.getSn());
  366. if(ObjectUtils.isEmpty(info)){
  367. resp.setResult("false");
  368. resp.setMessage("设备不存在");
  369. return resp;
  370. }
  371. resp.setData(info);
  372. return resp;
  373. }
  374. @RequiresPermissions("mes:mesDevice:view")
  375. @RequestMapping(value = "map")
  376. public String map(MesDevice mesDevice, Model model) {
  377. model.addAttribute("mesDevice", mesDevice);
  378. return "modules/mes/equipment/equipment_map";
  379. }
  380. @RequestMapping(value = "oeeScreen")
  381. public String oeeScreen(Model model) {
  382. return "modules/mes/mesDeviceOeeScreen";
  383. }
  384. @RequestMapping(value = "screen5Data")
  385. @ResponseBody
  386. public CommonResp<Map<String, Object>> screen5Data() {
  387. CommonResp<Map<String, Object>> resp = new CommonResp<>();
  388. Map<String, Object> data = MapUtils.newHashMap();
  389. Date now = new Date();
  390. Date weekStart = DateUtils.addDays(now, -7);
  391. data.put("deviceCount", mesDeviceService.findList(new MesDevice()).size());
  392. MesDevicePreventTask preventQuery = new MesDevicePreventTask();
  393. preventQuery.setStartDate_gte(weekStart);
  394. preventQuery.setStartDate_lte(now);
  395. List<MesDevicePreventTask> preventList = mesDevicePreventTaskService.findList(preventQuery);
  396. data.put("preventiveCount", preventList.size());
  397. List<Map<String, Object>> preventiveStatus = ListUtils.newArrayList();
  398. long pending = preventList.stream().filter(p -> "0".equals(p.getState())).count();
  399. long processing = preventList.stream().filter(p -> "1".equals(p.getState())).count();
  400. long completed = preventList.stream().filter(p -> "2".equals(p.getState())).count();
  401. long unfinished = preventList.stream().filter(p -> "3".equals(p.getState())).count();
  402. Map<String, Object> pendingMap = MapUtils.newHashMap();
  403. pendingMap.put("name", "未开始");
  404. pendingMap.put("value", pending);
  405. preventiveStatus.add(pendingMap);
  406. Map<String, Object> processingMap = MapUtils.newHashMap();
  407. processingMap.put("name", "进行中");
  408. processingMap.put("value", processing);
  409. preventiveStatus.add(processingMap);
  410. Map<String, Object> completedMap = MapUtils.newHashMap();
  411. completedMap.put("name", "已完成");
  412. completedMap.put("value", completed);
  413. preventiveStatus.add(completedMap);
  414. Map<String, Object> unfinishedMap = MapUtils.newHashMap();
  415. unfinishedMap.put("name", "未完成");
  416. unfinishedMap.put("value", unfinished);
  417. preventiveStatus.add(unfinishedMap);
  418. data.put("preventiveStatus", preventiveStatus);
  419. data.put("preventiveList", preventList.stream().limit(10).collect(Collectors.toList()));
  420. MesDeviceUrgency urgencyQuery = new MesDeviceUrgency();
  421. urgencyQuery.setStartDate_gte(weekStart);
  422. urgencyQuery.setStartDate_lte(now);
  423. List<MesDeviceUrgency> urgencyList = mesDeviceUrgencyService.findList(urgencyQuery);
  424. data.put("urgencyCount", urgencyList.size());
  425. List<Map<String, Object>> urgencyStatus = ListUtils.newArrayList();
  426. long urgencyPending = urgencyList.stream().filter(u -> "0".equals(u.getState())).count();
  427. long urgencyCompleted = urgencyList.stream().filter(u -> "1".equals(u.getState())).count();
  428. Map<String, Object> urgencyPendingMap = MapUtils.newHashMap();
  429. urgencyPendingMap.put("name", "维修中");
  430. urgencyPendingMap.put("value", urgencyPending);
  431. urgencyPendingMap.put("color", "#ff9800");
  432. urgencyStatus.add(urgencyPendingMap);
  433. Map<String, Object> urgencyCompletedMap = MapUtils.newHashMap();
  434. urgencyCompletedMap.put("name", "已完成");
  435. urgencyCompletedMap.put("value", urgencyCompleted);
  436. urgencyCompletedMap.put("color", "#00d5d8");
  437. urgencyStatus.add(urgencyCompletedMap);
  438. data.put("urgencyStatus", urgencyStatus);
  439. Map<String, Long> contentCount = urgencyList.stream()
  440. .filter(u -> StringUtils.isNotBlank(u.getContent()))
  441. .collect(Collectors.groupingBy(u -> u.getContent(), Collectors.counting()));
  442. List<Map<String, Object>> urgencyContent = ListUtils.newArrayList();
  443. contentCount.entrySet().stream()
  444. .sorted((a, b) -> Long.compare(b.getValue(), a.getValue()))
  445. .limit(6)
  446. .forEach(e -> {
  447. Map<String, Object> contentMap = MapUtils.newHashMap();
  448. contentMap.put("name", e.getKey());
  449. contentMap.put("value", e.getValue());
  450. urgencyContent.add(contentMap);
  451. });
  452. data.put("urgencyContent", urgencyContent);
  453. data.put("urgencyList", urgencyList.stream().limit(10).collect(Collectors.toList()));
  454. data.put("weekStart", DateUtils.formatDate(weekStart, "yyyy-MM-dd HH:mm:ss"));
  455. data.put("weekEnd", DateUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"));
  456. resp.setData(data);
  457. resp.setResult(Global.TRUE);
  458. return resp;
  459. }
  460. @RequestMapping(value = "oeeScreenData")
  461. @ResponseBody
  462. public CommonResp<Map<String, Object>> oeeScreenData() {
  463. CommonResp<Map<String, Object>> resp = new CommonResp<>();
  464. Map<String, Object> data = MapUtils.newHashMap();
  465. Date now = new Date();
  466. Calendar calendar = Calendar.getInstance();
  467. calendar.set(Calendar.HOUR_OF_DAY, 0);
  468. calendar.set(Calendar.MINUTE, 0);
  469. calendar.set(Calendar.SECOND, 0);
  470. calendar.set(Calendar.MILLISECOND, 0);
  471. Date todayStart = calendar.getTime();
  472. long elapsedSeconds = Math.max(1L, (now.getTime() - todayStart.getTime()) / 1000);
  473. List<MesDevice> devices = mesDeviceService.findList(new MesDevice());
  474. List<Map<String, Object>> deviceCards = ListUtils.newArrayList();
  475. List<Map<String, Object>> ranking = ListUtils.newArrayList();
  476. long runningCount = 0;
  477. long faultCount = 0;
  478. long maintenanceCount = 0;
  479. long alarmCount = 0;
  480. long offlineCount = 0;
  481. long unknownCount = 0;
  482. long totalRunningSeconds = 0;
  483. for (int i = 0; i < devices.size(); i++) {
  484. MesDevice device = devices.get(i);
  485. MesDeviceState latestQuery = new MesDeviceState();
  486. latestQuery.setDeviceSn(device.getSn());
  487. MesDeviceState latestState = StringUtils.isBlank(device.getSn()) ? null : mesDeviceStateService.findInfo(latestQuery);
  488. String state = latestState != null && StringUtils.isNotBlank(latestState.getState()) ? latestState.getState() : device.getWorkStatus();
  489. String statusCode = getDeviceScreenStatus(device, state);
  490. if ("running".equals(statusCode)) {
  491. runningCount++;
  492. } else if ("fault".equals(statusCode)) {
  493. faultCount++;
  494. } else if ("maintenance".equals(statusCode)) {
  495. maintenanceCount++;
  496. } else if ("alarm".equals(statusCode)) {
  497. alarmCount++;
  498. } else if ("offline".equals(statusCode)) {
  499. offlineCount++;
  500. } else {
  501. unknownCount++;
  502. }
  503. MesDeviceState stateQuery = new MesDeviceState();
  504. stateQuery.setDeviceSn(device.getSn());
  505. stateQuery.setStartDate_gte(todayStart);
  506. stateQuery.setStartDate_lte(now);
  507. List<MesDeviceState> stateList = StringUtils.isBlank(device.getSn()) ? ListUtils.newArrayList() : mesDeviceStateService.findList(stateQuery);
  508. long runningSeconds = getRunningSeconds(stateList, todayStart, now);
  509. if (isRunningState(state) && latestState != null && latestState.getStartDate() != null && latestState.getStartDate().before(todayStart)) {
  510. runningSeconds = elapsedSeconds;
  511. }
  512. if (runningSeconds <= 0 && isRunningState(state)) {
  513. runningSeconds = getRunningSecondsFromWorkTime(device.getWorkTime(), todayStart, now);
  514. }
  515. totalRunningSeconds += runningSeconds;
  516. double openRate = Math.min(100D, runningSeconds * 100D / elapsedSeconds);
  517. Map<String, Object> card = MapUtils.newHashMap();
  518. card.put("name", getText(device.getTreeName(), getText(device.getSn(), "-")));
  519. card.put("sn", getText(device.getSn(), "-"));
  520. card.put("deviceCode", getText(device.getDeviceCode(), "-"));
  521. card.put("lineSn", getText(device.getLineSn(), "-"));
  522. card.put("imagePath", getFirstImagePath(device.getImagePath()));
  523. card.put("statusCode", statusCode);
  524. card.put("statusName", getDeviceScreenStatusName(statusCode));
  525. card.put("stateName", getDeviceStateName(state));
  526. card.put("openRate", Math.round(openRate * 10D) / 10D);
  527. card.put("openMinutes", Math.round(runningSeconds / 60D));
  528. card.put("lastReportTime", latestState != null && latestState.getStartDate() != null ? DateUtils.formatDate(latestState.getStartDate(), "HH:mm:ss") : "-");
  529. card.put("lastReportDate", latestState != null && latestState.getStartDate() != null ? DateUtils.formatDate(latestState.getStartDate(), "yyyy-MM-dd HH:mm:ss") : "-");
  530. card.put("imageIndex", i % 8 + 1);
  531. deviceCards.add(card);
  532. Map<String, Object> rankItem = MapUtils.newHashMap();
  533. rankItem.put("name", card.get("name"));
  534. rankItem.put("sn", card.get("sn"));
  535. rankItem.put("openRate", card.get("openRate"));
  536. rankItem.put("openMinutes", card.get("openMinutes"));
  537. ranking.add(rankItem);
  538. }
  539. ranking.sort((a, b) -> Double.compare(Double.valueOf(String.valueOf(b.get("openRate"))), Double.valueOf(String.valueOf(a.get("openRate")))));
  540. if (ranking.size() > 10) {
  541. ranking = ranking.subList(0, 10);
  542. }
  543. List<Map<String, Object>> statusList = ListUtils.newArrayList();
  544. addStatusItem(statusList, "运行", runningCount, "#35f2c2");
  545. addStatusItem(statusList, "故障", faultCount, "#ff5f6d");
  546. addStatusItem(statusList, "维修", maintenanceCount, "#ffc857");
  547. addStatusItem(statusList, "报警", alarmCount, "#ff8a3d");
  548. addStatusItem(statusList, "离线", offlineCount, "#7d8da8");
  549. addStatusItem(statusList, "未知", unknownCount, "#49a7ff");
  550. double avgOpenRate = devices.isEmpty() ? 0D : totalRunningSeconds * 100D / (elapsedSeconds * devices.size());
  551. data.put("deviceTotal", devices.size());
  552. data.put("runningCount", runningCount);
  553. data.put("faultCount", faultCount);
  554. data.put("offlineCount", offlineCount);
  555. data.put("avgOpenRate", Math.round(avgOpenRate * 10D) / 10D);
  556. data.put("statusList", statusList);
  557. data.put("ranking", ranking);
  558. data.put("devices", deviceCards);
  559. data.put("statDate", DateUtils.formatDate(now, "yyyy-MM-dd"));
  560. data.put("statTime", DateUtils.formatDate(now, "HH:mm:ss"));
  561. data.put("dataNote", "当前系统缺少计划产量、良品数、理想节拍,页面展示的是基于设备状态记录计算的开动率。");
  562. resp.setData(data);
  563. resp.setResult(Global.TRUE);
  564. return resp;
  565. }
  566. private long getRunningSeconds(List<MesDeviceState> stateList, Date todayStart, Date now) {
  567. long runningSeconds = 0L;
  568. for (MesDeviceState state : stateList) {
  569. if (!isRunningState(state.getState()) || state.getStartDate() == null) {
  570. continue;
  571. }
  572. Date start = state.getStartDate().before(todayStart) ? todayStart : state.getStartDate();
  573. Date end = state.getEndDate();
  574. if (end == null && state.getInterval() != null) {
  575. end = new Date(state.getStartDate().getTime() + state.getInterval() * 1000L);
  576. }
  577. if (end == null || end.after(now)) {
  578. end = now;
  579. }
  580. if (end.after(start)) {
  581. runningSeconds += (end.getTime() - start.getTime()) / 1000;
  582. }
  583. }
  584. return runningSeconds;
  585. }
  586. private long getRunningSecondsFromWorkTime(String workTime, Date todayStart, Date now) {
  587. if (StringUtils.isBlank(workTime)) {
  588. return 0L;
  589. }
  590. Date start = parseWorkTime(workTime);
  591. if (start == null) {
  592. return 0L;
  593. }
  594. if (start.before(todayStart)) {
  595. start = todayStart;
  596. }
  597. if (!now.after(start)) {
  598. return 0L;
  599. }
  600. return (now.getTime() - start.getTime()) / 1000;
  601. }
  602. private Date parseWorkTime(String workTime) {
  603. String[] patterns = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"};
  604. for (String pattern : patterns) {
  605. try {
  606. return new SimpleDateFormat(pattern).parse(workTime);
  607. } catch (Exception ignored) {
  608. }
  609. }
  610. return null;
  611. }
  612. private boolean isRunningState(String state) {
  613. return "1".equals(state) || "2".equals(state);
  614. }
  615. private String getDeviceScreenStatus(MesDevice device, String state) {
  616. if (device.getOnline() != null && device.getOnline() == 1) {
  617. return "offline";
  618. }
  619. if ("3".equals(state)) {
  620. return "fault";
  621. }
  622. if ("4".equals(state)) {
  623. return "maintenance";
  624. }
  625. if ("5".equals(state) || "6".equals(state)) {
  626. return "alarm";
  627. }
  628. if (isRunningState(state)) {
  629. return "running";
  630. }
  631. return "unknown";
  632. }
  633. private String getDeviceScreenStatusName(String statusCode) {
  634. if ("running".equals(statusCode)) {
  635. return "运行";
  636. }
  637. if ("fault".equals(statusCode)) {
  638. return "故障";
  639. }
  640. if ("maintenance".equals(statusCode)) {
  641. return "维修";
  642. }
  643. if ("alarm".equals(statusCode)) {
  644. return "报警";
  645. }
  646. if ("offline".equals(statusCode)) {
  647. return "离线";
  648. }
  649. return "未知";
  650. }
  651. private String getDeviceStateName(String state) {
  652. if ("1".equals(state)) {
  653. return "正常";
  654. }
  655. if ("2".equals(state)) {
  656. return "手动";
  657. }
  658. if ("3".equals(state)) {
  659. return "故障";
  660. }
  661. if ("4".equals(state)) {
  662. return "维修";
  663. }
  664. if ("5".equals(state)) {
  665. return "质量报警";
  666. }
  667. if ("6".equals(state)) {
  668. return "物流堵料";
  669. }
  670. return "未知";
  671. }
  672. private void addStatusItem(List<Map<String, Object>> list, String name, long value, String color) {
  673. Map<String, Object> item = MapUtils.newHashMap();
  674. item.put("name", name);
  675. item.put("value", value);
  676. item.put("color", color);
  677. list.add(item);
  678. }
  679. private String getText(String value, String defaultValue) {
  680. return StringUtils.isBlank(value) ? defaultValue : value;
  681. }
  682. private String getFirstImagePath(String imagePath) {
  683. if (StringUtils.isBlank(imagePath)) {
  684. return "";
  685. }
  686. String[] paths = imagePath.split("\\|");
  687. for (String path : paths) {
  688. if (StringUtils.isNotBlank(path)) {
  689. return path;
  690. }
  691. }
  692. return "";
  693. }
  694. }