CZT
2023-10-11 564295458c720206db9b5194b90481b711f4b010
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
package com.ld.igds.grain.manager;
 
import com.baomidou.mybatisplus.plugins.Page;
import com.ld.igds.common.CoreCommonService;
import com.ld.igds.common.CoreDeviceIotService;
import com.ld.igds.common.CoreSerService;
import com.ld.igds.constant.*;
import com.ld.igds.data.*;
import com.ld.igds.grain.*;
import com.ld.igds.grain.GrainPrintBuilder;
import com.ld.igds.grain.dto.*;
import com.ld.igds.grain.service.CoreGrainService;
import com.ld.igds.io.RemoteGrainService;
import com.ld.igds.io.RemoteManager;
import com.ld.igds.io.constant.OrderRespEnum;
import com.ld.igds.io.request.CheckGrainRequest;
import com.ld.igds.io.response.GrainResponse;
import com.ld.igds.m.service.HQualityManageService;
import com.ld.igds.models.*;
import com.ld.igds.order.ExeOrderService;
import com.ld.igds.order.data.ExeRequest;
import com.ld.igds.util.ContextUtil;
import com.ld.igds.util.DateUtil;
import com.ld.igds.util.DecimalUtil;
import com.ld.igds.util.FilesUtil;
import com.ld.igds.view.service.BuildingService;
 
import lombok.extern.slf4j.Slf4j;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.text.Collator;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * 逻辑管理,用于实现控制层的逻辑
 */
@Slf4j
@Component
public class GrainManager {
 
    @Autowired
    private CoreGrainService coreGrainService;
    @Autowired
    private CoreSerService coreSerService;
    @Autowired
    private CoreCommonService coreCommonService;
    @Autowired
    private ExeOrderService exeOrderService;
    @Autowired
    private RemoteManager remoteManager;
    @Autowired
    private HQualityManageService hQualityManageService;
    @Autowired
    private CoreDeviceIotService deviceIotService;
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private GrainExportBuilder grainExportBuilder;
    @Resource
    private FilesUtil filesUtil;
 
    /**
     * 根据参数获取粮情数据信息
     *
     * @param param
     * @return
     */
    public PageResponse<GrainData> queryGrainData(GrainParam param) {
        if (StringUtils.isEmpty(param.getDepotId())) {
            return new PageResponse<>(RespCodeEnum.CODE_1007.getCode(),
                    "没有获取到仓库参数。");
        }
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        if (null != param.getCheckDate()) {
            param.setStart(DateUtil.getCurZero(param.getCheckDate()));
            param.setEnd(DateUtil.getNextZero(param.getCheckDate()));
            param.setCheckDate(null);
        }
 
        List<GrainData> list = coreGrainService.listGrainData(param);
 
        if (null == list) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "当前条件下没有获取到粮情数据信息");
        }
 
        GrainData grainData = list.get(0);
 
        // 添加仓库信息
        Depot depotData = coreCommonService.getCacheDepot(param.getCompanyId(), param.getDepotId());
 
        if (null == depotData) {
            log.error("未获取到仓库信息");
        }
        MQuality mQuality = hQualityManageService.getCacheLastData(depotData.getId());
 
        grainData.setDepotData(depotData);
        grainData.setMquality(mQuality);
        return new PageResponse<>(RespCodeEnum.CODE_0000, grainData);
    }
 
    public PageResponse<List<GrainData>> queryListGrainData(GrainParam param) {
        if (StringUtils.isEmpty(param.getDepotId())) {
            return new PageResponse<>(RespCodeEnum.CODE_1007.getCode(),
                    "没有获取到仓库参数。");
        }
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        if (null != param.getCheckDate()) {
            param.setStart(DateUtil.getCurZero(param.getCheckDate()));
            param.setEnd(DateUtil.getNextZero(param.getCheckDate()));
            param.setCheckDate(null);
        }
 
        if (null != param.getCheckMonth()) {
            param.setStart(DateUtil.getMonthFirst(param.getCheckMonth()));
            param.setEnd(DateUtil.getNextMonthFirst(param.getCheckMonth()));
            param.setCheckMonth(null);
        }
 
        List<GrainData> list = coreGrainService.listGrainData(param);
 
        if (null == list || list.isEmpty()) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "根据条件获取数据为空");
        }
 
        // 添加仓库信息
        Depot depotData = coreCommonService.getCacheDepot(param.getCompanyId(), param.getDepotId());
 
        if (null == depotData) {
            log.error("未获取到仓库信息");
        }
        MQuality mQuality = hQualityManageService.getCacheLastData(depotData.getId());
        // 添加仓库数据信息
        for (GrainData data : list) {
            data.setDepotData(depotData);
            data.setMquality(mQuality);
        }
        return new PageResponse<>(RespCodeEnum.CODE_0000, list);
    }
 
    public PageResponse<Map<String, GrainData>> queryCheckDateMap(
            GrainParam param) {
 
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        param.setTagUpdate(true);
        Map<String, GrainData> result = coreGrainService.queryCheckDateMap(param);
 
        if (null == result) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "当前条件下没有获取到粮情信息!!");
        }
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, result);
    }
 
    public PageResponse<ChartLine> queryLineData(GrainParam param) {
        if (StringUtils.isEmpty(param.getDepotId())) {
            return new PageResponse<>(RespCodeEnum.CODE_1007.getCode(),
                    "请选择需要查询的仓库");
        }
        // 默认2个月以前的数据
        if (null == param.getEnd()) {
            param.setEnd(new Date());
        }
        if (null == param.getStart()) {
            param.setStart(DateUtils.addMonths(param.getEnd(), -2));
        }
 
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
        param.setStart(DateUtil.getCurZero(param.getStart()));
        param.setEnd(DateUtil.getNextZero(param.getEnd()));
        param.setTagUpdate(false);
        List<GrainData> list = coreGrainService.listChartData(param);
 
        if (null == list || list.isEmpty()) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "根据条件获取数据为空");
        }
 
        // 将粮情数据转换为折线图
        String[] arrtLegendData = new String[]{"仓温", "外温", "平均粮温", "最高粮温",
                "最低粮温"};
        List<String> xaxisData = new ArrayList<String>();
        List<ChartSeries> listSeries = new ArrayList<ChartSeries>();
        for (String name : arrtLegendData) {
            listSeries.add(new ChartSeries(name));
        }
 
        for (GrainData grain : list) {
            // X轴数据添加
            xaxisData.add(DateFormatUtils.format(grain.getReceiveDate(),
                    "yyyy-MM-dd HH:mm"));
            // 仓温
            if (null == grain.getTempIn()
                    || Constant.ERROR_TEMP == grain.getTempIn()) {
                listSeries.get(0).getData().add("0.0");
            } else {
                listSeries.get(0).getData()
                        .add(String.valueOf(grain.getTempIn()));
            }
            // 外温
            if (null == grain.getTempOut()
                    || Constant.ERROR_TEMP == grain.getTempOut()) {
                listSeries.get(1).getData().add("0.0");
            } else {
                listSeries.get(1).getData()
                        .add(String.valueOf(grain.getTempOut()));
            }
 
            // 平均粮温
            if (Constant.ERROR_TEMP == grain.getTempAve()) {
                listSeries.get(2).getData().add("0.0");
            } else {
                listSeries.get(2).getData()
                        .add(String.valueOf(grain.getTempAve()));
            }
 
            // 最低粮温
            if (Constant.ERROR_TEMP == grain.getTempMax()) {
                listSeries.get(3).getData().add("0.0");
            } else {
                listSeries.get(3).getData()
                        .add(String.valueOf(grain.getTempMax()));
            }
 
            // 最高粮温
            if (Constant.ERROR_TEMP == grain.getTempMin()) {
                listSeries.get(4).getData().add("0.0");
            } else {
                listSeries.get(4).getData()
                        .add(String.valueOf(grain.getTempMin()));
            }
        }
 
        ChartLine result = new ChartLine(Arrays.asList(arrtLegendData),
                xaxisData, listSeries);
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, result);
    }
 
 
    public GrainResponse checkSingle(GrainParam param) {
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        if (StringUtils.isEmpty(param.getDeptId())) {
            param.setDeptId(ContextUtil.subDeptId(null));
        }
 
        if (StringUtils.isEmpty(param.getDepotId())) {
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                    "没有获取到仓库参数,请重新选择仓库并执行!");
        }
 
        try {
            // 缓存获仓库配置信息
            DepotConf depotConf = coreCommonService.getCacheDepotConf(param.getCompanyId(), param.getDepotId());
 
            if (null == depotConf) {
                return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                        "当前仓库没有配置粮情参数,执行被拒绝!");
            }
 
            // 获取分机信息
            DeviceSer deviceSer = coreSerService.getCacheSer(param.getCompanyId(), depotConf.getGrainSer());
 
            if (null == deviceSer) {
                return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                        "当前仓库没有配置粮情分机,执行被拒绝!");
            }
 
            CheckGrainRequest request = new CheckGrainRequest();
            request.setDepotId(param.getDepotId());
            request.setCompanyId(param.getCompanyId());
            request.setCableStart(depotConf.getCableStart());
            request.setCableEnd(depotConf.getCableEnd());
            request.setCableRule(depotConf.getCableRule());
            request.setIp(deviceSer.getIp());
            request.setPort(deviceSer.getPort());
            request.setBizType(BizType.GRAIN.getCode());
            request.setSerId(deviceSer.getId());
            request.setSerName(deviceSer.getName());
            request.setDepotName(depotConf.getDepotName());
            // 新增温湿度信息
            request.setThSerId(depotConf.getThSer());
            request.setThConf(depotConf.getThConf());
            request.setDeptId(ContextUtil.subDeptId(null));
 
            // 避免重复发送命令和添加操作记录
            ExeRequest exeRequest = new ExeRequest(request);
 
            RemoteGrainService remoteGrainService = remoteManager.getRemoteGrainService(deviceSer.getProtocol());
 
            if (null == remoteGrainService) {
                String msg = "系统没有" + deviceSer.getProtocol() + "的协议实现,执行被拒绝!";
                return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(), msg);
            }
 
            GrainResponse result = remoteGrainService.checkGrain(request);
 
            if (OrderRespEnum.ORDER_SUCCESS.getCode().equals(result.getCode())) {
                //添加日志和执行缓存
                exeOrderService.addLogAndCache(exeRequest);
                return result;
            } else {
                String msg = depotConf.getDepotName() + "请求失败:" + result.getMsg();
                return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(), msg);
            }
        } catch (Exception e) {
            log.error("批量粮情异常:{}", e);
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                    "系统异常:" + e.getMessage());
        }
    }
 
 
    /**
     * 多参采集入口,系统根据是否启动一分机多仓功能自动调用调整
     *
     * @param param
     * @return
     */
    public GrainResponse checkBatch(GrainParam param) {
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        DicSysConf sysConf = coreCommonService.getCacheSysConf(param.getCompanyId());
 
        if (StringUtils.isEmpty(sysConf.getGrainMoreTag())) {
            return checkBatch1(param, sysConf);
        }
 
        if (Constant.YN_N.equals(sysConf.getGrainMoreTag())) {
            return checkBatch1(param, sysConf);
        }
 
        if (Constant.YN_Y.equals(sysConf.getGrainMoreTag())) {
            return checkBatch2(param, sysConf);
        }
 
        return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                "没有获取到系统参数配置信息,无法执行判断!");
    }
 
    /**
     * 批量采集-单仓单分机
     *
     * @param param
     * @return
     */
    public GrainResponse checkBatch1(GrainParam param, DicSysConf sysConf) {
        if (null == param.getDepotIds()) {
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                    "没有获取到仓库参数,请重新选择仓库并执行!");
        }
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        if (StringUtils.isEmpty(param.getDeptId())) {
            param.setDeptId(ContextUtil.subDeptId(null));
        }
 
        if (null == sysConf) {
            sysConf = coreCommonService.getCacheSysConf(param.getCompanyId());
        }
 
        String[] attr = param.getDepotIds().split(",");
        GrainResponse tempResp;
        // 缓存获仓库配置信息
        DepotConf depotConf;
        // 获取分机信息
        DeviceSer deviceSer;
        CheckGrainRequest request;
        ExeRequest exeRequest;
 
        for (String depotId : attr) {
            param.setDepotId(depotId);
 
            depotConf = coreCommonService.getCacheDepotConf(param.getCompanyId(), param.getDepotId());
 
            if (null == depotConf) {
                String msg = depotId + " 粮情请求失败,原因: 没有获取到粮情参数配置。";
                exeOrderService.addErrorCache(param.getCompanyId(), BizType.GRAIN.getCode(), param.getDeptId(), depotId, msg);
                continue;
            }
 
            deviceSer = coreSerService.getCacheSer(param.getCompanyId(), depotConf.getGrainSer());
 
            if (null == deviceSer) {
                String msg = depotConf.getDepotName() + "粮情请求失败,原因: 没有获取到分机信息。";
                exeOrderService.addErrorCache(param.getCompanyId(), BizType.GRAIN.getCode(), param.getDeptId(), depotConf.getDepotName(), msg);
                continue;
            }
 
            request = new CheckGrainRequest();
            request.setDepotId(param.getDepotId());
            request.setCompanyId(param.getCompanyId());
            request.setCableStart(depotConf.getCableStart());
            request.setCableEnd(depotConf.getCableEnd());
            request.setCableRule(depotConf.getCableRule());
            request.setIp(deviceSer.getIp());
            request.setPort(deviceSer.getPort());
            request.setBizType(BizType.GRAIN.getCode());
            request.setSerId(deviceSer.getId());
            request.setSerName(deviceSer.getName());
            request.setThSerId(depotConf.getThSer());
            request.setThConf(depotConf.getThConf());
            request.setDepotName(depotConf.getDepotName());
            request.setDeptId(param.getDeptId());
 
            exeRequest = new ExeRequest(request);
 
            RemoteGrainService remoteGrainService = remoteManager.getRemoteGrainService(deviceSer.getProtocol());
 
            if (null == remoteGrainService) {
                String msg = depotConf.getDepotName() + "粮情请求失败,原因: 分机对应协议未实现。";
 
                exeOrderService.addErrorCache(request, msg);
                continue;
            }
 
            try {
                tempResp = remoteGrainService.checkGrain(request);
                if (OrderRespEnum.ORDER_SUCCESS.getCode().equals(tempResp.getCode())) {
                    exeOrderService.addLogAndCache(exeRequest);
                } else {
                    String msg = depotConf.getDepotName() + " 粮情命令发送异常:" + tempResp.getMsg();
                    exeOrderService.addErrorCache(request, msg);
                }
                if (deviceSer.getNetworkType().equals(Constant.NETWORK_02)) {// 如果是无线模式,间隔执行
                    Thread.sleep(sysConf.getIntervalTime() * 1000);
                } else {
                    Thread.sleep(500);
                }
            } catch (Exception e) {
                String msg = depotConf.getDepotName() + "粮情请求失败,原因:" + e.getMessage();
                exeOrderService.addErrorCache(request, msg);
                log.error(msg);
            }
        }
 
        return new GrainResponse(OrderRespEnum.ORDER_SUCCESS.getCode(),
                "批量执行粮情检测命令发送成功,请等待终端响应……");
    }
 
    /**
     * 当前方法 为了支持 一个分机多个仓
     *
     * @param param
     * @return
     */
    public GrainResponse checkBatch2(GrainParam param, DicSysConf dicSysConf) {
        if (null == param.getDepotIds()) {
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                    "没有获取到仓库参数,请重新选择仓库并执行!");
        }
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        if (StringUtils.isEmpty(param.getDeptId())) {
            param.setDeptId(ContextUtil.subDeptId(null));
        }
 
 
        log.info("-------------批量 一分机多仓 规则执行粮情检测------------");
 
        String[] attr = param.getDepotIds().split(",");
        // 缓存获仓库配置信息
        DepotConf depotConf;
        // 获取分机信息
        DeviceSer deviceSer;
        CheckGrainRequest request;
        ExeRequest exeRequest;
 
        //用于存放当前任务顺序
        Map<String, Integer> mapTemp = new HashMap<>();
 
        for (String depotId : attr) {
            param.setDepotId(depotId);
 
            depotConf = coreCommonService.getCacheDepotConf(param.getCompanyId(), param.getDepotId());
 
            if (null == depotConf) {
                String msg = param.getDepotId() + "粮情请求失败,原因: 没有获取到粮情参数配置。";
                exeOrderService.addErrorCache(param.getCompanyId(), BizType.GRAIN.getCode(), param.getDeptId(), depotId, msg);
                continue;
            }
 
            deviceSer = coreSerService.getCacheSer(param.getCompanyId(), depotConf.getGrainSer());
 
            if (null == deviceSer) {
                String msg = depotConf.getDepotName() + "粮情请求失败,原因: 没有获取到分机信息。";
                exeOrderService.addErrorCache(param.getCompanyId(), BizType.GRAIN.getCode(), param.getDeptId(), depotConf.getDepotName(), msg);
                continue;
            }
 
            request = new CheckGrainRequest();
            request.setDepotId(param.getDepotId());
            request.setCompanyId(param.getCompanyId());
            request.setCableStart(depotConf.getCableStart());
            request.setCableEnd(depotConf.getCableEnd());
            request.setCableRule(depotConf.getCableRule());
            request.setIp(deviceSer.getIp());
            request.setPort(deviceSer.getPort());
            request.setBizType(BizType.GRAIN.getCode());
            request.setSerId(deviceSer.getId());
            request.setSerName(deviceSer.getName());
            request.setThSerId(depotConf.getThSer());
            request.setThConf(depotConf.getThConf());
            request.setDepotName(depotConf.getDepotName());
            request.setDeptId(param.getDeptId());
 
            exeRequest = new ExeRequest(request);
 
            RemoteGrainService remoteGrainService = remoteManager.getRemoteGrainService(deviceSer.getProtocol());
 
            if (null == remoteGrainService) {
                String msg = depotConf.getDepotName() + "粮情请求失败,原因: 分机对应协议未实现。";
                exeOrderService.addErrorCache(request, msg);
                continue;
            }
 
            //添加执行记录
            mapTemp.put(deviceSer.getId(), null == mapTemp.get(deviceSer.getId()) ? 0 : (mapTemp.get(deviceSer.getId()) + 1));
 
            //判断执行顺序
            if (mapTemp.get(deviceSer.getId()) > 0) {
                log.info("----分机={}多仓执行顺序-{},创建子任务稍后执行新的命令", exeRequest.getSerName(), mapTemp.get(deviceSer.getId()));
                FutureTask<String> futureTask = new FutureTask<>(new GrainTask(remoteGrainService, exeOrderService, request, depotConf, dicSysConf, mapTemp.get(deviceSer.getId())));
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.submit(futureTask);
                executorService.shutdown();
            } else {
                this.doBatchCheckStp2(request, exeRequest, depotConf, dicSysConf, deviceSer, remoteGrainService);
            }
        }
 
        return new GrainResponse(OrderRespEnum.ORDER_SUCCESS.getCode(),
                "批量执行粮情检测命令发送成功,请等待终端响应……");
    }
 
    private void doBatchCheckStp2(CheckGrainRequest request, ExeRequest exeRequest, DepotConf depotConf, DicSysConf sysConf, DeviceSer deviceSer, RemoteGrainService remoteGrainService) {
        try {
            GrainResponse tempResp = remoteGrainService.checkGrain(request);
            if (OrderRespEnum.ORDER_SUCCESS.getCode().equals(tempResp.getCode())) {
                exeOrderService.addLogAndCache(exeRequest);
            } else {
                String msg = depotConf.getDepotName() + " 粮情命令发送异常:" + tempResp.getMsg();
                exeOrderService.addErrorCache(request, msg);
            }
 
            if (deviceSer.getNetworkType().equals(Constant.NETWORK_02)) {// 如果是无线模式,间隔执行
                Thread.sleep(sysConf.getIntervalTime() * 1000);
            } else {
                Thread.sleep(500);
            }
        } catch (Exception e) {
            String msg = depotConf.getDepotName() + "粮情请求失败,原因:" + e.getMessage();
            log.error(msg);
            exeOrderService.addErrorCache(request, msg);
        }
    }
 
    /**
     * 返回粮情map数据
     *
     * @param param
     * @return
     */
    public Map<String, GrainData> getCacheGrainDateMap(GrainParam param) {
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
        return coreGrainService.getCacheGrainDateMap(param.getCompanyId(), param.getDeptId());
    }
 
    public PageResponse<List<GrainData>> pageListGrainData(GrainParam param) {
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
        if (StringUtils.isEmpty(param.getDepotId())) {
            return new PageResponse<>(RespCodeEnum.CODE_1007.getCode(),
                    "没有获取到仓库参数,执行失败!");
        }
 
        param.setTagUpdate(false);
        Page<GrainData> page = coreGrainService.pageListGrainData(param);
 
        if (null == page.getRecords()) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "当前条件下没有获取到粮情信息!!");
        }
 
        return new PageResponse<List<GrainData>>(RespCodeEnum.CODE_0000,
                page.getRecords());
    }
 
    public PageResponse<GrainData> dataCompare(GrainCompareParam param) {
        GrainData dataA = param.getDataA();
        GrainData dataB = param.getDataB();// 被对比数据
 
        // 开始数据对比
        if (!dataA.getCable().equals(dataB.getCable())) {
            return new PageResponse<>(
                    RespCodeEnum.CODE_1111.getCode(), "两个批次的采集点个数不一致,无法执行对比");
        }
 
        dataA.setTempAve(DecimalUtil.sub(dataA.getTempAve(), dataB.getTempAve()));
        dataA.setTempMax(DecimalUtil.sub(dataA.getTempMax(), dataB.getTempMax()));
        dataA.setTempMin(DecimalUtil.sub(dataA.getTempMin(), dataB.getTempMin()));
 
        //判断仓内温是否为null,若为null则默认设置为-100
        if (null == dataA.getTempIn()) {
            dataA.setTempIn(Constant.ERROR_TEMP);
        }
        if (null == dataB.getTempIn()) {
            dataB.setTempIn(Constant.ERROR_TEMP);
        }
        dataA.setTempIn(DecimalUtil.sub(dataA.getTempIn(), dataB.getTempIn()));
 
        //判断仓内湿是否为null,若为null则默认设置为-100
        if (null == dataA.getHumidityIn()) {
            dataA.setHumidityIn(Constant.ERROR_TEMP);
        }
        if (null == dataB.getHumidityIn()) {
            dataB.setHumidityIn(Constant.ERROR_TEMP);
        }
        dataA.setHumidityIn(DecimalUtil.sub(dataA.getHumidityIn(),
                dataB.getHumidityIn()));
        dataA.setHumidityOut(DecimalUtil.sub(dataA.getHumidityOut(),
                dataB.getHumidityOut()));
 
        // 计算采集点
        String[] attrA = dataA.getPoints().split(",");
        String[] attrB = dataB.getPoints().split(",");
 
        List<Double> points = new ArrayList<Double>();
 
        for (int i = 0; i < attrA.length; i++) {
            // 对比需要考虑故障点的计算,任何一方出现故障点,则对比值为0
            if (Double.valueOf(attrA[i]) == Constant.ERROR_TEMP
                    || Double.valueOf(attrB[i]) == Constant.ERROR_TEMP) {
                points.add(0.0);
            } else {
                points.add(DecimalUtil.sub(attrA[i], attrB[i]));
            }
        }
        // 重新配置
        dataA.setPoints(StringUtils.join(points, ","));
 
        DepotConf depotConf = coreCommonService.getCacheDepotConf(dataA.getCompanyId(), dataA.getDepotId());
 
        // 更新粮情数据
        GrainDataBuilder.updateGrainData(dataA, null, depotConf);
 
        // 添加仓库信息
        Depot depotData = coreCommonService.getCacheDepot(dataA.getCompanyId(),
                dataA.getDepotId());
        dataA.setDepotData(depotData);
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, dataA);
    }
 
    public PageResponse<ChartLine> chartPointLine(GrainPointParam param) {
        if (null == param.getCompanyId()) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        param.setX(param.getNumX() - 1 - param.getX());
        param.setZ(param.getNumZ() - 1 - param.getZ());
 
        // 根据坐标系获取采集的顺序,数据库中的顺序从1开始
        int num = param.getX() * param.getNumZ() * param.getNumY()
                + param.getNumZ() * param.getY() + param.getZ() + 1;
        param.setNum(num);
 
        // 根据参数获取到集合,默认获取180天的数据
        param.setStart(DateUtil.getNewByDay(null, -180));
 
        ChartLine chartLine = coreGrainService.chartPointLine(param);
 
        if (null == chartLine) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "没有获取到采集信息");
        }
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, chartLine);
    }
 
    /**
     * 根据参数获取当前打印需要的模板
     *
     * @param param
     * @return
     */
    public PageResponse<PrintModeData> buildPrintModel(GrainParam param) {
        if (null == param.getCompanyId()) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
        if (StringUtils.isEmpty(param.getDepotType())) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "没有获取到当前仓库的仓库类型");
        }
        if (StringUtils.isEmpty(param.getCableRule()) && StringUtils.isEmpty(param.getCableCir())) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "没有获取当前仓库的布线规则");
        }
        PrintModeData result = GrainPrintBuilder.buildPrintModel(param);
 
        if (null == result) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    "系统没有获取当前仓库的表单模板");
        }
 
        if (StringUtils.isNotEmpty(result.getMsg())) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(),
                    result.getMsg());
        }
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, result);
    }
 
    public PageResponse<Map<String, PrintModeData>> buildPrintModelAll(GrainParam param) {
 
        Map<String, PrintModeData> result = new HashMap<>();
 
        List<DepotConf> depotConfList = coreCommonService.getCacheDepotConf(param.getCompanyId());
        PrintModeData modeData;
        String key;
        for (DepotConf conf : depotConfList) {
            if (null == conf.getDepotType()) {
                conf.setDepotType(DepotType.TYPE_01.getCode());
            }
            // param.setCompanyId(conf.getCompanyId());
            param.setCableRule(conf.getCableRule());
            param.setDepotId(conf.getDepotId());
            param.setCableCir(conf.getCableCir());
            param.setDepotType(conf.getDepotType());
 
            if (StringUtils.isNotEmpty(param.getCableCir())) {
                key = param.getDepotType() + "_" + param.getCableRule() + "_" + param.getCableCir();
            } else {
                key = param.getDepotType() + "_" + param.getCableRule();
            }
            if (null == result.get(key)) {
                modeData = GrainPrintBuilder.buildPrintModel(param);
                result.put(key, modeData);
            }
        }
        return new PageResponse<>(RespCodeEnum.CODE_0000, result);
    }
 
    /**
     * 获取仓库的液位高度信息
     *
     * @param companyId
     * @param deptId
     * @return
     */
    public List<GrainData> getLiquidHeight(String companyId, String deptId) {
 
        if (StringUtils.isEmpty(companyId)) {
            companyId = ContextUtil.getCompanyId();
        }
        if (StringUtils.isEmpty(deptId)) {
            deptId = ContextUtil.subDeptId(null);
        }
 
        List<Depot> depotList = coreCommonService.getCacheDepotList(companyId, deptId);
        if (null == depotList || depotList.isEmpty()) {
            return null;
        }
 
        Map<String, Building> map;
        List<Building> buildingList = buildingService.getCacheBuilding(companyId, deptId);
        if (null != buildingList && buildingList.size() > 0) {
            map = buildingList.stream().collect(Collectors.toMap(Building::getId, Function.identity()));
        } else {
            map = new HashMap<>();
        }
 
        List<GrainData> list = new ArrayList<>();
        GrainData grainData;
        Building building;
        String height;
        //直径
        Double diameter;
        Double bulkWeight;
        Double storage = 0.0;
        Double volume = 0.0;
        Double deVolume;
        for (Depot depot : depotList) {
 
            //获取仓房信息,设置建筑高度
            height = null;
            //获取仓房直径
            diameter = 0.0;
            deVolume = 0.0;
            //容重
            bulkWeight = depot.getBulkWeight();
            grainData = coreGrainService.listLiquidHeight(companyId, depot.getId());
            if (null == grainData) {
                grainData = new GrainData();
            }
 
            if (null != depot.getBuildingId()) {
                building = map.get(depot.getBuildingId());
                if (null != building) {
                    if (null != building.getHeight()) {
                        height = building.getHeight() + "";
                    }
                    if (null != building.getLength()) {
                        diameter = building.getLength();
                    }
                    if (null != building.getDeVolume()) {
                        deVolume = building.getDeVolume();
                    }
                }
            }
 
            grainData.setDepotData(depot);
            grainData.setDepotHeight(height);
            if (null != bulkWeight && StringUtils.isNotEmpty(grainData.getOilHeight())) {
                Double oilHeight = Double.valueOf(grainData.getOilHeight());
                //计算体积
                volume = 3.14 * Math.pow(diameter / 2, 2) * oilHeight  - deVolume;
                storage = volume * bulkWeight;
            }
 
            grainData.setStorage(storage);
            list.add(grainData);
        }
 
        return list;
    }
 
    /**
     * 获取成品仓的Iot设备列表信
     *
     * @param param
     * @return
     */
    public PageResponse<List<DeviceIot>> listDeviceIot(GrainParam param) {
 
        if (null == param || StringUtils.isEmpty(param.getDepotId())) {
            return new PageResponse<>(RespCodeEnum.CODE_1007,
                    null);
        }
 
        List<DeviceIot> list = deviceIotService.getCacheDeviceIotByDepotId(param.getCompanyId(), param.getDepotId());
 
        if (null == list || list.isEmpty()) {
            return new PageResponse<>(RespCodeEnum.CODE_2000.getCode(), "没有获取到设备请联系管理员");
        }
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, list);
    }
 
    public PageResponse<GrainData> queryIotGrainData(GrainParam param) {
        if (StringUtils.isEmpty(param.getDepotId())) {
            return new PageResponse<>(RespCodeEnum.CODE_1007.getCode(),
                    "没有获取到仓库参数。");
        }
        if (StringUtils.isEmpty(param.getCompanyId())) {
            param.setCompanyId(ContextUtil.getCompanyId());
        }
 
        GrainData grainData = new GrainData();
 
        Depot depot = coreCommonService.getCacheDepot(param.getCompanyId(), param.getDepotId());
        if (null == depot) {
            log.error("未获取到仓库信息");
        }
        // 添加仓库数据信息
        grainData.setDepotData(depot);
 
        //从缓存中获取仓库所有iot温湿度设备的数据信息
        List<GrainIotData> list = coreGrainService.queryIotGrainData(param.getCompanyId(), param.getDepotId());
 
        if (null != list && list.size() > 0) {
            log.error("未获取到温湿度信息");
        }
 
        grainData.setGrainIotData(list);
 
        return new PageResponse<>(RespCodeEnum.CODE_0000, grainData);
    }
 
    public GrainResponse exportBatch(GrainParam param) {
 
        //根据条件获取需要打印的粮情信息
 
        if (null != param.getCheckDate()) {
            param.setStart(DateUtil.getCurZero(param.getCheckDate()));
            param.setEnd(DateUtil.getNextZero(param.getCheckDate()));
            param.setCheckDate(null);
        }
 
        //获取已经粮情格式化完成的粮情数据
        param.setTagUpdate(true);
        List<GrainData> list = coreGrainService.listGrainData(param);
 
        if (null == list || list.isEmpty()) {
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                    "当前条件下没有查询到粮情检测记录,取消导出");
        }
 
        //按照仓库编码从新排序
        Collator sortChina = Collator.getInstance(java.util.Locale.CHINA);
        Collections.sort(list, (a, b) -> sortChina.compare(a.getDepotId(), b.getDepotId()));
 
        //获取缓存的仓库列表,用于获取仓库名称
        List<Depot> listDepot = coreCommonService.getCacheDepotList(param.getCompanyId(), param.getDeptId());
 
        //去除重复的粮情数据
        LinkedHashMap<String, GrainData> dataMap = new LinkedHashMap<>();
        for (GrainData data : list) {
            if (null != dataMap.get(data.getDepotId())) continue;
 
            dataMap.put(data.getDepotId(), data);
        }
 
 
        String fileName = grainExportBuilder.exportByMapData(dataMap, listDepot);
 
        if (fileName.startsWith("ERROR")) {
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                    "执行导出出现错误:" + fileName);
        }
 
        return new GrainResponse(OrderRespEnum.ORDER_SUCCESS.getCode(),
                fileName);
    }
}