wlzboy
8 天以前 09faa36132c8cbada5327649875534ef01c1a3b1
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
package com.ruoyi.system.service.impl;
 
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.net.HttpURLConnection;
import java.net.URL;
 
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.TaskCodeGenerator;
import com.ruoyi.common.config.ImageUrlConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.GpsDistanceUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.SysTask;
import com.ruoyi.system.domain.SysTaskVehicle;
import com.ruoyi.system.domain.SysTaskAttachment;
import com.ruoyi.system.domain.SysTaskLog;
import com.ruoyi.system.domain.SysTaskEmergency;
import com.ruoyi.system.domain.SysTaskWelfare;
import com.ruoyi.system.domain.SysTaskAssignee;
import com.ruoyi.system.domain.enums.TaskStatus;
import com.ruoyi.system.domain.VehicleInfo;
import com.ruoyi.system.event.TaskCreatedEvent;
import com.ruoyi.system.event.TaskAssignedEvent;
import com.ruoyi.system.event.TaskStatusChangedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
 
/**
 * 任务管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-15
 */
@Service
public class SysTaskServiceImpl implements ISysTaskService {
    
    private static final Logger log = LoggerFactory.getLogger(SysTaskServiceImpl.class);
    
    @Autowired
    private SysTaskMapper sysTaskMapper;
    
    @Autowired
    private SysTaskAttachmentMapper sysTaskAttachmentMapper;
    
    @Autowired
    private SysTaskLogMapper sysTaskLogMapper;
    
    @Autowired
    private SysTaskEmergencyMapper sysTaskEmergencyMapper;
    
    @Autowired
    private SysTaskAssigneeMapper sysTaskAssigneeMapper;
    
    @Autowired(required = false)
    private ILegacySystemSyncService legacySystemSyncService;
    
    @Autowired
    private ISysEmergencyTaskService sysEmergencyTaskService;
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    @Autowired
    private ImageUrlConfig imageUrlConfig;
    
    @Autowired
    private ISysTaskAttachmentService sysTaskAttachmentService;
 
    @Autowired
    private SysUserMapper sysUserMapper;
 
    @Autowired(required = false)
    private IMapService mapService;
 
    @Autowired
    private ISysConfigService configService;
 
    @Autowired
    private ISysTaskAssigneeService sysTaskAssigneeService;
 
    @Autowired
    private ISysWelfareTaskService sysWelfareTaskService;
 
    @Autowired
    private ISysTaskVehicleService sysTaskVehicleService;
 
    /**
     * 查询任务管理
     * 
     * @param taskId 任务管理主键
     * @return 任务管理
     */
    @Override
    public SysTask selectSysTaskByTaskId(Long taskId) {
        SysTask task = sysTaskMapper.selectSysTaskByTaskId(taskId);
        if (task != null) {
            // 加载急救转运扩展信息
            if ("EMERGENCY_TRANSFER".equals(task.getTaskType())) {
                SysTaskEmergency emergencyInfo = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(taskId);
                task.setEmergencyInfo(emergencyInfo);
            }
            // 加载福祉车扩展信息
            else if ("WELFARE".equals(task.getTaskType())) {
                SysTaskWelfare welfareInfo = sysWelfareTaskService.getWelfareInfoByTaskId(taskId);
                task.setWelfareInfo(welfareInfo);
            }
        }
        return task;
    }
 
    /**
     * 查询任务管理列表
     * 
     * @param queryVO 任务查询对象
     * @return 任务管理
     */
    @Override
    public List<SysTask> selectSysTaskList(TaskQueryVO queryVO) {
        return sysTaskMapper.selectSysTaskList(queryVO);
    }
 
    /**
     * 新增任务管理
     * 
     * @param createVO 任务创建对象
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSysTask(TaskCreateVO createVO) {
        String username = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();
        if(userId==null || userId==0){
            log.error("insertSysTask 用户ID为空 userName:{}",username);
            return 0;
        }
        SysTask task = new SysTask();
        task.setTaskCode(generateTaskCode());
        task.setTaskType(createVO.getTaskType());
        task.setTaskStatus(TaskStatus.PENDING.getCode());
        task.setTaskDescription(createVO.getTaskDescription());
        task.setPlannedStartTime(createVO.getPlannedStartTime());
        task.setPlannedEndTime(createVO.getPlannedEndTime());
        task.setAssigneeId(createVO.getAssigneeId());
        task.setCreatorId(userId);
        // 优先使用前端传入的部门ID,如果没有则使用当前用户的部门ID
        task.setDeptId(createVO.getDeptId() != null ? createVO.getDeptId() : SecurityUtils.getDeptId());
        task.setCreateBy(username);
        task.setCreateTime(DateUtils.getNowDate());
        task.setUpdateBy(username);
        task.setUpdateTime(DateUtils.getNowDate());
        task.setRemark(createVO.getRemark());
        task.setDelFlag("0");
        
        // 设置地址和坐标信息
        setAddressAndCoordinatesFromVO(task, createVO);
        // 设置任务类型特定信息
        setTaskTypeSpecificInfo(task, createVO);
        // 自动填充缺失的GPS坐标
        autoFillMissingGpsCoordinates(task);
        
        int result = sysTaskMapper.insertSysTask(task);
        
        // 保存车辆关联信息
        if (result > 0 && createVO.getVehicleIds() != null && !createVO.getVehicleIds().isEmpty()) {
            sysTaskVehicleService.saveTaskVehicles(task.getTaskId(), createVO.getVehicleIds(), username);
        }
        
        // 保存执行人员信息(包含角色类型)
        if (result > 0 && createVO.getAssignees() != null && !createVO.getAssignees().isEmpty()) {
            sysTaskAssigneeService.saveTaskAssignees(task.getTaskId(), createVO.getAssignees(),username);
        }
        
        // 保存急救转运扩展信息
        if (result > 0 && "EMERGENCY_TRANSFER".equals(createVO.getTaskType())) {
            sysEmergencyTaskService.saveEmergencyInfo(task.getTaskId(), username, createVO, null, null, null);
        }
        
        // 保存福祉车扩展信息
        if (result > 0 && "WELFARE".equals(createVO.getTaskType())) {
            sysWelfareTaskService.saveWelfareInfo(task.getTaskId(), SecurityUtils.getUsername(), createVO);
        }
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(task.getTaskId(), "CREATE", "创建任务", null, 
                         "任务类型:" + createVO.getTaskType(), SecurityUtils.getUserId(), SecurityUtils.getUsername());
        }
        
        // 发布任务创建事件
        if (result > 0) {
            eventPublisher.publishEvent(new TaskCreatedEvent(
                this,
                task.getTaskId(),
                task.getTaskCode(),
                task.getTaskType(),
                task.getCreatorId(),
                SecurityUtils.getUsername()
            ));
        }
        
        // 发布任务分配事件
        if (result > 0 && createVO.getAssignees() != null && !createVO.getAssignees().isEmpty()) {
            this.sendTaskAssigneeEvent(createVO,task,SecurityUtils.getUserId(),SecurityUtils.getUsername());
        }
        
        // 异步同步急救转运任务到旧系统
        if (result > 0 && "EMERGENCY_TRANSFER".equals(createVO.getTaskType()) && legacySystemSyncService != null) {
            final Long finalTaskId = task.getTaskId();
            new Thread(() -> {
                try {
                    Thread.sleep(2000); // 等待2秒,确保事务已提交
                    legacySystemSyncService.syncEmergencyTaskToLegacy(finalTaskId);
                } catch (Exception e) {
                    // 同步失败不影响主流程,仅记录日志
                }
            }).start();
        }
        
        return result;
    }
 
    /**
     * 新增任务管理(允许从外部传入用户信息、部门信息和时间信息)
     * 
     * @param createVO 任务创建对象
     * @param userId 用户ID
     * @param deptId 部门ID
     * @param createTime 创建时间
     * @param updateTime 更新时间
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTask(TaskCreateVO createVO,String serviceOrderId,String dispatchOrderId, String serviceOrdNo, Long userId,String userName, Long deptId, Date createTime, Date updateTime) {
        SysTask task = new SysTask();
        if(createVO.getTaskCode()!=null){
            task.setTaskCode(createVO.getTaskCode());
        }else{
            task.setTaskCode(generateTaskCode());
        }
        task.setTaskType(createVO.getTaskType());
        task.setTaskStatus(TaskStatus.PENDING.getCode());
        task.setTaskDescription(createVO.getTaskDescription());
        task.setPlannedStartTime(createVO.getPlannedStartTime());
        task.setPlannedEndTime(createVO.getPlannedEndTime());
        task.setActualStartTime(createVO.getActualStartTime());
        task.setActualEndTime(createVO.getActualEndTime());
        task.setAssigneeId(createVO.getAssigneeId());
        // 使用外部传入的用户ID和部门ID
        task.setCreatorId(userId);
        task.setDeptId(deptId);
        task.setCreateBy(userName);
        // 使用外部传入的创建时间和更新时间
        task.setCreateTime(createTime);
        task.setUpdateTime(updateTime);
        task.setUpdateBy(userName);
        task.setRemark(createVO.getRemark());
        task.setDelFlag("0");
 
 
        
        // 设置地址和坐标信息
        setAddressAndCoordinatesFromVO(task, createVO);
        // 设置任务类型特定信息(注:insertTask使用plannedStartTime而非serviceTime)
        if (createVO.getTransferTime() != null) {
            task.setPlannedStartTime(createVO.getTransferTime());
        }
        if (createVO.getTransferDistance() != null) {
            task.setEstimatedDistance(createVO.getTransferDistance());
        }
        if (createVO.getPlannedStartTime() != null) {
            task.setPlannedStartTime(createVO.getPlannedStartTime());
        }
        if (createVO.getStartAddress() != null) {
            task.setDepartureAddress(createVO.getStartAddress());
        }
        if (createVO.getEndAddress() != null) {
            task.setDestinationAddress(createVO.getEndAddress());
        }
        if (createVO.getDistance() != null) {
            task.setEstimatedDistance(createVO.getDistance());
        }
        // 自动填充缺失的GPS坐标
        autoFillMissingGpsCoordinates(task);
        
        int result = sysTaskMapper.insertSysTask(task);
        
        // 保存车辆关联信息
        if (result > 0 && createVO.getVehicleIds() != null && !createVO.getVehicleIds().isEmpty()) {
            sysTaskVehicleService.saveTaskVehicles(task.getTaskId(), createVO.getVehicleIds(), userName, 
                updateTime, createTime, updateTime);
        }
        
        // 保存执行人员信息(包含角色类型)
        if (result > 0 && createVO.getAssignees() != null && !createVO.getAssignees().isEmpty()) {
            sysTaskAssigneeService.saveTaskAssignees(task.getTaskId(), createVO.getAssignees(),userName);
        }
        
        // 保存急救转运扩展信息
        if (result > 0 && "EMERGENCY_TRANSFER".equals(createVO.getTaskType())) {
            sysEmergencyTaskService.saveEmergencyInfo(task.getTaskId(), userName, createVO, serviceOrderId, dispatchOrderId, serviceOrdNo);
        }
        
        // 保存福祉车扩展信息
        if (result > 0 && "WELFARE".equals(createVO.getTaskType())) {
            sysWelfareTaskService.saveWelfareInfo(task.getTaskId(), userName, createVO);
        }
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(task.getTaskId(), "CREATE", "创建任务", null, 
                         "任务类型:" + createVO.getTaskType(), userId, userName);
        }
        
        // 发布任务创建事件
        if (result > 0) {
            eventPublisher.publishEvent(new TaskCreatedEvent(
                this,
                task.getTaskId(),
                task.getTaskCode(),
                task.getTaskType(),
                userId,
                userName
            ));
        }
        
        // 发布任务分配事件
        if (result > 0 && createVO.getAssignees() != null && !createVO.getAssignees().isEmpty()) {
            this.sendTaskAssigneeEvent(createVO,task,userId,userName);
        }
        
 
        
        return result;
    }
 
    private void sendTaskAssigneeEvent(TaskCreateVO createVO,SysTask task,Long userId,String userName){
        List<Long> assigneeIds = createVO.getAssignees().stream()
                .map(assignee -> assignee.getUserId())
                .collect(Collectors.toList());
        List<String> assigneeNames = createVO.getAssignees().stream()
                .map(assignee -> assignee.getUserName())
                .collect(Collectors.toList());
 
        eventPublisher.publishEvent(new TaskAssignedEvent(
                this,
                task.getTaskId(),
                task.getTaskCode(),
                assigneeIds,
                assigneeNames,
                userId,
                userName
        ));
    }
 
    /**
     * 修改任务管理
     * 
     * @param updateVO 任务更新对象
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSysTask(TaskUpdateVO updateVO, Boolean updateFromLegacy) {
        SysTask oldTask = sysTaskMapper.selectSysTaskByTaskId(updateVO.getTaskId());
        if (oldTask == null) {
            throw new RuntimeException("任务不存在");
        }
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        
        SysTask task = new SysTask();
        task.setTaskId(updateVO.getTaskId());
        task.setTaskDescription(updateVO.getTaskDescription());
        task.setPlannedStartTime(updateVO.getPlannedStartTime());
        task.setPlannedEndTime(updateVO.getPlannedEndTime());
        task.setAssigneeId(updateVO.getAssigneeId());
        task.setUpdateBy(userName);
        task.setUpdateTime(updateVO.getUpdateTime() != null ? updateVO.getUpdateTime() : DateUtils.getNowDate());
        task.setRemark(updateVO.getRemark());
        
        // 设置通用地址和坐标信息
        task.setDepartureAddress(updateVO.getDepartureAddress());
        task.setDestinationAddress(updateVO.getDestinationAddress());
        task.setDepartureLongitude(updateVO.getDepartureLongitude());
        task.setDepartureLatitude(updateVO.getDepartureLatitude());
        task.setDestinationLongitude(updateVO.getDestinationLongitude());
        task.setDestinationLatitude(updateVO.getDestinationLatitude());
        
        // 设置预计距离
        if (updateVO.getEstimatedDistance() != null) {
            task.setEstimatedDistance(updateVO.getEstimatedDistance());
        } else if (updateVO.getTransferDistance() != null) {
            // 兼容急救转运字段
            task.setEstimatedDistance(updateVO.getTransferDistance());
        } else if (updateVO.getDistance() != null) {
            // 兼容福祉车字段
            task.setEstimatedDistance(updateVO.getDistance());
        }
        
        // 如果更新了部门ID
        if (updateVO.getDeptId() != null) {
            task.setDeptId(updateVO.getDeptId());
        }
        
        // 如果更新了任务编号
        if (updateVO.getTaskCode() != null) {
            task.setTaskCode(updateVO.getTaskCode());
        }
        
        // 自动获取出发地GPS坐标(如果更新了地址但缺失坐标)
        if (updateVO.getDepartureAddress() != null && 
            (updateVO.getDepartureLongitude() == null || updateVO.getDepartureLatitude() == null) && 
            mapService != null) {
            if (!updateVO.getDepartureAddress().equals(oldTask.getDepartureAddress())) {
                try {
                    Map<String, Double> coords = mapService.geocoding(
                        updateVO.getDepartureAddress(),
                        extractCityFromAddress(updateVO.getDepartureAddress())
                    );
                    if (coords != null) {
                        task.setDepartureLongitude(BigDecimal.valueOf(coords.get("lng")));
                        task.setDepartureLatitude(BigDecimal.valueOf(coords.get("lat")));
//                        log.info("出发地GPS坐标自动获取成功: {}, {}", coords.get("lng"), coords.get("lat"));
                    }
                } catch (Exception e) {
                    log.error("自动获取出发地GPS坐标失败", e);
                }
            }
        }
        
        // 自动获取目的地GPS坐标(如果更新了地址但缺失坐标)
        if (updateVO.getDestinationAddress() != null && 
            (updateVO.getDestinationLongitude() == null || updateVO.getDestinationLatitude() == null) && 
            mapService != null) {
            if (!updateVO.getDestinationAddress().equals(oldTask.getDestinationAddress())) {
                try {
                    Map<String, Double> coords = mapService.geocoding(
                        updateVO.getDestinationAddress(),
                        extractCityFromAddress(updateVO.getDestinationAddress())
                    );
                    if (coords != null) {
                        task.setDestinationLongitude(BigDecimal.valueOf(coords.get("lng")));
                        task.setDestinationLatitude(BigDecimal.valueOf(coords.get("lat")));
//                        log.info("目的地GPS坐标自动获取成功: {}, {}", coords.get("lng"), coords.get("lat"));
                    }
                } catch (Exception e) {
                    log.error("自动获取目的地GPS坐标失败", e);
                }
            }
        }
        // 用于跟踪是否需要重新同步(车辆、人员、地址、成交价变更)
        boolean needResync = false;
        int result = sysTaskMapper.updateSysTask(task);
        
 
        
        // 更新车辆关联
        if (result > 0 && updateVO.getVehicleIds() != null && !updateVO.getVehicleIds().isEmpty()) {
            boolean vehiclesChanged = sysTaskVehicleService.updateTaskVehicles(
                updateVO.getTaskId(), updateVO.getVehicleIds(), userName);
            if (vehiclesChanged) {
                // 标记需要重新同步(车辆变更)
                needResync = true;
            }
        }
        
        // 更新执行人员(检测人员变更)
        if (result > 0 && updateVO.getAssignees() != null) {
            boolean assigneesChanged = sysTaskAssigneeService.updateTaskAssignees(
                updateVO.getTaskId(), updateVO.getAssignees(), userName);
            if (assigneesChanged) {
                // 标记需要重新同步(人员变更)
                needResync = true;
            }
        }
        
        // 更新急救转运扩展信息(检测地址和成交价变更)
        if (result > 0 && "EMERGENCY_TRANSFER".equals(oldTask.getTaskType())) {
            SysTaskEmergency oldEmergency = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(updateVO.getTaskId());
            sysEmergencyTaskService.updateEmergencyInfoFromUpdateVO(oldEmergency, updateVO, userName);
            sysEmergencyTaskService.markNeedResyncIfNecessary(updateVO.getTaskId(), oldTask, updateVO, updateFromLegacy);
        }
        
        // 更新福祉车扩展信息
        if (result > 0 && "WELFARE".equals(oldTask.getTaskType())) {
            if (updateVO.getPassenger() != null || updateVO.getStartAddress() != null || updateVO.getEndAddress() != null) {
                sysWelfareTaskService.updateWelfareInfo(updateVO.getTaskId(), updateVO, userName);
            }
        }
        
        // 如果是急救转运任务且有变更,标记需要重新同步
        if (result > 0 && "EMERGENCY_TRANSFER".equals(oldTask.getTaskType()) && needResync && !updateFromLegacy) {
            sysEmergencyTaskService.markNeedResyncIfNecessary(updateVO.getTaskId(), oldTask, updateVO, updateFromLegacy);
        }
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(updateVO.getTaskId(), "UPDATE", "更新任务",
                buildTaskDescription(oldTask), buildTaskDescription(task),
                userId, userName);
        }
 
        if(result > 0 && oldTask.getTaskStatus().equals(TaskStatus.PENDING.getCode()) && updateVO.getAssignees() != null && !updateVO.getAssignees().isEmpty()){
 
            this.sendTaskAssigneeEvent(updateVO,oldTask,userId,userName);
        }
 
        return result;
    }
 
    /**
     * 更新任务(用于旧系统同步)
     * 
     * @param updateVO 任务更新对象
     * @param serviceOrderId 旧系统服务单ID
     * @param dispatchOrderId 旧系统调度单ID
     * @param serviceOrdNo 旧系统服务单编号
     * @param userId 用户ID
     * @param userName 用户名
     * @param deptId 部门ID
     * @param createTime 创建时间
     * @param updateTime 更新时间
     * @return 结果
     */
    @Override
    public int updateTask(TaskUpdateVO updateVO, String serviceOrderId, String dispatchOrderId, String serviceOrdNo,
                         Long userId, String userName, Long deptId, Date createTime, Date updateTime) {
//        log.info("开始更新任务 ServiceOrdID: {} , dispatchOrdId:{}", serviceOrderId,dispatchOrderId);
        // 通过旧系统服务单ID查找任务
        SysTaskEmergency taskEmergency = sysTaskEmergencyMapper.selectByLegacyServiceOrdId(Long.parseLong(serviceOrderId));
        Long taskId = taskEmergency.getTaskId();
        updateVO.setTaskId(taskId);
        SysTask task = new SysTask();
        task.setTaskId(taskId);
        if(updateVO.getTaskStatus()!=null){
            task.setTaskStatus(updateVO.getTaskStatus());
        }
        task.setTaskDescription(updateVO.getTaskDescription());
        task.setPlannedStartTime(updateVO.getPlannedStartTime());
        task.setPlannedEndTime(updateVO.getPlannedEndTime());
        if(updateVO.getActualStartTime() != null) {
            task.setActualStartTime(updateVO.getActualStartTime());
        }
        if(updateVO.getActualEndTime() != null) {
            task.setActualEndTime(updateVO.getActualEndTime());
        }
        task.setAssigneeId(updateVO.getAssigneeId());
        task.setUpdateBy(userName);
        task.setUpdateTime(DateUtils.getNowDate());
        task.setRemark(updateVO.getRemark());
 
        
        // 设置地址和坐标信息
        task.setDepartureAddress(updateVO.getDepartureAddress());
        task.setDestinationAddress(updateVO.getDestinationAddress());
        task.setDepartureLongitude(updateVO.getDepartureLongitude());
        task.setDepartureLatitude(updateVO.getDepartureLatitude());
        task.setDestinationLongitude(updateVO.getDestinationLongitude());
        task.setDestinationLatitude(updateVO.getDestinationLatitude());
        
        // 如果更新了部门ID
        if (updateVO.getDeptId() != null) {
            task.setDeptId(updateVO.getDeptId());
        }
        
        // 如果更新了任务编号
        if (updateVO.getTaskCode() != null) {
            task.setTaskCode(updateVO.getTaskCode());
        }
        
        // 获取旧任务信息,用于判断地址是否变更
        SysTask oldTask = sysTaskMapper.selectSysTaskByTaskId(taskId);
        
        // 自动获取出发地GPS坐标(如果地址变更且缺失坐标)
        if (oldTask != null && updateVO.getDepartureAddress() != null
            && !updateVO.getDepartureAddress().equals(oldTask.getDepartureAddress())
            && (updateVO.getDepartureLongitude() == null || updateVO.getDepartureLatitude() == null)
            && mapService != null) {
            try {
                Map<String, Double> coords = mapService.geocoding(
                    updateVO.getDepartureAddress(),
                    extractCityFromAddress(updateVO.getDepartureAddress())
                );
                if (coords != null) {
                    task.setDepartureLongitude(BigDecimal.valueOf(coords.get("lng")));
                    task.setDepartureLatitude(BigDecimal.valueOf(coords.get("lat")));
//                    log.info("出发地GPS坐标自动获取成功: {}, {}", coords.get("lng"), coords.get("lat"));
                }
            } catch (Exception e) {
                log.error("自动获取出发地GPS坐标失败", e);
            }
        }
        
        // 自动获取目的地GPS坐标(如果地址变更且缺失坐标)
        if (oldTask != null && updateVO.getDestinationAddress() != null
            && !updateVO.getDestinationAddress().equals(oldTask.getDestinationAddress())
            && (updateVO.getDestinationLongitude() == null || updateVO.getDestinationLatitude() == null)
            && mapService != null) {
            try {
                Map<String, Double> coords = mapService.geocoding(
                    updateVO.getDestinationAddress(),
                    extractCityFromAddress(updateVO.getDestinationAddress())
                );
                if (coords != null) {
                    task.setDestinationLongitude(BigDecimal.valueOf(coords.get("lng")));
                    task.setDestinationLatitude(BigDecimal.valueOf(coords.get("lat")));
//                    log.info("目的地GPS坐标自动获取成功: {}, {}", coords.get("lng"), coords.get("lat"));
                }
            } catch (Exception e) {
                log.error("自动获取目的地GPS坐标失败", e);
            }
        }
        
        int result = sysTaskMapper.updateSysTask(task);
//        log.info("更新转运任务,ServiceOrdID:{},dispatchOrderId:{},result:{}",serviceOrderId,dispatchOrderId,result);
//        log.info("更新任务车辆 ServiceOrdID: {} , dispatchOrdId:{},VehicleIds:{}", serviceOrderId,dispatchOrderId,updateVO.getVehicleIds());
        // 更新车辆关联
        if (result > 0 && updateVO.getVehicleIds() != null && !updateVO.getVehicleIds().isEmpty()) {
//            log.info("更新车辆关联 ServiceOrdID:{},dispatchOrderId:{}",serviceOrderId,dispatchOrderId);
            sysTaskVehicleService.updateTaskVehicles(taskId, updateVO.getVehicleIds(), userName);
        }
 
        Boolean hasAssignee = updateVO.getAssigneeId() != null && !updateVO.getAssignees().isEmpty() ;
//        log.info("更新转运任务,ServiceOrdID:{},dispatchOrderId:{},result:{}, hasAssignee:{}",serviceOrderId,dispatchOrderId,result,hasAssignee);
 
        // 更新执行人员(检测人员变更)
        if (result > 0 && hasAssignee) {
//            log.info("更新执行人员 ServiceOrdID:{},dispatchOrderId:{}",serviceOrderId,dispatchOrderId);
            sysTaskAssigneeService.updateTaskAssignees(taskId, updateVO.getAssignees(), userName);
        }
        
        // 更新急救转运扩展信息
        if (result > 0) {
            // 更新旧系统ID
            if (serviceOrderId != null) {
                taskEmergency.setLegacyServiceOrdId(Long.parseLong(serviceOrderId));
            }
            if (dispatchOrderId != null) {
                taskEmergency.setLegacyDispatchOrdId(Long.parseLong(dispatchOrderId));
                taskEmergency.setLegacyDispatchOrdId(Long.parseLong(dispatchOrderId));
                taskEmergency.setDispatchSyncStatus(2);
                taskEmergency.setDispatchSyncTime(new Date());
                taskEmergency.setDispatchSyncErrorMsg("旧系统同步过来");
            }
            if (serviceOrdNo != null) {
                taskEmergency.setLegacyServiceOrdNo(serviceOrdNo);
            }
            taskEmergency.setUpdateTime(DateUtils.getNowDate());
 
            Boolean hasEmergencyInfo = updateVO.getHospitalOut() != null || updateVO.getHospitalIn() != null || updateVO.getPatient() != null;
//            log.info("更新转运任务信息 serviceOrdID:{},dispatchOrderId:{} hasEmergencyInfo:{}",serviceOrderId,
//                    dispatchOrderId,hasEmergencyInfo);
 
            // 使用TaskCreateVO的字段来更新急救转运信息
            if (hasEmergencyInfo) {
                sysEmergencyTaskService.updateEmergencyInfoFromCreateVO(taskEmergency, updateVO, userName);
            }
        }
 
        if(updateVO.getTaskStatus()!=null && updateVO.getTaskStatus().equals(TaskStatus.PENDING.getCode()) && updateVO.getAssignees()!=null && !updateVO.getAssignees().isEmpty()){
            this.sendTaskAssigneeEvent(updateVO,task,userId,userName);
        }
        
        return result;
    }
 
    /**
     * 批量删除任务管理
     * 
     * @param taskIds 需要删除的任务管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysTaskByTaskIds(Long[] taskIds) {
        int result = 0;
        for (Long taskId : taskIds) {
            // 记录删除日志
            recordTaskLog(taskId, "DELETE", "删除任务", null, null, 
                         SecurityUtils.getUserId(), SecurityUtils.getUsername());
            result += sysTaskMapper.deleteSysTaskByTaskId(taskId);
        }
        return result;
    }
 
    /**
     * 分配任务
     * 
     * @param taskId 任务ID
     * @param assigneeId 执行人ID
     * @param remark 备注
     * @return 结果
     */
    @Override
    @Transactional
    public int assignTask(Long taskId, Long assigneeId, String remark) {
        SysTask task = sysTaskMapper.selectSysTaskByTaskId(taskId);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        SysTask updateTask = new SysTask();
        updateTask.setTaskId(taskId);
        updateTask.setAssigneeId(assigneeId);
        updateTask.setUpdateBy(SecurityUtils.getUsername());
        updateTask.setUpdateTime(DateUtils.getNowDate());
        
        int result = sysTaskMapper.assignTask(updateTask);
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(taskId, "ASSIGN", "分配任务", null, 
                         "分配给用户ID:" + assigneeId + ",备注:" + remark, 
                         SecurityUtils.getUserId(), SecurityUtils.getUsername());
        }
        
        // 发布任务分配事件
        if (result > 0) {
            List<Long> assigneeIds = new ArrayList<>();
            assigneeIds.add(assigneeId);
            
            eventPublisher.publishEvent(new TaskAssignedEvent(
                this,
                task.getTaskId(),
                task.getTaskCode(),
                assigneeIds,
                null, // 姓名列表在监听器中查询
                SecurityUtils.getUserId(),
                SecurityUtils.getUsername()
            ));
        }
        
        return result;
    }
 
    /**
     * 变更任务状态
     * 
     * @param taskId 任务ID
     * @param newStatus 新状态
     * @param remark 备注
     * @return 结果
     */
    @Override
    public int changeTaskStatus(Long taskId, TaskStatus newStatus, String remark) {
        return changeTaskStatusWithLocation(taskId, newStatus, remark, null);
    }
 
    /**
     * 变更任务状态(含GPS位置信息)
     * 
     * @param taskId 任务ID
     * @param newStatus 新状态
     * @param remark 备注
     * @param locationLog GPS位置信息日志对象
     * @return 结果
     */
    @Override
    public int changeTaskStatusWithLocation(Long taskId, TaskStatus newStatus, String remark, SysTaskLog locationLog) {
        SysTask oldTask = sysTaskMapper.selectSysTaskByTaskId(taskId);
        if (oldTask == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 验证状态流转是否合法
        TaskStatus oldTaskStatus = TaskStatus.getByCode(oldTask.getTaskStatus());
        if (!oldTask.canChangeStatus(newStatus)) {
            throw new RuntimeException("状态流转不合法:从 " + oldTaskStatus.getInfo() + " 到 " + newStatus.getInfo());
        }
        
        SysTask task = new SysTask();
        task.setTaskId(taskId);
        task.setTaskStatus(newStatus.getCode());
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        
        // 根据状态设置相应的时间
        if (newStatus == TaskStatus.DEPARTING && oldTask.getActualStartTime() == null) {
            // 出发中:设置实际开始时间
            task.setActualStartTime(DateUtils.getNowDate());
        } else if (newStatus == TaskStatus.IN_PROGRESS && oldTask.getActualStartTime() == null) {
            // 兼容旧数据:任务中状态也设置实际开始时间
            task.setActualStartTime(DateUtils.getNowDate());
        } else if (newStatus == TaskStatus.COMPLETED) {
            // 已完成:设置实际结束时间
            task.setActualEndTime(DateUtils.getNowDate());
        }
        
        int result = sysTaskMapper.updateTaskStatus(task);
        
        // 记录操作日志(含GPS位置信息)
        if (result > 0) {
            recordTaskLog(taskId, "STATUS_CHANGE", "状态变更", 
                         "状态:" + oldTaskStatus.getInfo(), 
                         "状态:" + newStatus.getInfo() + ",备注:" + remark, 
                         SecurityUtils.getUserId(), SecurityUtils.getUsername(),
                         locationLog);
        }
        
        // 发布任务状态变更事件
        if (result > 0) {
            // 查询任务的所有执行人
            List<SysTaskAssignee> assignees = sysTaskAssigneeMapper.selectSysTaskAssigneeByTaskId(taskId);
            List<Long> assigneeIds = null;
            if (assignees != null && !assignees.isEmpty()) {
                assigneeIds = assignees.stream()
                    .map(SysTaskAssignee::getUserId)
                    .collect(Collectors.toList());
            }
            Long userId=SecurityUtils.getUserId();
            Double lng=locationLog==null?null: locationLog.getLongitude();
            Double lat=locationLog==null?null: locationLog.getLatitude();
            String address=locationLog==null?null: locationLog.getLocationAddress();
            eventPublisher.publishEvent(new TaskStatusChangedEvent(
                this,
                oldTask.getTaskId(),
                oldTask.getTaskCode(),
                oldTaskStatus.getCode(),
                newStatus.getCode(),
                oldTaskStatus.getInfo(),
                newStatus.getInfo(),
                assigneeIds,
                oldTask.getCreatorId(),
                userId,
                    lng, lat,
                    address
 
            ));
        }
        
        return result;
    }
 
    /**
     * 上传任务附件
     * 
     * @param taskId 任务ID
     * @param file 文件
     * @param category 附件分类
     * @return 结果
     */
    @Override
    @Transactional
    public Long uploadAttachment(Long taskId, MultipartFile file, String category) {
        return sysTaskAttachmentService.uploadAttachment(taskId, file, category);
    }
    
    /**
     * 从微信mediaId上传任务附件
     * 
     * @param taskId 任务ID
     * @param accessToken 微信AccessToken
     * @param mediaId 微信mediaId
     * @param category 附件分类
     * @return 返回附件ID
     */
    @Override
    @Transactional
    public Long uploadAttachmentFromWechat(Long taskId, String accessToken, String mediaId, String category) {
        return sysTaskAttachmentService.uploadAttachmentFromWechat(taskId, accessToken, mediaId, category);
    }
 
 
    /**
     * 删除任务附件
     * 
     * @param attachmentId 附件ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAttachment(Long attachmentId) {
        return sysTaskAttachmentService.deleteAttachment(attachmentId);
    }
    
    /**
     * 根据ID获取附件详情
     * 
     * @param attachmentId 附件ID
     * @return 附件详情
     */
    @Override
    public SysTaskAttachment getAttachmentById(Long attachmentId) {
        return sysTaskAttachmentService.getAttachmentById(attachmentId);
    }
 
    @Override
    public List<SysTaskAttachment> getAttachmentsByTaskId(Long taskId) {
        return sysTaskAttachmentService.getAttachmentsByTaskId(taskId);
    }
 
    /**
     * 分配车辆给任务
     * 
     * @param taskId 任务ID
     * @param vehicleId 车辆ID
     * @param remark 备注
     * @return 结果
     */
    @Override
    @Transactional
    public int assignVehicleToTask(Long taskId, Long vehicleId, String remark,Long userId,String userName) {
        int result = sysTaskVehicleService.assignVehicleToTask(taskId, vehicleId, remark, userId, userName);
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(taskId, "ASSIGN", "分配车辆", null, 
                         "分配车辆ID:" + vehicleId + ",备注:" + remark, 
                         userId, userName);
        }
        
        return result;
    }
 
    /**
     * 取消任务车辆分配
     * 
     * @param taskId 任务ID
     * @param vehicleId 车辆ID
     * @return 结果
     */
    @Override
    @Transactional
    public int unassignVehicleFromTask(Long taskId, Long vehicleId) {
        int result = sysTaskVehicleService.unassignVehicleFromTask(taskId, vehicleId);
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(taskId, "ASSIGN", "取消车辆分配", 
                         "取消车辆ID:" + vehicleId, null, 
                         SecurityUtils.getUserId(), SecurityUtils.getUsername());
        }
        
        return result;
    }
 
    /**
     * 批量分配车辆给任务
     * 
     * @param taskId 任务ID
     * @param vehicleIds 车辆ID列表
     * @param remark 备注
     * @return 结果
     */
    @Override
    @Transactional
    public int assignMultipleVehiclesToTask(Long taskId, List<Long> vehicleIds, String remark,Long userId,String userName) {
        int result = sysTaskVehicleService.assignMultipleVehiclesToTask(taskId, vehicleIds, remark, userId, userName);
        
        // 记录操作日志
        if (result > 0) {
            recordTaskLog(taskId, "ASSIGN", "批量分配车辆", null, 
                         "分配车辆数量:" + result + ",备注:" + remark, 
                         userId, userName);
        }
        
        return result;
    }
 
    /**
     * 查询任务关联的车辆
     * 
     * @param taskId 任务ID
     * @return 任务车辆关联列表
     */
    @Override
    public List<SysTaskVehicle> getTaskVehicles(Long taskId) {
        return sysTaskVehicleService.getTaskVehicles(taskId);
    }
 
    /**
     * 查询可用车辆
     * 
     * @param deptId 部门ID
     * @param taskType 任务类型
     * @return 可用车辆列表
     */
    @Override
    public List<SysTaskVehicle> getAvailableVehicles(Long deptId, String taskType) {
        return sysTaskVehicleService.getAvailableVehicles(deptId, taskType);
    }
 
    /**
     * 查询任务统计信息
     * 
     * @return 任务统计信息
     */
    @Override
    public TaskStatisticsVO getTaskStatistics() {
        return sysTaskMapper.selectTaskStatistics();
    }
 
    /**
     * 查询超时任务列表
     * 
     * @return 超时任务列表
     */
    @Override
    public List<SysTask> selectOverdueTasks() {
        return sysTaskMapper.selectOverdueTasks();
    }
 
    /**
     * 查询我的任务列表
     * 
     * @param userId 用户ID
     * @return 我的任务列表
     */
    @Override
    public List<SysTask> selectMyTasks(Long userId) {
        return sysTaskMapper.selectMyTasks(userId);
    }
 
    /**
     * 获取任务详情(包含关联数据)
     * 
     * @param taskId 任务ID
     * @return 任务详情
     */
    @Override
    public SysTask getTaskDetail(Long taskId) {
        SysTask task = sysTaskMapper.selectSysTaskByTaskId(taskId);
        if (task != null) {
            // 查询关联车辆
            task.setAssignedVehicles(sysTaskVehicleService.getTaskVehicles(taskId));
            // 查询附件(已自动拼接完整URL)
            task.setAttachments(sysTaskAttachmentService.getAttachmentsByTaskId(taskId));
            // 查询操作日志
            task.setOperationLogs(sysTaskLogMapper.selectSysTaskLogByTaskId(taskId));
            // 查询执行人员列表
            task.setAssignees(sysTaskAssigneeMapper.selectSysTaskAssigneeByTaskId(taskId));
            // 加载急救转运扩展信息
            if ("EMERGENCY_TRANSFER".equals(task.getTaskType())) {
                SysTaskEmergency emergencyInfo = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(taskId);
                task.setEmergencyInfo(emergencyInfo);
            }
            // 加载福祉车扩展信息
            else if ("WELFARE".equals(task.getTaskType())) {
                SysTaskWelfare welfareInfo = sysWelfareTaskService.getWelfareInfoByTaskId(taskId);
                task.setWelfareInfo(welfareInfo);
            }
        }
        return task;
    }
 
    /**
     * 检查车辆是否有正在进行中的任务
     * 正在进行中的任务是指状态不为:PENDING(待处理)、COMPLETED(已完成)、CANCELLED(已取消)的任务
     * 
     * @param vehicleId 车辆ID
     * @return 正在进行中的任务列表
     */
    @Override
    public List<SysTask> checkVehicleActiveTasks(Long vehicleId) {
        return sysTaskMapper.selectActiveTasksByVehicleId(vehicleId);
    }
 
    /**
     * 检查任务是否已关联旧系统服务单ID
     * 
     * @param taskId 任务ID
     * @return true-已关联,false-未关联
     */
    @Override
    public boolean hasLegacyServiceOrdId(Long taskId) {
        return sysEmergencyTaskService.hasLegacyServiceOrdId(taskId);
    }
 
    /**
     * 检查任务是否已关联旧系统调度单ID
     * 
     * @param taskId 任务ID
     * @return true-已关联,false-未关联
     */
    @Override
    public boolean hasLegacyDispatchOrdId(Long taskId) {
        return sysEmergencyTaskService.hasLegacyDispatchOrdId(taskId);
    }
 
    /**
     * 根据旧系统服务单ID检查是否存在任务
     * 
     * @param legacyServiceOrdId 旧系统服务单ID
     * @return true-存在,false-不存在
     */
    @Override
    public boolean existsByLegacyServiceOrdId(Long legacyServiceOrdId) {
        return sysEmergencyTaskService.existsByLegacyServiceOrdId(legacyServiceOrdId);
    }
 
    /**
     * 根据旧系统调度单ID检查是否存在任务
     * 
     * @param legacyDispatchOrdId 旧系统调度单ID
     * @return true-存在,false-不存在
     */
    @Override
    public boolean existsByLegacyDispatchOrdId(Long legacyDispatchOrdId) {
        return sysEmergencyTaskService.existsByLegacyDispatchOrdId(legacyDispatchOrdId);
    }
 
    @Autowired
    private TaskCodeGenerator taskCodeGenerator;
    
    /**
     * 生成任务编号
     * 
     * @return 任务编号
     */
    private String generateTaskCode() {
        return taskCodeGenerator.generateTaskCode();
    }
    
    /**
     * 从地址中提取城市名称(用于地图地理编码)
     * 
     * @param address 地址
     * @return 城市名称
     */
    private String extractCityFromAddress(String address) {
        if (address == null || address.trim().isEmpty()) {
            return null;
        }
        
        // 常见城市名列表
        String[] cities = {"广州", "深圳", "东莞", "佛山", "珠海", "惠州", "中山", "江门", "湛江", "肇庆", "清远", "韶关", "梅州", "河源", "潮州", "揭阳", "汕头", "汕尾", "云浮", "阳江","北京","上海","天津"};
        
        
        for (String city : cities) {
            if (address.contains(city)) {
                return city;
            }
        }
        
        return null;
    }
 
    /**
     * 记录任务操作日志
     * 
     * @param taskId 任务ID
     * @param operationType 操作类型
     * @param operationDesc 操作描述
     * @param oldValue 操作前值
     * @param newValue 操作后值
     * @param operatorId 操作人ID
     * @param operatorName 操作人姓名
     */
    private void recordTaskLog(Long taskId, String operationType, String operationDesc, 
                              String oldValue, String newValue, Long operatorId, String operatorName) {
        recordTaskLog(taskId, operationType, operationDesc, oldValue, newValue, 
                     operatorId, operatorName, null);
    }
 
    /**
     * 记录任务操作日志(含GPS位置信息)
     * 
     * @param taskId 任务ID
     * @param operationType 操作类型
     * @param operationDesc 操作描述
     * @param oldValue 操作前值
     * @param newValue 操作后值
     * @param operatorId 操作人ID
     * @param operatorName 操作人姓名
     * @param log GPS位置信息日志对象(可为null)
     */
    private void recordTaskLog(Long taskId, String operationType, String operationDesc, 
                              String oldValue, String newValue, Long operatorId, String operatorName,
                              SysTaskLog log) {
        if (log == null) {
            log = new SysTaskLog();
        }
        
        log.setTaskId(taskId);
        log.setOperationType(operationType);
        log.setOperationDesc(operationDesc);
        log.setOldValue(oldValue);
        log.setNewValue(newValue);
        log.setOperatorId(operatorId);
        log.setOperatorName(operatorName);
        log.setOperationTime(DateUtils.getNowDate());
        // 这里可以获取IP地址
        log.setIpAddress("127.0.0.1");
        
        sysTaskLogMapper.insertSysTaskLog(log);
    }
 
    /**
     * 构建任务描述
     * 
     * @param task 任务对象
     * @return 任务描述
     */
    private String buildTaskDescription(SysTask task) {
        StringBuilder sb = new StringBuilder();
        sb.append("任务编号:").append(task.getTaskCode()).append(",");
        sb.append("任务类型:").append(task.getTaskType()).append(",");
        sb.append("任务状态:").append(task.getTaskStatus()).append(",");
        if (StringUtils.isNotEmpty(task.getTaskDescription())) {
            sb.append("任务描述:").append(task.getTaskDescription()).append(",");
        }
        return sb.toString();
    }
 
 
    /**
     * 从TaskCreateVO设置地址和坐标信息到任务对象
     * 
     * @param task 任务对象
     * @param createVO 创建VO
     */
    private void setAddressAndCoordinatesFromVO(SysTask task, TaskCreateVO createVO) {
        // 设置通用地址和坐标信息
        if (createVO.getDepartureAddress() != null) {
            task.setDepartureAddress(createVO.getDepartureAddress());
        }
        if (createVO.getDestinationAddress() != null) {
            task.setDestinationAddress(createVO.getDestinationAddress());
        }
        if (createVO.getDepartureLongitude() != null) {
            task.setDepartureLongitude(createVO.getDepartureLongitude());
        }
        if (createVO.getDepartureLatitude() != null) {
            task.setDepartureLatitude(createVO.getDepartureLatitude());
        }
        if (createVO.getDestinationLongitude() != null) {
            task.setDestinationLongitude(createVO.getDestinationLongitude());
        }
        if (createVO.getDestinationLatitude() != null) {
            task.setDestinationLatitude(createVO.getDestinationLatitude());
        }
        if (createVO.getEstimatedDistance() != null) {
            task.setEstimatedDistance(createVO.getEstimatedDistance());
        }
    }
 
    /**
     * 设置任务类型特定信息(急救转运/福祉车)
     * 
     * @param task 任务对象
     * @param createVO 创建VO
     */
    private void setTaskTypeSpecificInfo(SysTask task, TaskCreateVO createVO) {
        // 设置急救转运特定信息
        if (createVO.getTransferTime() != null) {
            task.setPlannedStartTime(createVO.getTransferTime());
        }
        if (createVO.getTransferDistance() != null) {
            task.setEstimatedDistance(createVO.getTransferDistance());
        }
        
        // 设置福祉车特定信息
        if (createVO.getServiceTime() != null) {
            task.setPlannedStartTime(createVO.getServiceTime());
        }
        if (createVO.getStartAddress() != null) {
            task.setDepartureAddress(createVO.getStartAddress());
        }
        if (createVO.getEndAddress() != null) {
            task.setDestinationAddress(createVO.getEndAddress());
        }
        if (createVO.getDistance() != null) {
            task.setEstimatedDistance(createVO.getDistance());
        }
    }
 
    /**
     * 自动填充缺失的GPS坐标
     * 
     * @param task 任务对象
     */
    private void autoFillMissingGpsCoordinates(SysTask task) {
        // 自动获取出发地GPS坐标(如果缺失)
        if (task.getDepartureAddress() != null && 
            (task.getDepartureLongitude() == null || task.getDepartureLatitude() == null) && 
            mapService != null) {
            try {
                Map<String, Double> coords = mapService.geocoding(
                    task.getDepartureAddress(), 
                    extractCityFromAddress(task.getDepartureAddress())
                );
                if (coords != null) {
                    task.setDepartureLongitude(BigDecimal.valueOf(coords.get("lng")));
                    task.setDepartureLatitude(BigDecimal.valueOf(coords.get("lat")));
                }
            } catch (Exception e) {
                log.error("自动获取出发地GPS坐标失败", e);
            }
        }
        
        // 自动获取目的地GPS坐标(如果缺失)
        if (task.getDestinationAddress() != null && 
            (task.getDestinationLongitude() == null || task.getDestinationLatitude() == null) && 
            mapService != null) {
            try {
                Map<String, Double> coords = mapService.geocoding(
                    task.getDestinationAddress(), 
                    extractCityFromAddress(task.getDestinationAddress())
                );
                if (coords != null) {
                    task.setDestinationLongitude(BigDecimal.valueOf(coords.get("lng")));
                    task.setDestinationLatitude(BigDecimal.valueOf(coords.get("lat")));
                }
            } catch (Exception e) {
                log.error("自动获取目的地GPS坐标失败", e);
            }
        }
    }
 
    /**
     * 计算预计公里数
     * 
     * @param task 任务对象
     */
    private void calculateEstimatedDistance(SysTask task) {
        if (task.getDepartureLongitude() != null && task.getDepartureLatitude() != null &&
            task.getDestinationLongitude() != null && task.getDestinationLatitude() != null) {
            
            // 验证GPS坐标是否有效
            if (GpsDistanceUtils.isValidCoordinate(task.getDepartureLatitude(), task.getDepartureLongitude()) &&
                GpsDistanceUtils.isValidCoordinate(task.getDestinationLatitude(), task.getDestinationLongitude())) {
                
                // 计算距离
                java.math.BigDecimal distance = GpsDistanceUtils.calculateDistance(
                    task.getDepartureLatitude(), task.getDepartureLongitude(),
                    task.getDestinationLatitude(), task.getDestinationLongitude()
                );
                
                task.setEstimatedDistance(distance);
            } else {
                // 坐标无效,设置为0
                task.setEstimatedDistance(java.math.BigDecimal.ZERO);
            }
        } else {
            // 坐标不完整,设置为0
            task.setEstimatedDistance(java.math.BigDecimal.ZERO);
        }
    }
 
    /**
     * 检查任务是否可以出发
     * 检查:
     * 1. 车辆是否有未完成的任务
     * 2. 执行人员是否有未完成的任务
     * 
     * @param taskId 任务ID
     * @return AjaxResult 校验结果
     */
    @Override
    public AjaxResult checkTaskCanDepart(Long taskId) {
        // 获取任务详情
        SysTask task = this.getTaskDetail(taskId);
        if (task == null) {
            return AjaxResult.error("任务不存在");
        }
        
        List<Map<String, Object>> conflicts = new ArrayList<>();
        
        // 1. 检查车辆是否有未完成的任务
        List<SysTaskVehicle> taskVehicles = task.getAssignedVehicles();
        if (taskVehicles != null && !taskVehicles.isEmpty()) {
            for (SysTaskVehicle taskVehicle : taskVehicles) {
                Long vehicleId = taskVehicle.getVehicleId();
                List<SysTask> vehicleActiveTasks = this.checkVehicleActiveTasks(vehicleId);
                
                // 过滤掉当前任务本身
                vehicleActiveTasks = vehicleActiveTasks.stream()
                    .filter(t -> !t.getTaskId().equals(taskId))
                    .collect(Collectors.toList());
                
                if (!vehicleActiveTasks.isEmpty()) {
                    for (SysTask activeTask : vehicleActiveTasks) {
                        Map<String, Object> conflict = new HashMap<>();
                        conflict.put("type", "vehicle");
                        conflict.put("vehicleNo", taskVehicle.getVehicleNo());
                        conflict.put("taskId", activeTask.getTaskId());
                        conflict.put("taskCode", activeTask.getTaskCode());
                        conflict.put("taskStatus", activeTask.getTaskStatus());
                        conflict.put("message", String.format("车辆 %s 尚有未完成的任务 %s,请先完成", 
                            taskVehicle.getVehicleNo(), activeTask.getTaskCode()));
                        conflicts.add(conflict);
                    }
                }
            }
        }
        
        // 2. 检查执行人员是否有未完成的任务
        List<SysTaskAssignee> assignees = task.getAssignees();
        if (assignees != null && !assignees.isEmpty()) {
            for (SysTaskAssignee assignee : assignees) {
                Long userId = assignee.getUserId();
                
                // 查询该执行人的所有正在进行中的任务(排除PENDING、COMPLETED、CANCELLED)
                List<SysTask> userActiveTasks = this.selectMyTasks(userId).stream()
                    .filter(t -> !TaskStatus.PENDING.getCode().equals(t.getTaskStatus())
                              && !TaskStatus.COMPLETED.getCode().equals(t.getTaskStatus()) 
                              && !TaskStatus.CANCELLED.getCode().equals(t.getTaskStatus())
                              && !t.getTaskId().equals(taskId)) // 过滤掉当前任务
                    .collect(Collectors.toList());
                
                if (!userActiveTasks.isEmpty()) {
                    for (SysTask activeTask : userActiveTasks) {
                        Map<String, Object> conflict = new HashMap<>();
                        conflict.put("type", "assignee");
                        conflict.put("userName", assignee.getUserName());
                        conflict.put("taskId", activeTask.getTaskId());
                        conflict.put("taskCode", activeTask.getTaskCode());
                        conflict.put("taskStatus", activeTask.getTaskStatus());
                        conflict.put("message", String.format("执行人 %s 尚有正在进行中的任务 %s,请先完成", 
                            assignee.getUserName(), activeTask.getTaskCode()));
                        conflicts.add(conflict);
                    }
                }
            }
        }
        
        // 3. 检查执行人是否全部就绪(受配置开关控制)
        String readyCheckEnabled = configService.selectConfigByKey("task.assignee.ready.check.enabled");
        if ("true".equalsIgnoreCase(readyCheckEnabled)) {
             assignees = task.getAssignees();
            if (assignees != null && !assignees.isEmpty()) {
                boolean allReady = assignees.stream()
                    .allMatch(a -> "1".equals(a.getIsReady()));
                if (!allReady) {
                    Map<String, Object> conflict = new HashMap<>();
                    conflict.put("type", "assigneeReady");
                    conflict.put("message", "存在未就绪的执行人,请等待所有执行人点击就绪后再出车");
                    conflicts.add(conflict);
                }
            }
        }
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("valid", conflicts.isEmpty());
        result.put("conflicts", conflicts);
        
        return AjaxResult.success(result);
    }
 
    /**
     * 执行人点击就绪
     * 
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult setAssigneeReady(Long taskId, Long userId) {
        return sysTaskAssigneeService.setAssigneeReady(taskId, userId);
    }
 
    /**
     * 取消执行人就绪
     * 
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult cancelAssigneeReady(Long taskId, Long userId) {
        return sysTaskAssigneeService.cancelAssigneeReady(taskId, userId);
    }
   
}