wlzboy
4 小时以前 5f2ee03958a1a16dc27195c76ea7cffb422c95d1
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
package com.ruoyi.system.listener;
 
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DeptUtil;
import com.ruoyi.common.utils.LongUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.event.*;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysMessageMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysTaskMapper;
import com.ruoyi.system.mapper.SysTaskEmergencyMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 任务消息监听器
 * 监听任务相关事件并保存消息到消息库
 * 
 * @author ruoyi
 * @date 2025-10-25
 */
@Component
public class TaskMessageListener {
    
    private static final Logger log = LoggerFactory.getLogger(TaskMessageListener.class);
    
    @Autowired
    private SysMessageMapper sysMessageMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;
 
    @Autowired
    private SysTaskMapper sysTaskMapper;
 
    @Autowired
    private SysTaskEmergencyMapper sysTaskEmergencyMapper;
 
    @Autowired
    private INotifyTaskService notifyTaskService;
 
    @Autowired
    private INotifyDispatchService notifyDispatchService;
 
    /** 待准备状态 - 可以发送短信通知 */
    private static final String TASK_STATUS_PENDING = "PENDING";
    /** 待准备状态 - 可以发送短信通知 */
    private static final String TASK_STATUS_PREPARING = "PREPARING";
 
    @Autowired
    private ISysTaskAssigneeService taskAssigneeService;
 
    @Async
    @EventListener
    public void handleTaskDispatchEvent(TaskDispatchSyncEvent event) {
        try{
            log.info("收到任务派发同步事件,任务ID:{},任务编号:{},派发单ID:{}", event.getTaskId(), event.getTaskCode(), event.getDispatchOrderId());
            SysTask task=sysTaskMapper.selectSysTaskByTaskId(event.getTaskId());
            SysTaskEmergency emergency = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(event.getTaskId());
            if(emergency != null){
               List<SysTaskAssignee> assignees=taskAssigneeService.getAssigneesByTaskId(emergency.getTaskId());
               if(assignees!=null && !assignees.isEmpty()){
                   List<Long> assigneeIds=assignees.stream().map(SysTaskAssignee::getUserId).collect(Collectors.toList());
                   task.setEmergencyInfo( emergency);
                   sendDispatchNotify(assigneeIds, task.getCreatorId(), event.getTaskId(),task.getShowTaskCode(), buildNotifyContent(task, emergency));
               }
            }
 
            Long taskId= event.getTaskId();
            Long dispatchOrdId= event.getDispatchOrderId();
            Long serviceOrdId= event.getServiceOrderId();
            Integer oaUserID= event.getOaUserId();
            legacySystemSyncService.syncTaskAttachment(taskId, dispatchOrdId, serviceOrdId, oaUserID);
 
        }catch (Exception ex){
            log.error("处理任务派发同步事件失败", ex);
        }
    }
    /**
     * 监听任务创建事件
     * 
     * @param event 任务创建事件
     */
    @Async
    @EventListener
    public void handleTaskCreatedEvent(TaskCreatedEvent event) {
        try {
            log.info("收到任务创建事件,任务ID:{},任务编号:{}", event.getTaskId(), event.getTaskCode());
            
            // 获取创建人信息
            SysUser creator = sysUserMapper.selectUserById(event.getCreatorId());
            if (creator == null) {
                log.warn("找不到创建人信息,用户ID:{}", event.getCreatorId());
                return;
            }
            
            // 创建消息
            SysMessage message = new SysMessage();
            message.setMessageType("CREATE");
            message.setMessageTitle("任务创建成功");
            message.setMessageContent("您创建的任务已成功提交");
            message.setTaskId(event.getTaskId());
            message.setTaskCode(event.getTaskCode());
            message.setReceiverId(event.getCreatorId());
            message.setReceiverName(creator.getNickName());
            message.setSenderId(event.getCreatorId());
            message.setSenderName("系统");
            message.setIsRead("0");
            message.setCreateTime(DateUtils.getNowDate());
            message.setDelFlag("0");
            
            // 保存消息
            sysMessageMapper.insertSysMessage(message);
            log.info("任务创建消息已保存,消息ID:{}", message.getMessageId());
            
        } catch (Exception e) {
            log.error("处理任务创建事件失败", e);
        }
    }
 
 
    @Autowired
    private ISysDeptService sysDeptService;
    /**
     * 只有服务单,且只在广州外的服务单,没有调度单
     * @param event
     */
    @Async
    @EventListener
    public void handleTaskOnlyServiceSync(TaskDispatchSyncEvent event){
        //给负责人发送消息
       Long taskId= event.getTaskId();
       SysTask task=sysTaskMapper.selectSysTaskByTaskId(taskId);
       SysTaskEmergency emergency = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(taskId);
       if(emergency != null){
           task.setEmergencyInfo( emergency);
           Long deptId=task.getDeptId();
           if(!deptId.equals(DeptUtil.GUANGZHOU_DEPT_ID)){
               //找到该部门的负责人
               SysDept dept= sysDeptService.selectDeptById(deptId);
               if(dept!=null){
                  String serviceOrdClass= dept.getServiceOrderClass();
                  String dispatchOrdClass= dept.getDispatchOrderClass();
                  List<SysUser> user=sysUserMapper.selectUsersByOrderClassAndCanViewAllConsult(serviceOrdClass);
                  if(user!=null && !user.isEmpty()){
                      List<NotifyTask> tasks=new ArrayList<>();
                      String buildNotifyContent = buildUnAssignNotifyContent(task, emergency);
                      for(SysUser u:user){
                       NotifyTask notifyTask= this.sendTaskUnAssignNotify(u.getUserId(),u.getNickName(),u.getPhonenumber(),taskId,task.getShowTaskCode(),"服务单派发",buildNotifyContent);
                       tasks.add(notifyTask);
                      }
                      if(!tasks.isEmpty()){
                          int successCount = notifyDispatchService.dispatchNotifies(tasks);
                          log.info("任务未分配消息已发送,发送成功数量:{}", successCount);
                      }
                  }
               }
           }
 
 
 
       }
    }
 
    private  String buildUnAssignNotifyContent(SysTask task, SysTaskEmergency emergency){
        //派发单号
        String dispatchCode=emergency.getDispatchCode();
        String taskCode=task.getTaskCode();
        String orderCode=dispatchCode;
        if(dispatchCode==null){
            orderCode=taskCode;
        }
        Date dispatchTime=task.getPlanedStartTime();
 
        StringBuilder content = new StringBuilder();
        content.append("您有新的服务单,任务单号:"+orderCode);
        // 添加出发地信息
        String departure = null;
        if (emergency != null && StringUtils.isNotEmpty(emergency.getHospitalOutName())) {
            departure = emergency.getHospitalOutName();
        } else if (StringUtils.isNotEmpty(task.getDepartureAddress())) {
            departure = task.getDepartureAddress();
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        content.append(",出发时间:").append(df.format(dispatchTime));
 
        // 添加目的地信息
        String destination = null;
        if (emergency != null && StringUtils.isNotEmpty(emergency.getHospitalInName())) {
            destination = emergency.getHospitalInName();
        } else if (StringUtils.isNotEmpty(task.getDestinationAddress())) {
            destination = task.getDestinationAddress();
        }
 
        if (departure != null || destination != null) {
            if (departure != null) {
                content.append("出发地:").append(departure);
            }
            if (destination != null) {
                if (content.length() > 0) content.append(",");
                content.append("目的地:").append(destination);
            }
            content.append(",请及时处理。");
        }
 
        return content.toString();
    }
 
 
 
 
    @Autowired
    private ILegacySystemSyncService legacySystemSyncService;
 
    @Async
    @EventListener
    public void handleTaskUpdateEvent(TaskUpdateEvent event){
        log.info("收到任务更新事件,任务ID:{},任务编号:{}", event.getTaskId(), event.getTaskCode());
        legacySystemSyncService.resyncDispatchOrderToLegacy(event.getTaskId());
 
    }
    //在这里监听派发的事件
    @Async
    @EventListener
    public void handleTaskServiceOrderSyncEvent(TaskServiceOrderSyncEvent event) {
//        log.info("收到任务服务单同步事件,任务ID:{},任务编号:{},服务单ID:{}", event.getTaskId(), event.getTaskCode(), event.getServiceOrderId());
       Long dispatchOrderId= legacySystemSyncService.syncDispatchOrderToLegacy(event.getTaskId());
//       if(LongUtil.isNotEmpty(dispatchOrderId)){
//           //更新needsync为0
//
//       }
    }
 
 
    /**
     * 监听任务分配事件
     * 创建通知任务,由通知分发服务决定发送渠道
     * 
     * @param event 任务分配事件
     */
    @Async
    @EventListener
    public void handleTaskAssignedEvent(TaskAssignedEvent event) {
        try {
            log.info("收到任务分配事件,任务ID:{},任务编号:{},执行人数量:{}", 
                    event.getTaskId(), event.getTaskCode(), 
                    event.getAssigneeIds() != null ? event.getAssigneeIds().size() : 0);
            
            if (event.getAssigneeIds() == null || event.getAssigneeIds().isEmpty()) {
                log.warn("执行人ID列表为空,无法推送消息");
                return;
            }
 
            // 查询任务信息
            SysTask task = sysTaskMapper.selectSysTaskByTaskId(event.getTaskId());
            if (task == null) {
                log.warn("任务不存在,taskId={}", event.getTaskId());
                return;
            }
 
            // 查询急救扩展信息(用于构建通知内容)
            SysTaskEmergency emergency = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(event.getTaskId());
 
            Long creatorId = task.getCreatorId();
            String taskStatus = task.getTaskStatus();
            task.setEmergencyInfo(emergency);
            // 仅在待准备状态下发送通知
            if (!TASK_STATUS_PENDING.equals(taskStatus) && !TASK_STATUS_PREPARING.equals(taskStatus)) {
                log.info("任务状态({})非待准备状态,跳过通知,taskId={}", taskStatus, event.getTaskId());
                return;
            }
 
            // 构建通知内容
            String notifyContent = buildNotifyContent(task, emergency);
            this.sendDispatchNotify(event.getAssigneeIds(), creatorId, event.getTaskId(),task.getShowTaskCode(), notifyContent);
 
            
        } catch (Exception e) {
            log.error("处理任务分配事件失败", e);
        }
    }
 
    /**
     * 向执行人发送任务分配通知
     * @param assigneeIds
     * @param creatorId
     * @param taskId
     * @param taskCode
     *
     * @param notifyContent
     */
 
    private void sendDispatchNotify(List<Long> assigneeIds, Long creatorId,
                            Long taskId,String taskCode,String notifyContent) {
        // 收集创建的通知任务
 
        List<NotifyTask> createdTasks = new ArrayList<>();
 
        // 为每个执行人创建通知任务
        for (Long assigneeId : assigneeIds) {
            // 排除创建人
            if (creatorId != null && creatorId.equals(assigneeId)) {
                log.debug("跳过创建人,不发送任务分配通知,userId={}", assigneeId);
                continue;
            }
 
            // 获取执行人信息
            SysUser assignee = sysUserMapper.selectUserById(assigneeId);
            if (assignee == null) {
                log.warn("找不到执行人信息,用户ID:{}", assigneeId);
                continue;
            }
 
            // 创建通知任务(带防重)
            NotifyTask notifyTask = new NotifyTask();
            notifyTask.setTaskId(taskId);
            notifyTask.setTaskCode(taskCode);
            notifyTask.setNotifyType(NotifyTask.NOTIFY_TYPE_TASK_ASSIGN);
            notifyTask.setUserId(assigneeId);
            notifyTask.setUserName(assignee.getNickName());
            notifyTask.setUserPhone(assignee.getPhonenumber());
            notifyTask.setTitle("转运单任务派单通知");
            notifyTask.setContent(notifyContent);
            notifyTask.setCreateBy( "系统");
 
            NotifyTask created = notifyTaskService.createNotifyTask(notifyTask);
            if (created != null) {
                createdTasks.add(created);
                log.info("创建通知任务成功,id={}, userId={}", created.getId(), assigneeId);
            } else {
                log.info("通知任务已存在,跳过,taskId={}, userId={}", taskId, assigneeId);
            }
        }
 
        // 分发通知任务
        if (!createdTasks.isEmpty()) {
            int successCount = notifyDispatchService.dispatchNotifies(createdTasks);
            log.info("通知分发完成,taskId={},创建数量={},成功数量={}",
                    taskId, createdTasks.size(), successCount);
        }
    }
 
    private NotifyTask  sendTaskUnAssignNotify(Long userId,String nickName,String phone,
                            Long taskId,String taskCode,String title,String notifyContent) {
        NotifyTask notifyTask = new NotifyTask();
        notifyTask.setTaskId(taskId);
        notifyTask.setTaskCode(taskCode);
        notifyTask.setNotifyType(NotifyTask.NOTIFY_TASK_UNASSIGN);
        notifyTask.setUserId(userId);
        notifyTask.setUserName(nickName);
        notifyTask.setUserPhone(phone);
        notifyTask.setTitle(title);
        notifyTask.setContent(notifyContent);
        notifyTask.setCreateBy( "系统");
 
        NotifyTask created = notifyTaskService.createNotifyTask(notifyTask);
        return created;
    }
    /**
     * 构建通知内容
     */
    private String buildNotifyContent(SysTask task, SysTaskEmergency emergency) {
        //派发单号
        String dispatchCode=emergency.getDispatchCode();
        String taskCode=task.getTaskCode();
        String orderCode=dispatchCode;
        if(dispatchCode==null){
            orderCode=taskCode;
        }
        Date dispatchTime=task.getPlanedStartTime();
 
        StringBuilder content = new StringBuilder();
        content.append("您有新的转运任务,任务单号:"+orderCode);
        // 添加出发地信息
        String departure = null;
        if (emergency != null && StringUtils.isNotEmpty(emergency.getHospitalOutName())) {
            departure = emergency.getHospitalOutName();
        } else if (StringUtils.isNotEmpty(task.getDepartureAddress())) {
            departure = task.getDepartureAddress();
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        content.append(",出发时间:").append(df.format(dispatchTime));
 
        // 添加目的地信息
        String destination = null;
        if (emergency != null && StringUtils.isNotEmpty(emergency.getHospitalInName())) {
            destination = emergency.getHospitalInName();
        } else if (StringUtils.isNotEmpty(task.getDestinationAddress())) {
            destination = task.getDestinationAddress();
        }
        
        if (departure != null || destination != null) {
            if (departure != null) {
                content.append("出发地:").append(departure);
            }
            if (destination != null) {
                if (content.length() > 0) content.append(",");
                content.append("目的地:").append(destination);
            }
            content.append(",请及时处理。");
        }
        
        return content.toString();
    }
 
    /**
     * 监听任务状态变更事件
     * 
     * @param event 任务状态变更事件
     */
    @Async
    @EventListener
    public void handleTaskStatusChangedEvent(TaskStatusChangedEvent event) {
        try {
            log.info("收到任务状态变更事件,任务ID:{},旧状态:{},新状态:{}", 
                    event.getTaskId(), event.getOldStatus(), event.getNewStatus());
            
            // 构建状态变更内容
            String statusContent = getStatusChangeContent(event.getNewStatus(), event.getNewStatusDesc());
            
            // 收集所有需要通知的用户ID(执行人+创建人,去重)
            java.util.Set<Long> receiverIds = new java.util.HashSet<>();
            
            // 添加执行人
            if (event.getAssigneeIds() != null) {
                receiverIds.addAll(event.getAssigneeIds());
            }
            
            // 添加创建人(如果不是执行人)
            if (event.getCreatorId() != null) {
                receiverIds.add(event.getCreatorId());
            }
            
            // 给每个用户发送消息
            for (Long receiverId : receiverIds) {
                SysUser user = sysUserMapper.selectUserById(receiverId);
                if (user == null) {
                    log.warn("找不到用户信息,用户ID:{}", receiverId);
                    continue;
                }
                
                // 创建消息
                SysMessage message = new SysMessage();
                message.setMessageType("STATUS");
                message.setMessageTitle("任务状态变更");
                message.setMessageContent(statusContent);
                message.setTaskId(event.getTaskId());
                message.setTaskCode(event.getTaskCode());
                message.setReceiverId(receiverId);
                message.setReceiverName(user.getNickName());
                message.setSenderId(event.getCreatorId());
                message.setSenderName("系统");
                message.setIsRead("0");
                message.setCreateTime(DateUtils.getNowDate());
                message.setDelFlag("0");
                
                // 保存消息
                sysMessageMapper.insertSysMessage(message);
                log.info("任务状态变更消息已保存,消息ID:{},新状态:{},接收人:{}", 
                        message.getMessageId(), event.getNewStatus(), user.getNickName());
            }
            
        } catch (Exception e) {
            log.error("处理任务状态变更事件失败", e);
        }
    }
 
    /**
     * 根据状态获取状态变更内容
     * 
     * @param status 任务状态
     * @param statusDesc 状态描述
     * @return 状态变更内容
     */
    private String getStatusChangeContent(String status, String statusDesc) {
        if (statusDesc != null && !statusDesc.isEmpty()) {
            return "任务状态变更为:" + statusDesc;
        }
        
        switch (status) {
            case "PENDING":
                return "任务状态变更为:待处理";
            case "DEPARTING":
            case "DEPARTED":
                return "任务状态变更为:已出发";
            case "ARRIVED":
                return "任务状态变更为:已到达";
            case "RETURNING":
                return "任务状态变更为:返程中";
            case "COMPLETED":
                return "任务状态变更为:已完成";
            case "CANCELLED":
                return "任务状态变更为:已取消";
            default:
                return "任务状态已更新";
        }
    }
}