liusheng
2024-09-18 907641e56c2085aaa81f267946dc3e3e9fca73e7
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
package com.ruoyi.web.component;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.ServiceFromEnum;
import com.ruoyi.common.utils.RSAPublicKeyExample;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.web.task.PhoneTask;
import com.smartor.common.SendService;
import com.smartor.config.RobotPhoneUtils;
import com.smartor.domain.*;
import com.smartor.mapper.ServiceSubtaskMapper;
import com.smartor.mapper.ServiceTaskMapper;
import com.smartor.mapper.SvyTaskMapper;
import com.smartor.mapper.SvyTaskSingleMapper;
import com.smartor.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
 
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
@Slf4j
@Component//监听此队列
public class RedisMqReceiver extends KeyExpirationEventMessageListener {
 
    @Value("${phonePath}")
    private String phonePath;
 
    @Value("${pub_key}")
    private String pub_key;
 
    @Value("${localIP}")
    private String localIP;
 
    @Value("${req_path}")
    private String req_path;
 
    @Value("${thirdWXUrl}")
    private String thirdWXUrl;
 
    @Autowired
    private IIvrTaskTemplateService ivrTaskTemplateService;
    @Autowired
    private ISvyTaskTemplateService svyTaskTemplateService;
 
    @Autowired
    private ServiceSubtaskMapper ivrTaskcallMapper;
 
    @Autowired
    private ServiceTaskMapper ivrTaskMapper;
 
    @Autowired
    private SendService sendService;
 
    @Autowired
    private RedisCache redisCache;
 
    @Autowired
    private RobotPhoneUtils robotPhoneUtils;
 
    @Autowired
    private ServiceTaskMapper svyTaskMapper;
 
    @Autowired
    private ServiceSubtaskMapper serviceSubtaskMapper;
 
    @Autowired
    private ISvyTaskTemplateService iSvyTaskTemplateService;
 
    @Autowired
    private IServiceSubtaskRecordService serviceSubtaskRecordService;
 
    @Autowired
    IBaseSmsaccountService baseSmsaccountService;
 
    // 创建固定大小的线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);
 
    public RedisMqReceiver(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("监听Redis key过期,key:{},channel:{}", message.toString(), new String(pattern));
        String ip = localIP;
        log.error("本机的网络IP为:{}", ip);
        String content = message.toString();
        //判断是不是任务信息,如果不是,直接返回,不需要执行
        if (!content.contains("taskid")) {
            log.info("不是任务信息");
            return;
        }
        CommonTaskcallMQ commonTaskcallMQ = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            if (!content.startsWith("{")) {
                commonTaskcallMQ = mapper.readValue("{" + content + "}", CommonTaskcallMQ.class);
            } else {
                commonTaskcallMQ = mapper.readValue(content, CommonTaskcallMQ.class);
            }
            if (commonTaskcallMQ != null) tsakHandle(commonTaskcallMQ, ip, commonTaskcallMQ.getTaskType());
 
            //处理完成,移除redis
            redisCache.deleteObject(message.toString());
            //将状态改成完成
            ServiceTask serviceTask = new ServiceTask();
            serviceTask.setTaskid(Long.valueOf(commonTaskcallMQ.getTaskid()));
            serviceTask.setSendState(5L);
            serviceTask.setFail(1L);
            svyTaskMapper.updateServiceTask(serviceTask);
        } catch (Exception e) {
            Integer integer = redisCache.getCacheObject(commonTaskcallMQ.getTaskid().toString());
            if (integer != null && integer == 3) {
                redisCache.deleteObject(message.toString());
                ServiceTask serviceTask = new ServiceTask();
                serviceTask.setTaskid(Long.valueOf(commonTaskcallMQ.getTaskid().toString()));
                serviceTask.setFail(0L);
                svyTaskMapper.updateServiceTask(serviceTask);
                //将消息从队列中删除
            } else if (integer == null) {
                redisCache.setCacheObject(commonTaskcallMQ.getTaskid().toString(), 1, 120, TimeUnit.MINUTES);
            } else {
                redisCache.setCacheObject(commonTaskcallMQ.getTaskid().toString(), integer + 1, 120, TimeUnit.MINUTES);
            }
            log.error("============消费失败,尝试消息补发再次消费!==============  {}", e.getMessage());
            redisCache.setCacheObject(message.toString(), message.toString(), 60, TimeUnit.SECONDS);
        }
    }
 
    /**
     * 任务处理
     *
     * @param commonTaskcallMQ
     */
    public void tsakHandle(CommonTaskcallMQ commonTaskcallMQ, String ip, Integer type) {
        log.error("进任务了吗?{}", commonTaskcallMQ);
        //判断一下commonTaskcallMQ中的stopstate是否与ivr_task中的一致,不一致,则说明是暂停了
        ServiceTask ivrTask1 = ivrTaskMapper.selectServiceTaskByTaskid(commonTaskcallMQ.getTaskid());
        if (ivrTask1.getStopState() != commonTaskcallMQ.getStopState()) {
            //将消息从队列中剔除
            return;
        }
 
        if (StringUtils.isNotEmpty(commonTaskcallMQ.getPreachform())) {
            //如何任务发送方式不为空
            String[] split = commonTaskcallMQ.getPreachform().split(",");
            System.out.println("split的值为:" + split);
            for (String serviceFrom : split) {
                String descByCode = ServiceFromEnum.getDescByCode(Integer.valueOf(serviceFrom));
                //这里可以考虑用策略模式优化一下,不然太难看了
 
//                //通过模板ID获取模板问题
//                IvrTaskTemplateVO ivrTaskTemplateVO = new IvrTaskTemplateVO();
//                ivrTaskTemplateVO.setId(Long.valueOf(commonTaskcallMQ.getTemplateid()));
//                IvrTaskTemplateVO ivrTaskTemplateVO1 = ivrTaskTemplateService.selectInfoByCondition(ivrTaskTemplateVO);
 
                //通过任务ID拿到患者信息
                ServiceSubtaskVO ivrTaskcall = new ServiceSubtaskVO();
                ivrTaskcall.setTaskid(commonTaskcallMQ.getTaskid());
                List<ServiceSubtask> selectServiceSubtaskList = ivrTaskcallMapper.selectServiceSubtaskList(ivrTaskcall);
                if (descByCode.equals("电话")) {
                    for (ServiceSubtask serviceSubtask : selectServiceSubtaskList) {
                        ServiceTask ivrTask = ivrTaskMapper.selectServiceTaskByTaskid(serviceSubtask.getTaskid());
                        if (ivrTask.getSendState() != null && ivrTask.getSendState() == 3 || ivrTask.getSendState() != null && ivrTask.getSendState() == 4) {
                            //如何任务被“暂停”或“终止”
                            break;
                        }
                        //获取到value值最少的key
                        String key = getKey();
                        if (commonTaskcallMQ.getSendType().equals("2")) {
                            //说明是立即发送
                            String value = redisCache.getCacheObject("cache-0");
                            ServiceSubtaskVO serviceSubtask1 = new ServiceSubtaskVO();
                            serviceSubtask1.setTaskid(commonTaskcallMQ.getTaskid());
                            List<ServiceSubtask> selectServiceSubtaskList1 = ivrTaskcallMapper.selectServiceSubtaskList(serviceSubtask1);
                            for (ServiceSubtask serviceSubtask2 : selectServiceSubtaskList1) {
                                if (StringUtils.isEmpty(value)) {
                                    value = "," + serviceSubtask2.getId().toString() + ",";
                                } else {
                                    value = value + "," + serviceSubtask2.getId().toString() + ",";
                                }
                            }
                            redisCache.setCacheObject("cache-0", value);
                        } else {
                            //非立即发送
                            String value = redisCache.getCacheObject(key);
                            ServiceSubtaskVO serviceSubtask1 = new ServiceSubtaskVO();
                            serviceSubtask1.setTaskid(commonTaskcallMQ.getTaskid());
                            List<ServiceSubtask> selectServiceSubtaskList1 = ivrTaskcallMapper.selectServiceSubtaskList(serviceSubtask1);
                            for (ServiceSubtask serviceSubtask2 : selectServiceSubtaskList1) {
                                if (StringUtils.isEmpty(value)) {
                                    value = "," + serviceSubtask2.getId().toString() + ",";
                                } else {
                                    value = value + "," + serviceSubtask2.getId().toString() + ",";
                                }
                            }
                            redisCache.setCacheObject(key, value);
                        }
 
                        //任务发送记录(这个代码应该写在phoneTask中,先写在这,后面再改)
                        ServiceSubtaskRecord serviceSubtaskRecord = new ServiceSubtaskRecord();
                        serviceSubtaskRecord.setTaskid(serviceSubtask.getTaskid().toString());
                        serviceSubtaskRecord.setUuid(UUID.randomUUID().toString());
                        serviceSubtaskRecord.setTasktype(serviceSubtask.getType());
                        serviceSubtaskRecord.setPreachform("3");
                        serviceSubtaskRecord.setStartTime(System.currentTimeMillis());
                        serviceSubtaskRecordService.insertServiceSubtaskRecord(serviceSubtaskRecord);
 
//                        //通过多线程的方式去打电话
//                        executorService.submit(new PhoneTask(serviceSubtask, ivrTaskTemplateVO1, redisCache, sendService, phonePath, robotPhoneUtils));
                    }
                } else if (descByCode.equals("多媒体")) {
                    //多媒体
                    continue;
                } else if (descByCode.equals("纸质")) {
                    //纸质
                    continue;
                } else if (descByCode.equals("短信")) {
                    //短信
//                        http://localhost:8099/followvisit/particty?param1=3&param2=348
                    //对url中两个参数加密
                    RSAPublicKeyExample rsaPublicKeyExample = new RSAPublicKeyExample();
                    String taskId = rsaPublicKeyExample.encryptedData(ivrTask1.getTaskid().toString(), pub_key);
 
                    for (ServiceSubtask serviceSubtask : selectServiceSubtaskList) {
                        try {
                            String patid = rsaPublicKeyExample.encryptedData(serviceSubtask.getPatid().toString(), pub_key);
                            SendMagParam sendMagParam = new SendMagParam();
                            sendMagParam.setType("4");
                            if (type == 1) {
                                sendMagParam.setUrl(ip + ":" + req_path + "/followvisit/particty?param1=" + taskId + "&param2=" + patid + "&param5=false");
                            } else if (type == 1) {
                                sendMagParam.setUrl(ip + ":" + req_path + "/outsideChainwt?param1=" + taskId + "&param2=" + patid + "&param3=" + URLEncoder.encode(ivrTask1.getTaskName(), StandardCharsets.UTF_8.toString()) + "&param5=false");
                            } else if (type == 3) {
                                sendMagParam.setUrl(ip + ":" + req_path + "/outsideChainxj?param1=" + taskId + "&param2=" + patid + "&param3=" + URLEncoder.encode(ivrTask1.getTaskName(), StandardCharsets.UTF_8.toString()) + "&param5=false");
                            }
                            Boolean aBoolean = sendService.sendMsg(sendMagParam);
 
                            //任务发送记录
                            ServiceSubtaskRecord serviceSubtaskRecord = new ServiceSubtaskRecord();
                            serviceSubtaskRecord.setTaskid(serviceSubtask.getTaskid().toString());
                            serviceSubtaskRecord.setUuid(UUID.randomUUID().toString());
                            serviceSubtaskRecord.setTasktype(serviceSubtask.getType());
                            serviceSubtaskRecord.setPreachform("4");
                            serviceSubtaskRecord.setStartTime(System.currentTimeMillis());
                            serviceSubtaskRecord.setResult(aBoolean == true ? "success" : "error");
                            serviceSubtaskMapper.updateServiceSubtask(serviceSubtask);
                            serviceSubtaskRecordService.insertServiceSubtaskRecord(serviceSubtaskRecord);
                        } catch (UnsupportedEncodingException e) {
                            String guid = UUID.randomUUID().toString();
                            log.error("短信任务,发送失败原因:{},{}", e.getMessage(), guid);
                            serviceSubtask.setResult("error");
                            serviceSubtask.setRemark("系统错误(任务)");
                            serviceSubtask.setGuid(guid);
                            serviceSubtask.setSendstate(4L);
                            serviceSubtask.setFinishtime(new Date());
                            serviceSubtaskMapper.insertServiceSubtask(serviceSubtask);
                        }
                    }
                } else if (descByCode.equals("公众号")) {
                    //公众号
                    RSAPublicKeyExample rsaPublicKeyExample = new RSAPublicKeyExample();
                    String taskId = rsaPublicKeyExample.encryptedData(ivrTask1.getTaskid().toString(), pub_key);
                    for (ServiceSubtask serviceSubtask : selectServiceSubtaskList) {
                        String patid = rsaPublicKeyExample.encryptedData(serviceSubtask.getPatid().toString(), pub_key);
 
//                        SendMagParam sendMagParam = new SendMagParam();
//                        sendMagParam.setType("5");
//                        sendMagParam.setUrl(ip + ":" + req_path + "/outsideChain?param1=" + taskId + "&param2=" + patid + "&param3=" + ivrTask1.getTaskName() + "&param5=false");
//                        log.info("链接完整路径:{}", ip + ":" + req_path + "/outsideChain?param1=" + taskId + "&param2=" + patid + "&param3=" + ivrTask1.getTaskName() + "&param5=false");
//                        //这个模板ID先写死,后面做成可选
//                        sendMagParam.setTmpCode("oG3pJHPVWpE81DmZsua_2tKwgJ97r0qz37z56ns7NB4");
//                        Map map = new HashMap();
//                        map.put("first", ivrTask1.getTaskName());
//                        sendMagParam.setContent(JSON.toJSONString(map));
//                        sendMagParam.setOpenid(serviceSubtask.getOpenid());
//                        Boolean aBoolean = sendService.sendMsg(sendMagParam);
                        String url = null;
                        try {
                            if (type == 1) {
                                url = ip + ":" + req_path + "/outsideChain?param1=" + taskId + "&param2=" + patid + "&param3=" + URLEncoder.encode(ivrTask1.getTaskName(), StandardCharsets.UTF_8.toString()) + "&param5=false";
                            } else if (type == 2) {
                                url = ip + ":" + req_path + "/outsideChainwt?param1=" + taskId + "&param2=" + patid + "&param3=" + URLEncoder.encode(ivrTask1.getTaskName(), StandardCharsets.UTF_8.toString()) + "&param5=false";
                            } else if (type == 3) {
                                url = ip + ":" + req_path + "/outsideChainxj?param1=" + taskId + "&param2=" + patid + "&param3=" + URLEncoder.encode(ivrTask1.getTaskName(), StandardCharsets.UTF_8.toString()) + "&param5=false";
                            }
 
                            String wxCode = getWXCode(serviceSubtask.getSfzh(), url, serviceSubtask.getTaskName(), serviceSubtask.getTaskDesc(), "无");
                            Map<String, Object> map = JSONObject.parseObject(wxCode, Map.class);
                            if (!map.isEmpty()) {
                                serviceSubtask.setResult("success");
                                serviceSubtask.setSendstate(3L);
                                if ((Boolean) map.get("succ") == false) {
                                    serviceSubtask.setResult("error");
                                    serviceSubtask.setRemark(map.get("msg").toString());
                                    serviceSubtask.setSendstate(5L);
                                }
                            }
                            //任务发送记录
                            ServiceSubtaskRecord serviceSubtaskRecord = new ServiceSubtaskRecord();
                            serviceSubtaskRecord.setTaskid(serviceSubtask.getTaskid().toString());
                            serviceSubtaskRecord.setUuid(UUID.randomUUID().toString());
                            serviceSubtaskRecord.setTasktype(serviceSubtask.getType());
                            serviceSubtaskRecord.setPreachform("5");
                            serviceSubtaskRecord.setStartTime(System.currentTimeMillis());
                            serviceSubtaskRecord.setResult("success");
                            if ((Boolean) map.get("succ") == false) {
                                serviceSubtaskRecord.setResult("error");
                            }
                            serviceSubtaskMapper.insertServiceSubtask(serviceSubtask);
                            serviceSubtaskRecordService.insertServiceSubtaskRecord(serviceSubtaskRecord);
                        } catch (Exception e) {
                            String guid = UUID.randomUUID().toString();
                            log.error("公众号任务,发送失败原因:{},{}", e.getMessage(), guid);
                            serviceSubtask.setResult("error");
                            serviceSubtask.setRemark("系统错误(任务)");
                            serviceSubtask.setGuid(guid);
                            serviceSubtask.setSendstate(5L);
                            serviceSubtask.setFinishtime(new Date());
                            serviceSubtaskMapper.insertServiceSubtask(serviceSubtask);
                        }
                    }
                }
                //通知 MQ 消息已被接收,可以ACK(从队列中删除)了   (这个需要根据业务再去处理ACK)
            }
        }
    }
 
    //    /**
//     * 机器人第一句话语音
//     * concurrency = "50"  并发数为50
//     */
//    @RabbitListener(queues = "ob_queue", concurrency = "50")
//    public void obVisit(String content, Message message, Channel channel) throws IOException {
//        try {
//            IvrTaskcallPhoneMQ commonTaskcallMQ = null;
//            ObjectMapper mapper = new ObjectMapper();
//            commonTaskcallMQ = mapper.readValue(content, IvrTaskcallPhoneMQ.class);
//            //判断患者是否已经接电话
//            String str = redisCache.getCacheObject(commonTaskcallMQ.getUuid() + "state_id");
//            System.out.println("-----------------" + str);
//            if (StringUtils.isNotEmpty(str) && str.equals("0")) {
//                //患者已经接听了电话
//                new PhoneUtils().ttsPlayback(commonTaskcallMQ.getScript(), commonTaskcallMQ.getUuid());
//            } else if (StringUtils.isNotEmpty(str) && str.equals("-10")) {
//                //这个说明,已经打了指定遍数还是没有人接,可以将消息从队列中移除了
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//                return;
//            } else {
//                //进行队列尾部,进行下一次校验
////                channel.basicRecover(false);
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//                System.out.println("++++++++++++++++++++++" + str);
//                return;
//            }
//            //通知 MQ 消息已被接收,可以ACK(从队列中删除)了   (这个需要根据业务再去处理ACK)
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        } catch (Exception e) {
//            log.error("============消费失败,尝试消息补发再次消费!==============");
//            log.error(e.getMessage());
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//        }
//    }
    private String getKey() {
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < 6; i++) {
            Boolean aBoolean = redisCache.hasKey("cache-" + i);
            if (!aBoolean) {
                redisCache.setCacheObject("cache-" + i, "");
                map.put("cache-" + i, "");
            } else {
                map.put("cache-" + i, redisCache.getCacheObject("cache-" + i));
            }
        }
 
        String key = null;
        String value = "";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (StringUtils.isEmpty(value)) {
                value = entry.getValue();
                key = entry.getKey();
            } else {
                if (entry.getValue().split(",").length < value.split(",").length) {
                    value = entry.getValue();
                    key = entry.getKey();
                }
            }
        }
        return key;
    }
 
    private String getWXCode(String idcard, String url, String taskName, String taskDesc, String submitprompt) {
        XinHuaWXReq xinHuaWXReq = new XinHuaWXReq();
        xinHuaWXReq.setIdcard(idcard);
        xinHuaWXReq.setUrl(url);
        xinHuaWXReq.setKeyword1("浙中医大二院出院随访");
        xinHuaWXReq.setKeyword2(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        xinHuaWXReq.setKeyword3(taskName);
        xinHuaWXReq.setKeyword4("疾病康复注意事项");
 
        String result = HttpUtils.sendPost(thirdWXUrl, new Gson().toJson(xinHuaWXReq));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = (String) jsonObject.toString();
        return code;
    }
 
}