rain
2024-08-21 2db1aa88e8ab53096a936163d686b90d8e056a99
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
package com.dji.sample.droneairport.service.impl;
 
 
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
//import com.alibaba.fastjson.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.component.redis.RedisOpsUtils;
import com.dji.sample.droneairport.dao.DbUploadMapper;
import com.dji.sample.droneairport.dao.DeviceExpanSionMapper;
import com.dji.sample.droneairport.model.Entity.DbUploadEntity;
import com.dji.sample.droneairport.model.Entity.DeviceExpanSionEntity;
import com.dji.sample.droneairport.model.dto.*;
import com.dji.sample.droneairport.model.param.ReturnTaskParam;
import com.dji.sample.droneairport.service.RegistService;
import com.dji.sample.droneairport.utils.AuthUtil;
import com.dji.sample.droneairport.utils.SM2.Utils;
import com.dji.sample.droneairport.utils.SM4Util;
import com.dji.sample.manage.dao.IDeviceMapper;
import com.dji.sample.manage.model.entity.DeviceEntity;
import com.dji.sample.manage.model.enums.DeviceModeCodeEnum;
import com.dji.sample.manage.model.enums.DockModeCodeEnum;
import com.dji.sample.manage.model.receiver.OsdDockReceiver;
import com.dji.sample.manage.model.receiver.OsdSubDeviceReceiver;
import com.dji.sample.manage.service.IDeviceRedisService;
import com.dji.sample.patches.dao.GetPatchesMapper;
import com.dji.sample.patches.dao.TaskInfoMapper;
import com.dji.sample.patches.model.entity.LotInfo;
import com.dji.sample.patches.model.entity.TaskInfo;
import com.dji.sample.patches.utils.TimerUtil;
import com.dji.sample.wayline.dao.IWaylineFileMapper;
import com.dji.sample.wayline.dao.IWaylineJobMapper;
import com.dji.sample.wayline.model.entity.WaylineFileEntity;
import com.dji.sample.wayline.model.entity.WaylineJobEntity;
import com.dji.sample.wayline.model.enums.WaylineJobStatusEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;
 
import static com.dji.sample.droneairport.utils.AuthUtil.getToken;
import static com.dji.sample.droneairport.utils.TaskAllocator.assignTasks;
import static com.dji.sample.patches.utils.TimerUtil.*;
 
@Service
public class RegistServiceImpl implements RegistService {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private IDeviceRedisService redisService;
    @Autowired
    private DeviceExpanSionMapper expanSionMapper;
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private GetPatchesMapper patchesMapper;
    @Autowired
    private TimerUtil timerUtil;
    @Autowired
    private IDeviceMapper deviceMapper;
    @Autowired
    private IWaylineJobMapper waylineJobMapper;
    @Autowired
    private IWaylineFileMapper fileMapper;
    @Autowired
    private DbUploadMapper dbUploadMapper;
 
    public String registPort(DeviceExpanSionEntity airport) {
        try {
            RegistDto registDto = airportEntityToDto(airport);
            String secret = SM4Util.generateSM4Key();
            String jsonBody = buildRequestBody(registDto);
            String base64 = SM4Util.encrypt(secret, jsonBody);
            String keys=Utils.encrypt(secret,"04225AACF606D800EA3C2C31FCF8FB161B15F7A8D0460DEB91013D4F228C455E76A2ED8D71BC6525B5DC5CC015C155479D8839950344AEE438A3A6305C90F8269F");
            String enSM2=Utils.hexToBase64(keys);
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
            headers.set("Accept-Language", "zh-CN,zh;q=0.9");
            headers.setConnection("keep-alive");
            headers.set("x-lc-token", getToken());
            headers.set("x-auth-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3b3Jrc3BhY2VfaWQiOiJlM2RlYTBmNS0zN2YyLTRkNzktYWU1OC00OTBhZjMyMjgwNjkiLCJzdWIiOiJDbG91ZEFwaVNhbXBsZSIsInVzZXJfdHlwZSI6IjEiLCJuYmYiOjE3MTg1ODUxNTQsImxvZyI6IkxvZ2dlcltjb20uZGppLnNhbXBsZS5jb21tb24ubW9kZWwuQ3VzdG9tQ2xhaW1dIiwiaXNzIjoiREpJIiwiaWQiOiI5Y2MwMGY3Zi0yODMwLTRmM2UtYjdmNC1lN2E1ZjIzYjNjNGYiLCJleHAiOjE4MDQ5ODUxNTQsImlhdCI6MTcxODU4NTE1NCwidXNlcm5hbWUiOiJhZG1pbkRQIn0.eTi9DTYGwcTvnIZasKTFq9OHQgMFS1-m840terb7ss0");
 
            headers.set("x-lc-secret", enSM2);
            // 构建请求实体
//            HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
//            // 发送请求
//            ResponseEntity<String> response = restTemplate.exchange(
//                    "https://xcx.geoway.com.cn:8033/v1/droneAirport/RegistService",
//                    HttpMethod.POST,
//                    requestEntity,
//                    String.class);
//            HttpHeaders responseHeaders = response.getHeaders();
//            String responseSecret = responseHeaders.getFirst("x-lc-secret");
 
            String data=deSM2(enSM2, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
 
            // 使用 Hutool 的 JSONUtil 解析 JSON 字符串
//            JSONObject jsonObject = JSONUtil.parseObj(response.getBody());
 
            // 提取 data 字段的值
//            String dataValue = jsonObject.getStr("data");
 
//            return SM4Util.decrypt(data,dataValue);
            String text=SM4Util.decrypt(data,base64);
            return SM4Util.decrypt(data,base64);
        } catch (Exception e) {
 
            // 异常处理
            return(e.getMessage());
        }
    }
 
//    private String buildRequestBody(RegistDto dto) {
//        try {
//            return objectMapper.writeValueAsString(dto);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("数据有误", e);
//        }
//    }
 
    public <T> String buildRequestBody(T obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("对象转换为JSON字符串时发生错误", e);
        }
    }
 
    @Override
    public String addDrone(String workspaceId) {
        try {
            DeviceExpanSionEntity airport = expanSionMapper.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                    .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                    .eq(DeviceExpanSionEntity::getType, 0));
            DeviceExpanSionEntity drone = expanSionMapper.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                    .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                    .eq(DeviceExpanSionEntity::getType, 1));
            registPort(airport);
            AddDeviceDto dto = deviceEntityToDto(drone);
            String secret = SM4Util.generateSM4Key();
            // 构建请求体
            String jsonBody = buildRequestBody(dto);
            String base64 = SM4Util.encrypt(secret, jsonBody);
            String keys=Utils.encrypt(secret,"04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD");
            String enSM2=Utils.hexToBase64(keys);
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
            headers.set("Accept-Language", "zh-CN,zh;q=0.9");
            headers.setConnection("keep-alive");
            headers.set("x-auth-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3b3Jrc3BhY2VfaWQiOiJlM2RlYTBmNS0zN2YyLTRkNzktYWU1OC00OTBhZjMyMjgwNjkiLCJzdWIiOiJDbG91ZEFwaVNhbXBsZSIsInVzZXJfdHlwZSI6IjEiLCJuYmYiOjE3MTg1ODUxNTQsImxvZyI6IkxvZ2dlcltjb20uZGppLnNhbXBsZS5jb21tb24ubW9kZWwuQ3VzdG9tQ2xhaW1dIiwiaXNzIjoiREpJIiwiaWQiOiI5Y2MwMGY3Zi0yODMwLTRmM2UtYjdmNC1lN2E1ZjIzYjNjNGYiLCJleHAiOjE4MDQ5ODUxNTQsImlhdCI6MTcxODU4NTE1NCwidXNlcm5hbWUiOiJhZG1pbkRQIn0.eTi9DTYGwcTvnIZasKTFq9OHQgMFS1-m840terb7ss0");
            headers.set("x-lc-token", getToken());
            headers.set("x-lc-secret", (enSM2));
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    "https://xcx.geoway.com.cn:8033/v1/droneAirport/addDevice",
                    HttpMethod.POST,
                    requestEntity,
                    String.class);
            HttpHeaders responseHeaders = response.getHeaders();
            String responseSecret = responseHeaders.getFirst("x-lc-secret");
            String data=deSM2(responseSecret, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
            // 使用 Hutool 的 JSONUtil 解析 JSON 字符串
            JSONObject jsonObject = JSONUtil.parseObj(response.getBody());
            // 提取 data 字段的值
            String dataValue = jsonObject.getStr("data");
            return SM4Util.decrypt(data,dataValue);
        } catch (Exception e) {
            // 异常处理
            return (e.getMessage());
        }
    }
 
    @Override
    public Map<String, String> getDroneState(String deviceId) throws Exception {
        String key = SM4Util.generateSM4Key();
        String secret = Utils.encrypt(key, "04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD");
        DroneStateDto data = getAirportFromCache(deviceId);
        String json = JSON.toJSONString(data);
        String SM4Screct = SM4Util.encrypt(key, json);
        Map<String, String> info = new HashMap<>();
        info.put("text", SM4Screct);
        info.put("serect", secret);
        return info;
    }
 
    //    @Override
//    public ResponseResult authorization(String base64, String Secret) throws Exception {
//        String sm4Secrect = deSM2(Secret, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
//        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
//        JSONObject jsonObject = new JSONObject(decryptedJson);
//        String deviceId = jsonObject.getStr("deviceid");
//        boolean online = redisService.checkDeviceOnline(deviceId);
//        if (online) {
//            return ResponseResult.success(200, "无人机机场授权成功!", "", "");
//        }
//        return ResponseResult.error(500, "无人机机场授权失败!");
//    }
    @Override
    public void noAuthorization(String sn) {
        AuthorDto dto = new AuthorDto();
        dto.setSn(sn);
        dto.setStatus(0);
        String jsonBody = buildRequestBody(dto);
        String base64 = SM4Util.encrypt(SM4Util.generateSM4Key(), jsonBody);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
        headers.set("Accept-Language", "zh-CN,zh;q=0.9");
        headers.setConnection("keep-alive");
        headers.set("x-lc-token", "eyJvcmdjb2RlIjoiMDAwMDAwMDAwMDAwMDAwMDAwIiwib3JnbmFtZSI6IuWbveWcn+iwg+afpeS6keaXoOS6uuacuuaOpeWPo+a1i+ivleivgeS5puS4peemgeeUqOS6juato+W8j+eOr+WigyIsImNlcnRjb2RlIjoiVUFWMzJfV0hSNEUzVUFKWlRFM0tFNUlaRkRHTDdDQlUiLCJjZXJ0b3JnY29kZSI6IjEyMTAwMDAwNDAwMDEwMzk4UCIsImNlcnRvcmduYW1lIjoi5Lit5Zu95Zu95Zyf5YuY5rWL6KeE5YiS6ZmiIiwiZXhwaXJhdGlvbiI6IjIwMjQtMTItMzEgMTU6NDY6MzIiLCJwdWJsaWNrZXkiOiIwNDIyNUFBQ0Y2MDZEODAwRUEzQzJDMzFGQ0Y4RkIxNjFCMTVGN0E4RDA0NjBERUI5MTAxM0Q0RjIyOEM0NTVFNzZBMkVEOEQ3MUJDNjUyNUI1REM1Q0MwMTVDMTU1NDc5RDg4Mzk5NTAzNDRBRUU0MzhBM0E2MzA1QzkwRjgyNjlGIiwic2lnbiI6IkI4OTVGQUM1Qzk4NzM5RURGNzFBRkE2QjM4NDEzQUIzNDRCRTBDQjE1RTk3MDQ3Nzk5QTczNUM0MjBEMkZFMzdENkE1NjJFQTlFMUFBRjFBNjhBRDJERjE0QzhEMThBOEY5N0JENzUyOUE2NDRERDA3NkI2NDM1OTg5QkQxREIwIiwiY2VydHR5cGUiOiLml6DkurrmnLrkuL7or4Hor4HkuaYiLCJyZWdpb25jb2RlIjoiMDAwMDAwIn0=");
        headers.set("x-lc-secret", "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                "https://xcx.geoway.com.cn:8033/v1/droneAirport/authorization",
                HttpMethod.POST,
                requestEntity,
                String.class);
    }
 
    @Override
    public void Authorization(String sn) {
        AuthorDto dto = new AuthorDto();
        dto.setSn(sn);
        dto.setStatus(1);
        String jsonBody = buildRequestBody(dto);
        String base64 = SM4Util.encrypt(SM4Util.generateSM4Key(), jsonBody);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
        headers.set("Accept-Language", "zh-CN,zh;q=0.9");
        headers.setConnection("keep-alive");
        headers.set("x-lc-token", "eyJvcmdjb2RlIjoiMDAwMDAwMDAwMDAwMDAwMDAwIiwib3JnbmFtZSI6IuWbveWcn+iwg+afpeS6keaXoOS6uuacuuaOpeWPo+a1i+ivleivgeS5puS4peemgeeUqOS6juato+W8j+eOr+WigyIsImNlcnRjb2RlIjoiVUFWMzJfV0hSNEUzVUFKWlRFM0tFNUlaRkRHTDdDQlUiLCJjZXJ0b3JnY29kZSI6IjEyMTAwMDAwNDAwMDEwMzk4UCIsImNlcnRvcmduYW1lIjoi5Lit5Zu95Zu95Zyf5YuY5rWL6KeE5YiS6ZmiIiwiZXhwaXJhdGlvbiI6IjIwMjQtMTItMzEgMTU6NDY6MzIiLCJwdWJsaWNrZXkiOiIwNDIyNUFBQ0Y2MDZEODAwRUEzQzJDMzFGQ0Y4RkIxNjFCMTVGN0E4RDA0NjBERUI5MTAxM0Q0RjIyOEM0NTVFNzZBMkVEOEQ3MUJDNjUyNUI1REM1Q0MwMTVDMTU1NDc5RDg4Mzk5NTAzNDRBRUU0MzhBM0E2MzA1QzkwRjgyNjlGIiwic2lnbiI6IkI4OTVGQUM1Qzk4NzM5RURGNzFBRkE2QjM4NDEzQUIzNDRCRTBDQjE1RTk3MDQ3Nzk5QTczNUM0MjBEMkZFMzdENkE1NjJFQTlFMUFBRjFBNjhBRDJERjE0QzhEMThBOEY5N0JENzUyOUE2NDRERDA3NkI2NDM1OTg5QkQxREIwIiwiY2VydHR5cGUiOiLml6DkurrmnLrkuL7or4Hor4HkuaYiLCJyZWdpb25jb2RlIjoiMDAwMDAwIn0=");
        headers.set("x-lc-secret", "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                "https://xcx.geoway.com.cn:8033/v1/droneAirport/authorization",
                HttpMethod.POST,
                requestEntity,
                String.class);
    }
 
    @Override
    public Map<String, String> AddTask(String base64, String Secret, String username) throws Exception {
        ReturnTaskParam param = new ReturnTaskParam();
        //获取SM4密钥
        String secret = SM4Util.generateSM4Key();
        //对SM4密钥进行SM2加密
        String retse = Utils.encrypt(secret, "04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD");
        String taskId = UUID.randomUUID().toString();
        String traceid = UUID.randomUUID().toString();
        //通过SM2私钥解密请求头里的secret获取SM4密钥
        String sm4Secrect = deSM2(Secret, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
        //使用从请求头里获取的SM4密钥解析请求参数
        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
        JSONObject jsonObject = new JSONObject(decryptedJson);
        AddTaskDto addTaskDto = jsonToDto(jsonObject);
        TaskInfo taskInfo = new TaskInfo();
        //获取设备Id
        List<String> listx = convertStringToList(addTaskDto.getDeviceid());
        taskInfo.setId(traceid);
        taskInfo.setTaskId(taskId);
        taskInfo.setName(addTaskDto.getBizidname());
        taskInfo.setDeviceIds(addTaskDto.getDeviceid());
        taskInfo.setCreateUser(username);
        param.setTraceId(traceid);
        taskInfoMapper.insert(taskInfo);
 
        // 转换 TaskListDto 为 LotInfo
        List<LotInfo> lotInfos = new ArrayList<>();
        List<TaskListDto> tasklist = addTaskDto.getTasklist();
        for (TaskListDto taskListDto : tasklist) {
            LotInfo lotInfo = convertToLotInfo(taskListDto);
            lotInfo.setTaskId(taskId);
            //
            lotInfo.setType(1);
            lotInfo.setTaskName(addTaskDto.getBizidname());
            lotInfo.setUserName(username);
            lotInfos.add(lotInfo);
            patchesMapper.insert(lotInfo);
        }
 
        // 获取机场信息
        List<Airport> airports = getAirportsBySn(listx);
        List<AirportTasks> airportTasks = assignTasks(airports, lotInfos);
 
        // 处理并插入图斑到数据库
        processAndInsertTasks(airportTasks);
 
        // 根据机场位置生成航线任务
        for (AirportTasks airportTask : airportTasks) {
            Airport airport = airportTask.getAirport();
            List<LotInfo> lotInfosForAirport = airportTask.getTasks();
 
            if (!lotInfosForAirport.isEmpty()) {
                String waylineName = TimerUtil.getTimeName();
                MultipartFile multipartFile = timerUtil.getFile(waylineName, lotInfosForAirport, airport.getLat(), airport.getLon());
                WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, airport.getWorkspaceId(), username);
                Long time = getNextDayEightAMTimestamp(getDistinctTaskIdCount(airport.getWorkspaceId()));
//                Long time = getAdjustedTimestamp(50);
                List<List<Long>> listOfLists = new ArrayList<>();
                List<Long> sublist = new ArrayList<>();
                sublist.add(time);
                listOfLists.add(sublist);
                List<Long> lists1 = new ArrayList<>();
                lists1.add(time);
                String times = TimerUtil.convertTimestampToFormattedString(time);
                param.setJobId(SM4Util.encrypt(secret, taskId));
                timerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, taskId + "~" + airport.getWorkspaceId(), airport.getDockSn());
                timerUtil.updatePatchesStatu(lotInfosForAirport);
            }
        }
        Map<String, String> info = new HashMap<>();
        info.put("taskid", param.getJobId());
        info.put("traceid", param.getTraceId());
        info.put("serect", retse);
        return info;
    }
 
 
    @Override
    public Map<String, String>  updateTask(String base64, String Secret, String username) throws Exception {
        ReturnTaskParam param = new ReturnTaskParam();
        String secret = SM4Util.generateSM4Key();
        String retse = Utils.encrypt(secret, "04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD");
        String traceid = UUID.randomUUID().toString();
        String sm4Secrect = deSM2(Secret, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
        JSONObject jsonObject = new JSONObject(decryptedJson);
        UpdataTaskDto addTaskDto = UpjsonToDto(jsonObject);
        String taskId = addTaskDto.getTaskid();
        String Bizidname = getBizidnameByTask(taskId);
        delPatchesByTaskId(taskId);
        delTaskInfo(taskId);
        delWaylineJob(taskId);
        TaskInfo taskInfo = new TaskInfo();
        List<String> listx = convertStringToList(addTaskDto.getDeviceid());
        taskInfo.setId(traceid);
        taskInfo.setTaskId(taskId);
        taskInfo.setName(Bizidname);
        taskInfo.setDeviceIds(addTaskDto.getDeviceid());
        taskInfo.setCreateUser(username);
        param.setTraceId(traceid);
        taskInfoMapper.insert(taskInfo);
 
        // 转换 TaskListDto 为 LotInfo
        List<LotInfo> lotInfos = new ArrayList<>();
        List<TaskListDto> tasklist = addTaskDto.getTasklist();
        for (TaskListDto taskListDto : tasklist) {
            LotInfo lotInfo = convertToLotInfo(taskListDto);
            lotInfo.setTaskId(taskId);
            lotInfo.setType(1);
            lotInfo.setTaskName(Bizidname);
            lotInfo.setUserName(username);
            lotInfos.add(lotInfo);
            patchesMapper.insert(lotInfo);
        }
 
        // 获取机场信息
        List<Airport> airports = getAirportsBySn(listx);
        List<AirportTasks> airportTasks = assignTasks(airports, lotInfos);
 
        // 处理并插入图斑到数据库
        processAndInsertTasks(airportTasks);
 
        // 根据机场位置生成航线任务
        for (AirportTasks airportTask : airportTasks) {
            Airport airport = airportTask.getAirport();
            List<LotInfo> lotInfosForAirport = airportTask.getTasks();
 
            if (!lotInfosForAirport.isEmpty()) {
                String waylineName = TimerUtil.getTimeName();
                MultipartFile multipartFile = timerUtil.getFile(waylineName, lotInfosForAirport, airport.getLat(), airport.getLon());
                WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, airport.getWorkspaceId(), username);
 
                // 将为规划的图斑状态更新为已规划
                Long time = getNextDayEightAMTimestamp(getDistinctTaskIdCount(airport.getWorkspaceId()));
                List<List<Long>> listOfLists = new ArrayList<>();
                List<Long> sublist = new ArrayList<>();
                sublist.add(time);
                listOfLists.add(sublist);
                List<Long> lists1 = new ArrayList<>();
                lists1.add(time);
                String times = TimerUtil.convertTimestampToFormattedString(time);
                param.setJobId(SM4Util.encrypt(secret, taskId));
                timerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, airport.getWorkspaceId() + "~" + taskId, airport.getDockSn());
                timerUtil.updatePatchesStatu(lotInfosForAirport);
            }
        }
        Map<String, String> info = new HashMap<>();
        info.put("taskid", param.getJobId());
        info.put("traceid", param.getTraceId());
        info.put("serect", retse);
        return info;
    }
 
    @Override
    public Map<String, String>  cancelTask(String taskId) throws InvalidCipherTextException, IOException {
        String secret = SM4Util.generateSM4Key();
        String retse = Utils.encrypt(secret, "04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD");
        LambdaUpdateWrapper<WaylineJobEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.like(WaylineJobEntity::getJobId, taskId)
                .set(WaylineJobEntity::getStatus, 4);
        waylineJobMapper.update(null, updateWrapper);
        Map<String, String> info = new HashMap<>();
        info.put("serect", retse);
        info.put("taskid", SM4Util.encrypt(secret,taskId));
        return info;
    }
 
    public void processAndInsertTasks(List<AirportTasks> airportTasks) {
        for (AirportTasks airportTasksEntry : airportTasks) {
            Airport airport = airportTasksEntry.getAirport();
            List<LotInfo> tasks = airportTasksEntry.getTasks();
 
            // 处理每个任务
            for (LotInfo lotInfo : tasks) {
                lotInfo.setWorkspaceId(airport.getWorkspaceId()); // 设置 workspaceId
                patchesMapper.updateById(lotInfo);
            }
        }
    }
 
    @Override
    public ResponseResult queryTaskStatus(String taskid) {
        List<WaylineJobEntity> jobEntity = waylineJobMapper.selectList(new LambdaQueryWrapper<WaylineJobEntity>().like(WaylineJobEntity::getJobId, taskid));
 
        if (jobEntity == null || jobEntity.isEmpty()) {
            return ResponseResult.success(201, "查询无人机机场任务状态失败!","",UUID.randomUUID().toString());
        }
 
        // 检查是否所有 status 都等于 4
        boolean allStatusAreFour = jobEntity.stream()
                .allMatch(job -> job.getStatus() == 4);
 
        // 检查是否所有 status 都等于 3
        boolean allStatusAreThree = jobEntity.stream()
                .allMatch(job -> job.getStatus() == 3);
 
        if (allStatusAreFour) {
            return ResponseResult.success(204, "查询无人机机场任务状态成功!","",UUID.randomUUID().toString());
        } else if (allStatusAreThree) {
            return ResponseResult.success(200, "查询无人机机场任务状态成功!","",UUID.randomUUID().toString());
        } else {
            return ResponseResult.success(202, "查询无人机机场任务状态成功!","",UUID.randomUUID().toString());
        }
    }
 
    /**
     * 根据任务 ID 查找对应的 DB 文件路径
     *
     * @param taskId 任务 ID
     * @return 匹配的 DB 文件路径列表
     */
    public Map<String,String> findDbFilesByTaskId(String taskId) throws InvalidCipherTextException, IOException {
        DbUploadEntity entity = dbUploadMapper.selectOne(new LambdaQueryWrapper<DbUploadEntity>()
                .eq(DbUploadEntity::getTaskId, taskId));
        String secret = SM4Util.generateSM4Key();
        String traceId = UUID.randomUUID().toString();
        Map<String,String> info =new HashMap<>();
        String retse = Utils.encrypt(secret, "04225AACF606D800EA3C2C31FCF8FB161B15F7A8D0460DEB91013D4F228C455E76A2ED8D71BC6525B5DC5CC015C155479D8839950344AEE438A3A6305C90F8269F");
        if (entity != null) {
            DbUploadDto dto = DbEntityToDto(entity);
            String data=buildRequestBody(dto);
            String text=SM4Util.encrypt(secret,data);
            info.put("data", text);
            info.put("serect", retse);
            info.put("traceId",traceId);
            return info;
        }
        return null;
    }
 
    public static void main(String[] args) {
        getToken();
    }
 
    public void delPatchesByTaskId(String taskId) {
        patchesMapper.delete(new LambdaUpdateWrapper<LotInfo>().eq(LotInfo::getTaskId, taskId));
    }
 
    public DbUploadDto DbEntityToDto(DbUploadEntity entity) {
        DbUploadDto dto = new DbUploadDto();
        dto.setAttachmentCount(entity.getAttachmentCount());
        dto.setCount(entity.getCount());
        dto.setSign(entity.getDataSign());
        dto.setExtension(entity.getExtension());
        dto.setHash(entity.getHash());
        dto.setRegioncode(entity.getRegioncode());
        dto.setTaskId(entity.getTaskId());
        dto.setKey(entity.getDecrypt());
        dto.setTimestamp(entity.getTimestamp());
        dto.setSize(entity.getSize());
        dto.setUrl(entity.getUrl());
        return dto;
    }
 
    public void delTaskInfo(String taskId) {
        taskInfoMapper.delete(new LambdaUpdateWrapper<TaskInfo>().eq(TaskInfo::getTaskId, taskId));
    }
 
//    private String buildRequestBody(AddDeviceDto dto) {
//        try {
//            return objectMapper.writeValueAsString(dto);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("数据有误", e);
//        }
//    }
 
    public String getWorkspaceId(String devicesn) {
        DeviceEntity entity = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>()
                .eq(DeviceEntity::getDeviceSn, devicesn));
        return entity.getWorkspaceId();
    }
 
    public String getBizidnameByTask(String taskId) {
        List<LotInfo> lotInfos = patchesMapper.selectList(new LambdaQueryWrapper<LotInfo>().eq(LotInfo::getTaskId, taskId));
        String taskName = lotInfos.get(0).getTaskName();
        return taskName;
    }
 
    public static String enSM2(String data, String pubKey) throws InvalidCipherTextException, IOException {
        String encrypt = Utils.encrypt(data, pubKey);
        encrypt = Utils.hexToBase64(encrypt);
        return encrypt;
    }
 
    public static String deSM2(String Base64, String priKey) throws Exception {
        String hex = Utils.convertBase64ToHex(Base64);
        return Utils.decrypt(hex, priKey);
    }
 
 
    public static Map<String, String> createKey() throws NoSuchAlgorithmException {
        Map<String, String> keyPair = Utils.createKeyPair();
        Map<String, String> newKey = new HashMap<>();
        newKey.put("publicKey", keyPair.get("pbcky"));
        newKey.put("privateKey", keyPair.get("pveky"));
        return newKey;
    }
 
    public AddDeviceDto deviceEntityToDto(DeviceExpanSionEntity entity) {
        AddDeviceDto.AddDeviceDtoBuilder builder = AddDeviceDto.builder();
        if (entity != null) {
            builder.brand(entity.getBrand())
                    .height(entity.getHeight())
                    .longitude(entity.getLongitude())
                    .latitude(entity.getLatitude())
                    .radius(entity.getRadius())
                    .regioncode(entity.getRegioncode())
                    .deviceid(entity.getDeviceSn())
                    .model(entity.getModel())
                    .build();
        }
        return builder.build();
    }
 
    public RegistDto airportEntityToDto(DeviceExpanSionEntity entity) {
        RegistDto.RegistDtoBuilder builder = RegistDto.builder();
        if (entity != null) {
            builder.serviceUrl(entity.getServiceUrl())
                    .contacts(entity.getContracts())
                    .phone(entity.getPhone())
                    .liveStreamPluginUrl(entity.getLiveStreamPluginUrl())
                    .build();
        }
        return builder.build();
    }
 
    public OsdSubDeviceReceiver getDroneFromCache(String sn) {
        String key = "osd:" + sn;
        return (OsdSubDeviceReceiver) RedisOpsUtils.get(key);
    }
 
    public void delWaylineJob(String taskId) {
        waylineJobMapper.delete(new LambdaQueryWrapper<WaylineJobEntity>().like(WaylineJobEntity::getJobId, taskId));
    }
 
    public DroneStateDto getAirportFromCache(String deviceId) {
        Optional<OsdSubDeviceReceiver> deviceOsdOpt = redisService.getDeviceOsd(deviceId, OsdSubDeviceReceiver.class);
        boolean result = deviceOsdOpt.isPresent();
        if (!result) {
            String sn = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>().eq(DeviceEntity::getChildSn, deviceId)).getDeviceSn();
            Optional<OsdDockReceiver> dockOsdOpt = redisService.getDeviceOsd(sn, OsdDockReceiver.class);
            boolean results = dockOsdOpt.isPresent();
            if (!results) {
                DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
                builder.gimbalYaw(0.0)
                        .gimbalPitch(0.0)
                        .batteryCapacityPercent(0)
                        .height(0)
                        .latitude(0)
                        .longitude(0)
                        .modeCode(1)
                        .elevation(0.0)
                        .gpsState(0)
                        .build();
                return builder.build();
            }
            OsdDockReceiver osdDockReceiver = objectMapper.convertValue(dockOsdOpt.get(), OsdDockReceiver.class);
            int mode;
            int sne = osdDockReceiver.getModeCode().getVal();
            if (sne == 0) {
                mode = 0;
            } else {
                mode = 2;
            }
            DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
            builder.gimbalYaw(0.0)
                    .gimbalPitch(0.0)
                    .batteryCapacityPercent(osdDockReceiver.getDroneChargeState().getCapacityPercent())
                    .height(osdDockReceiver.getHeight())
                    .latitude(osdDockReceiver.getLatitude())
                    .longitude(osdDockReceiver.getLongitude())
                    .modeCode(mode)
                    .elevation(0.0)
                    .gpsState(2)
                    .build();
            return builder.build();
        }
        OsdSubDeviceReceiver receiver = objectMapper.convertValue(deviceOsdOpt.get(), OsdSubDeviceReceiver.class);
        DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
        builder.gimbalYaw(receiver.getPayloads().get(0).getGimbalYaw())
                .gimbalPitch(receiver.getPayloads().get(0).getGimbalPitch())
                .batteryCapacityPercent(receiver.getBattery().getCapacityPercent())
                .height(receiver.getHeight())
                .latitude(receiver.getLatitude())
                .longitude(receiver.getLongitude())
                .modeCode(2)
                .elevation(receiver.getElevation())
                .gpsState(2)
                .build();
        return builder.build();
    }
 
    public static AddTaskDto jsonToDto(JSONObject jsonObject) {
        AddTaskDto dto = new AddTaskDto();
        String deviceid = jsonObject.getStr("deviceid");
        dto.setDeviceid(deviceid);
        dto.setBizidname(jsonObject.getStr("bizidname"));
        JSONArray taskListArray = jsonObject.getJSONArray("tasklist");
        if (taskListArray != null) {
            List<TaskListDto> taskList = new ArrayList<>();
            for (int i = 0; i < taskListArray.size(); i++) {
                JSONObject taskObject = taskListArray.getJSONObject(i);
                if (taskObject != null) {
                    TaskListDto task = new TaskListDto();
                    task.bsm = taskObject.getStr("bsm");
                    task.xzqdm = taskObject.getStr("xzqdm");
                    task.dkbh = taskObject.getStr("dkbh");
                    task.dklx = taskObject.getStr("dklx");
                    task.zdkbh = taskObject.getStr("zdkbh");
                    task.dkmc = taskObject.getStr("dkmc");
                    task.dkmj = taskObject.getDouble("dkmj");
                    task.dkfw = taskObject.getStr("dkfw");
                    task.bz = taskObject.getStr("bz");
                    taskList.add(task);
                }
            }
            dto.tasklist = taskList;
        }
 
        return dto;
    }
 
    public static UpdataTaskDto UpjsonToDto(JSONObject jsonObject) {
        UpdataTaskDto dto = new UpdataTaskDto();
        String deviceid = jsonObject.getStr("deviceid");
        String taskid = jsonObject.getStr("taskid");
        dto.setDeviceid(deviceid);
        dto.setTaskid(taskid);
        JSONArray taskListArray = jsonObject.getJSONArray("tasklist");
        if (taskListArray != null) {
            List<TaskListDto> taskList = new ArrayList<>();
            for (int i = 0; i < taskListArray.size(); i++) {
                JSONObject taskObject = taskListArray.getJSONObject(i);
                if (taskObject != null) {
                    TaskListDto task = new TaskListDto();
                    task.bsm = taskObject.getStr("bsm");
                    task.xzqdm = taskObject.getStr("xzqdm");
                    task.dkbh = taskObject.getStr("dkbh");
                    task.dklx = taskObject.getStr("dklx");
                    task.zdkbh = taskObject.getStr("zdkbh");
                    task.dkmc = taskObject.getStr("dkmc");
                    task.dkmj = taskObject.getDouble("dkmj");
                    task.dkfw = taskObject.getStr("dkfw");
                    task.bz = taskObject.getStr("bz");
                    taskList.add(task);
                }
            }
            dto.tasklist = taskList;
        }
 
        return dto;
    }
 
    public static LotInfo convertToLotInfo(TaskListDto taskListDto) {
        if (taskListDto == null) {
            return null;
        }
        return LotInfo.builder()
                .bsm(taskListDto.bsm)
                .dklx(taskListDto.dklx)
                .xzqdm(taskListDto.xzqdm)
                .dkbh(taskListDto.dkbh)
                .dkmc(taskListDto.dkmc)
                .dkmj(taskListDto.dkmj)
                .dkfw(taskListDto.dkfw)
                .bz(taskListDto.bz)
                .build();
    }
 
 
    public List<Airport> getAirportsBySn(List<String> snList) {
        List<Airport> airports = new ArrayList<>();
        // 查询所有设备
        List<DeviceExpanSionEntity> entities = expanSionMapper.selectList(
                new LambdaQueryWrapper<DeviceExpanSionEntity>().in(DeviceExpanSionEntity::getDeviceSn, snList)
        );
 
        // 使用一个Map来存储SN和经纬度的对应关系
        Map<String, DeviceExpanSionEntity> entityMap = new HashMap<>();
        for (DeviceExpanSionEntity entity : entities) {
            entityMap.put(entity.getDeviceSn(), entity);
        }
 
        // 遍历SN列表,创建Airport对象
        for (String sn : snList) {
            DeviceExpanSionEntity entity = entityMap.get(sn);
            if (entity != null) {
                DeviceEntity deviceEntity = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>().eq(DeviceEntity::getChildSn, sn));
                Airport airport = new Airport(entity.getWorkspaceId(), deviceEntity.getDeviceSn(), entity.getLatitude(), entity.getLongitude());
                airports.add(airport);
            }
        }
 
        return airports;
    }
 
    public static List<String> convertStringToList(String input) {
        // 使用 Hutool 解析字符串
        JSONArray jsonArray = JSONUtil.parseArray(input);
 
        // 将 JSONArray 转换为 List<String>
        return jsonArray.stream()
                .map(Object::toString)
                .collect(Collectors.toList());
    }
 
    public void updateTaskInfo(String traceid, String taskId, String deviceIds, String username) {
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setId(traceid);
        taskInfo.setTaskId(taskId);
        taskInfo.setDeviceIds(deviceIds);
        taskInfo.setCreateUser(username);
 
        LambdaUpdateWrapper<TaskInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TaskInfo::getId, traceid);
        updateWrapper.eq(TaskInfo::getTaskId, taskId);
 
        // 执行更新操作
        taskInfoMapper.update(taskInfo, updateWrapper);
    }
 
    public void updateJob(String jobid, String waylineId) {
        LambdaUpdateWrapper<WaylineJobEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WaylineJobEntity::getJobId, jobid)
                .set(WaylineJobEntity::getFileId, waylineId);
 
        // 调用 update 方法进行更新操作
        waylineJobMapper.update(null, updateWrapper);
    }
 
    /**
     * 统计给定工作空间下,创建时间为当天的不同 taskId 的数量。
     *
     * @param workspaceId 工作空间 ID
     * @return 不同 taskId 的数量
     */
    public Integer getDistinctTaskIdCount(String workspaceId) {
        // 获取当前日期的开始和结束时间
        LocalDate today = LocalDate.now();
        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = today.plusDays(1).atStartOfDay();
 
        // 转换为毫秒时间戳
        long startTimestamp = startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long endTimestamp = endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
 
        // 使用 LambdaQueryWrapper 进行查询
        LambdaQueryWrapper<LotInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(LotInfo::getWorkspaceId, workspaceId)
                .ge(LotInfo::getCreateTime, startTimestamp)
                .lt(LotInfo::getCreateTime, endTimestamp);
 
        // 获取符合条件的所有 taskId
        Set<String> taskIdSet = patchesMapper.selectList(queryWrapper).stream()
                .map(LotInfo::getTaskId)
                .collect(Collectors.toSet());
 
        // 返回不同 taskId 的数量
        return taskIdSet.size();
    }
 
 
}