wlzboy
2025-12-02 d294abb765e4ed349907c92ce313689c6299ba7d
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
package com.ruoyi.system.service.impl;
 
import com.ruoyi.common.config.WechatConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WechatUtils;
import com.ruoyi.system.domain.SysTask;
import com.ruoyi.system.domain.SysTaskEmergency;
import com.ruoyi.system.mapper.SysTaskEmergencyMapper;
import com.ruoyi.system.mapper.SysTaskMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IWechatTaskNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 微信任务通知服务实现
 * 统一管理所有任务相关的微信订阅消息发送逻辑
 * 
 * @author ruoyi
 * @date 2025-11-30
 */
@Service
public class WechatTaskNotifyServiceImpl implements IWechatTaskNotifyService {
    
    private static final Logger log = LoggerFactory.getLogger(WechatTaskNotifyServiceImpl.class);
    
    @Autowired
    private SysTaskMapper sysTaskMapper;
    
    @Autowired
    private SysTaskEmergencyMapper sysTaskEmergencyMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private WechatConfig wechatConfig;
    
    /**
     * 发送任务通知消息给指定用户列表
     * 
     * @param taskId 任务ID
     * @param userIds 接收用户ID列表
     * @param excludeUserId 排除的用户ID(可选,如创建人)
     * @return 成功发送的消息数量
     */
    @Override
    public int sendTaskNotifyMessage(Long taskId, List<Long> userIds, Long excludeUserId) {
        if (taskId == null || userIds == null || userIds.isEmpty()) {
            log.warn("发送微信任务通知参数不完整,taskId={}, userIds={}", taskId, userIds);
            return 0;
        }
        
        // 查询任务信息
        SysTask task = sysTaskMapper.selectSysTaskByTaskId(taskId);
        if (task == null) {
            log.warn("微信通知失败,任务不存在,taskId={}", taskId);
            return 0;
        }
        
        // 查询急救信息
        SysTaskEmergency emergency = sysTaskEmergencyMapper.selectSysTaskEmergencyByTaskId(taskId);
        
        // 获取微信AccessToken
        String accessToken = WechatUtils.getAccessToken(wechatConfig.getAppId(), wechatConfig.getAppSecret());
        if (StringUtils.isEmpty(accessToken)) {
            log.error("获取微信AccessToken失败,无法发送任务通知");
            return 0;
        }
        
        // 构造消息数据
        Map<String, String> data = buildTaskNotifyData(task, emergency);
        
        // 获取模板配置
        String page = wechatConfig.getTaskDetailPage() + "?id=" + taskId;
        String templateId = wechatConfig.getTaskNotifyTemplateId();
        
        // 发送消息给每个用户
        int successCount = 0;
        for (Long userId : userIds) {
            // 排除指定用户
            if (excludeUserId != null && excludeUserId.equals(userId)) {
                log.debug("跳过排除用户,userId={}", userId);
                continue;
            }
            
            // 查询用户信息
            SysUser user = sysUserMapper.selectUserById(userId);
            if (user == null || StringUtils.isEmpty(user.getOpenId())) {
                log.debug("用户未绑定微信openId,跳过发送,userId={}", userId);
                continue;
            }
            
            // 发送订阅消息
            try {
                WechatUtils.sendSubscribeMessage(accessToken, user.getOpenId(), templateId, page, data);
                successCount++;
                log.info("微信任务通知发送成功,taskId={}, userId={}, userName={}", taskId, userId, user.getUserName());
            } catch (Exception e) {
                log.error("微信任务通知发送失败,taskId={}, userId={}", taskId, userId, e);
            }
        }
        
        log.info("微信任务通知批量发送完成,taskId={}, 总数={}, 成功={}", taskId, userIds.size(), successCount);
        return successCount;
    }
    
    /**
     * 发送任务通知消息给指定用户列表(不排除任何用户)
     * 
     * @param taskId 任务ID
     * @param userIds 接收用户ID列表
     * @return 成功发送的消息数量
     */
    @Override
    public int sendTaskNotifyMessage(Long taskId, List<Long> userIds) {
        return sendTaskNotifyMessage(taskId, userIds, null);
    }
    
    /**
     * 构造任务通知的消息数据
     * 
     * @param task 任务信息
     * @param emergency 急救信息(可选)
     * @return 消息数据Map
     */
    private Map<String, String> buildTaskNotifyData(SysTask task, SysTaskEmergency emergency) {
        // 事项描述
        String problemDesc = "您有新的转运任务,请及时处理";
        
        // 地点信息
        String location;
        if (emergency != null && StringUtils.isNotEmpty(emergency.getHospitalOutName()) && StringUtils.isNotEmpty(emergency.getHospitalInName())) {
            location = emergency.getHospitalOutName() + " → " + emergency.getHospitalInName();
        } else if (StringUtils.isNotEmpty(task.getDepartureAddress()) && StringUtils.isNotEmpty(task.getDestinationAddress())) {
            location = task.getDepartureAddress() + " → " + task.getDestinationAddress();
        } else {
            location = "未知地点";
        }
        
        // 时间信息
        String startTimeStr;
        if (task.getPlannedStartTime() != null) {
            startTimeStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", task.getPlannedStartTime());
        } else {
            startTimeStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", new java.util.Date());
        }
        
        // 运单号
        String waybillNo = StringUtils.isNotEmpty(task.getTaskCode()) ? task.getTaskCode() : String.valueOf(task.getTaskId());
        
        // 组装数据(应用thing类型字段的长度限制)
        Map<String, String> data = new HashMap<>();
        // data.put("thing1", WechatUtils.truncateThingValue(problemDesc));  // 截断thing类型字段
        // data.put("thing10", WechatUtils.truncateThingValue(location));  // 截断thing类型字段
        data.put("time8", startTimeStr);
        data.put("character_string1", waybillNo);
        
        return data;
    }
}