ny
23 小时以前 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
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
package jnpf.message.util;
 
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONObject;
import jnpf.base.SysConfigApi;
import jnpf.base.UserInfo;
import jnpf.base.entity.SysConfigEntity;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.MsgCode;
import jnpf.message.entity.*;
import jnpf.message.enums.MessageTypeEnum;
import jnpf.message.mapper.*;
import jnpf.message.model.SentMessageForm;
import jnpf.message.model.TriggerModel;
import jnpf.message.model.WxgzhMessageModel;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.util.wxutil.mp.WXGZHWebChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
 
@Component
@Slf4j
public class SendFlowMsgUtil {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SentMessageUtil sentMessageUtil;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private UserApi userApi;
    @Autowired
    private SysConfigApi sysconfigService;
 
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessagereceiveMapper messagereceiveMapper;
    @Autowired
    private MessageMonitorMapper messageMonitorMapper;
    @Autowired
    private SendMessageConfigMapper sendMessageConfigMapper;
    @Autowired
    private SendConfigTemplateMapper sendConfigTemplateMapper;
    @Autowired
    private MessageTemplateConfigMapper messageTemplateConfigMapper;
    @Autowired
    private ShortLInkMapper shortLInkMapper;
    @Autowired
    private AccountConfigMapper accountConfigMapper;
    @Autowired
    private SmsFieldMapper smsFieldMapper;
    @Autowired
    private AuthUtil authUtil;
    @Autowired
    private WechatUserMapper wechatUserMapper;
 
 
    public void sendMessage(SentMessageForm sentMessageForm) {
        List<String> toUserIdsList = sentMessageForm.getToUserIds();
        // 模板id
        String templateId = sentMessageForm.getTemplateId();
        // 参数
        Map<String, Object> parameterMap = sentMessageForm.getParameterMap();
        UserInfo userInfo = sentMessageForm.getUserInfo();
        boolean flag = true;
        if (!(toUserIdsList != null && toUserIdsList.size() > 0)) {
            log.error("接收人员为空");
            flag = false;
        }
        if (StringUtil.isEmpty(templateId)) {
            log.error("模板Id为空");
            flag = false;
        }
        if (flag) {
            // 获取发送配置详情
//            MessageTemplateEntity entity = messageTemplateService.getInfo(templateId);
            SendMessageConfigEntity entity = sendMessageConfigMapper.getInfoByEnCode(templateId);
            if (entity != null) {
                templateId = entity.getId();
            } else {
                entity = sendMessageConfigMapper.getInfo(templateId);
            }
            if (entity != null) {
                List<SendConfigTemplateEntity> list = sendConfigTemplateMapper.getDetailListByParentId(templateId);
                if (list != null && list.size() > 0) {
                    for (SendConfigTemplateEntity entity1 : list) {
                        if (parameterMap.get(entity1.getId() + "@Title") == null) {
                            parameterMap.put(entity1.getId() + "@Title", sentMessageForm.getTitle());
                        }
                        if (parameterMap.get(entity1.getId() + "@CreatorUserName") == null || StringUtil.isEmpty(String.valueOf(parameterMap.get(entity1.getId() + "@CreatorUserName")))) {
                            parameterMap.put(entity1.getId() + "@CreatorUserName", sentMessageForm.getUserInfo().getUserName());
                        }
                        if (parameterMap.get(entity1.getId() + "@SendTime") == null || StringUtil.isEmpty(String.valueOf(parameterMap.get(entity1.getId() + "@SendTime")))) {
                            parameterMap.put(entity1.getId() + "@SendTime", DateUtil.getNow().substring(11));
                        }
                        if (parameterMap.get(entity1.getId() + "@FlowLink") == null) {
                            parameterMap.put(entity1.getId() + "@FlowLink", "");
                        }
                        if ("1".equals(String.valueOf(entity1.getEnabledMark()))) {
                            String sendType = entity1.getMessageType();
                            MessageTypeEnum typeEnum = MessageTypeEnum.getByCode(sendType);
                            Map<String, String> contentMsg = sentMessageForm.getContentMsg();
                            switch (typeEnum) {
                                case SysMessage:
                                    // 站内消息、
                                    for (String toUserId : toUserIdsList) {
                                        List<String> toUser = new ArrayList<>();
                                        String content = sentMessageForm.getContent();
                                        MessageTemplateConfigEntity templateConfigEntity = messageTemplateConfigMapper.getInfo(entity1.getTemplateId());
                                        String title = sentMessageForm.getTitle();
                                        String appLink = "";
                                        if (templateConfigEntity != null) {
                                            title = templateConfigEntity.getTitle();
                                            String msg = contentMsg.get(toUserId) != null ? contentMsg.get(toUserId) : "{}";
                                            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
                                            String encode = Base64.getEncoder().encodeToString(bytes);
                                            //流程审批页面链接地址
                                            //流程审批页面链接地址
                                            String pcLink = "/workFlowDetail?config=" + encode;
                                            appLink = "/pages/workFlow/flowBefore/index?config=" + encode;
                                            //转换为短链
                                            String shortLink = shortLInkMapper.shortLink(pcLink + toUserId + templateConfigEntity.getMessageType());
                                            shortLink = shortLInkMapper.shortLink(pcLink + toUserId + templateConfigEntity.getMessageType());
                                            String link = configValueUtil.getApiDomain() + "/api/message/ShortLink/" + shortLink;
                                            if (StringUtil.isNotBlank(userInfo.getTenantId())) {
                                                link = link + "/" + userInfo.getTenantId();
                                            }
                                            if (title.contains("{@FlowLink}")) {
                                                title = title.replace("{@FlowLink}", link + " ");
                                                //链接数据保存
                                                sentMessageUtil.saveShortLink(pcLink, appLink, shortLink, userInfo, toUserId, msg);
                                            }
                                            Map<String, Object> msgMap = new HashMap<>();
                                            msgMap = sentMessageUtil.getParamMap(entity1.getId(), parameterMap);
                                            if (StringUtil.isNotEmpty(title)) {
                                                StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                                                title = strSubstitutor.replace(title);
                                            }
                                        }
                                        toUser.add(toUserId);
                                        messagereceiveMapper.sentMessage(toUser, title, content, contentMsg, userInfo);
                                        //消息监控写入
                                        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
                                        monitorEntity.setId(RandomUtil.uuId());
                                        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUser));
                                        monitorEntity.setSendTime(DateUtil.getNowDate());
                                        monitorEntity.setCreatorTime(DateUtil.getNowDate());
                                        monitorEntity.setCreatorUserId(userInfo.getUserId());
                                        sentMessageUtil.createMessageMonitor(monitorEntity, templateConfigEntity, null, null, userInfo, toUser, title);
                                        messageMonitorMapper.insert(monitorEntity);
                                    }
                                    String url = configValueUtil.getApiDomain() + "/api/workflow/trigger/MsgExecute";
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("id", entity1.getTemplateId());
                                    map.put("userInfo", userInfo);
                                    HttpRequest request = HttpRequest.of(url).method(Method.POST).body(JsonUtil.getObjectToString(map));
                                    request.header(Constants.AUTHORIZATION, userInfo.getToken());
                                    request.execute().body();
                                    break;
                                case SmsMessage:
                                    // 发送短信
                                    sentMessageUtil.sendSms(toUserIdsList, userInfo, entity1, parameterMap, contentMsg);
                                    break;
                                case MailMessage:
                                    // 邮件
                                    sentMessageUtil.SendMail(toUserIdsList, userInfo, sendType, entity1, parameterMap, contentMsg);
                                    break;
                                case QyMessage:
                                    // 企业微信
                                    JSONObject jsonObject = sentMessageUtil.SendQyWebChat(toUserIdsList, userInfo, sendType, entity1, parameterMap, contentMsg);
                                    if (!(Boolean) jsonObject.get("code")) {
                                        log.error("发送企业微信消息失败,错误:" + jsonObject.get("error"));
                                    }
                                    break;
                                case DingMessage:
                                    // 钉钉
                                    JSONObject jsonObject1 = sentMessageUtil.SendDingTalk(toUserIdsList, userInfo, sendType, entity1, parameterMap, contentMsg);
                                    if (!(Boolean) jsonObject1.get("code")) {
                                        log.error("发送企业微信消息失败,错误:" + jsonObject1.get("error"));
                                    }
                                    break;
                                case WebHookMessage:
                                    // webhook
                                    this.SendWebHook(sendType, userInfo, entity1, parameterMap, new HashMap<>());
                                    break;
                                case WechatMessage:
                                    // 微信公众号
                                    this.SendWXGzhChat(toUserIdsList, userInfo, sendType, entity1, contentMsg, parameterMap);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
 
    public List<String> sendScheduleMessage(SentMessageForm sentMessageForm) {
        List<String> errList = new ArrayList<>();
        UserInfo userInfo = sentMessageForm.getUserInfo();
        String templateId = sentMessageForm.getTemplateId();
        String title = sentMessageForm.getTitle();
        List<String> toUserIds = sentMessageForm.getToUserIds();
        //获取发送配置详情
        SendMessageConfigEntity configEntity = sendMessageConfigMapper.getInfoByEnCode(templateId);
        if (configEntity != null) {
            templateId = configEntity.getId();
        } else {
            configEntity = sendMessageConfigMapper.getInfo(templateId);
        }
        List<SendConfigTemplateEntity> list = sendConfigTemplateMapper.getDetailListByParentId(templateId);
        if (configEntity != null) {
            for (SendConfigTemplateEntity sendConfigTemplateEntity : list) {
                Map<String, Object> objectMap = new HashMap<>(sentMessageForm.getParameterMap());
                Map<String, Object> parameterMap = new HashMap<>();
                for (String key : objectMap.keySet()) {
                    if (key.contains(sendConfigTemplateEntity.getId())) {
                        parameterMap.put(key.substring(sendConfigTemplateEntity.getId().length()), objectMap.get(key));
                    }
                }
                parameterMap.putAll(objectMap);
                Map<String, String> contentMsg = new HashMap<>();
                for (String key : parameterMap.keySet()) {
                    contentMsg.put(key, String.valueOf(parameterMap.get(key)));
                }
                String sendType = sendConfigTemplateEntity.getMessageType();
                switch (sendType) {
                    case "1":
                        MessageTemplateConfigEntity templateConfigEntity = messageTemplateConfigMapper.getInfo(sendConfigTemplateEntity.getTemplateId());
                        String messageTitle = StringUtil.isNotEmpty(templateConfigEntity.getTitle()) ? templateConfigEntity.getTitle() : "";
                        String content = StringUtil.isNotEmpty(templateConfigEntity.getContent()) ? templateConfigEntity.getContent() : "";
                        StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                        messageTitle = strSubstitutor.replace(messageTitle);
                        content = strSubstitutor.replace(content);
                        sentMessageForm.setTitle(messageTitle);
                        sentMessageForm.setContent(content);
                        // 站内消息
                        message(sentMessageForm);
                        // 通知触发
                        try {
                            String url = configValueUtil.getApiDomain() + "/api/workflow/trigger/MsgExecute";
                            TriggerModel model = new TriggerModel();
                            model.setUserInfo(userInfo);
                            model.setId(templateConfigEntity.getId());
                            HttpRequest request = HttpRequest.of(url).method(Method.POST).body(JsonUtil.getObjectToString(model));
                            request.header(Constants.AUTHORIZATION, userInfo.getToken());
                            request.execute().body();
                        } catch (Exception e) {
                            log.error("消息触发流程报错信息:" + e.getMessage());
                        }
                        break;
                    case "2":
                        // 邮件
                        List<String> mailErrs = sentMessageUtil.SendMail(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        errList.addAll(mailErrs.stream().distinct().collect(Collectors.toList()));
                        break;
                    case "3":
                        // 发送短信
                        List<String> smsErrs = sentMessageUtil.sendSms(toUserIds, userInfo, sendConfigTemplateEntity, parameterMap, new HashMap<>());
                        errList.addAll(smsErrs.stream().distinct().collect(Collectors.toList()));
                        break;
                    case "4":
                        // 钉钉
                        JSONObject jsonObject1 = sentMessageUtil.SendDingTalk(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        if (!(Boolean) jsonObject1.get("code")) {
                            log.error("发送企业微信消息失败,错误:" + jsonObject1.get("error"));
                            errList.add("发送钉钉消息失败,错误:" + jsonObject1.get("error"));
                        }
                        break;
                    case "5":
                        // 企业微信
                        JSONObject jsonObject = sentMessageUtil.SendQyWebChat(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        if (!(Boolean) jsonObject.get("code")) {
                            log.error("发送企业微信消息失败,错误:" + jsonObject.get("error"));
                            errList.add("发送企业微信消息失败,错误:" + jsonObject.get("error"));
                        }
                        break;
                    case "6":
                        // webhook
                        this.SendWebHook(sendType, userInfo, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        break;
                    case "7":
                        // 微信公众号
                        JSONObject jsonObject2 = this.SendWXGzhChat(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), parameterMap);
                        if (!(Boolean) jsonObject2.get("code")) {
                            errList.add("发送微信公众号消息失败,错误:" + jsonObject2.get("error"));
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        return errList;
    }
 
    public void SendWebHook(String sendType, UserInfo userInfo, SendConfigTemplateEntity entity, Map<String, Object> parameterMap, Map<String, String> contentMsg) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigMapper.getInfo(entity.getTemplateId());
        AccountConfigEntity accountEntity = accountConfigMapper.getInfo(entity.getAccountConfigId());
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        String content = msgTemEntity.getContent();
        //获取消息模板参数
        parameterMap = SentMessageUtil.getParamMap(entity.getId(), parameterMap);
        // 替换参数
        if (StringUtil.isNotEmpty(content)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            content = strSubstitutor.replace(content);
        }
        String title = msgTemEntity.getTitle();
        if (StringUtil.isNotEmpty(title)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            title = strSubstitutor.replace(title);
        }
        title = SentMessageUtil.systemParam(parameterMap, contentMsg, title, userInfo);
        content = SentMessageUtil.systemParam(parameterMap, contentMsg, content, userInfo);
        if (entity != null) {
            if (accountEntity != null) {
                //创建消息监控
                monitorEntity = SentMessageUtil.createMessageMonitor(monitorEntity, msgTemEntity, accountEntity, content, userInfo, null, title);
                messageMonitorMapper.create(monitorEntity);
                switch (accountEntity.getWebhookType()) {
                    case 1:
                        //钉钉
                        if (Objects.equals(1, accountEntity.getApproveType())) {
                            WebHookUtil.sendDDMessage(accountEntity.getWebhookAddress(), content);
                        } else if (Objects.equals(2, accountEntity.getApproveType())) {
                            WebHookUtil.sendDingDing(accountEntity.getWebhookAddress(), accountEntity.getBearer(), content);
                        }
                        break;
                    case 2:
                        if (Objects.equals(1, accountEntity.getApproveType())) {
                            WebHookUtil.callWeChatBot(accountEntity.getWebhookAddress(), content);
                        }
                        break;
                    default:
                        break;
                }
            } else {
                monitorEntity = SentMessageUtil.createMessageMonitor(monitorEntity, msgTemEntity, null, content, userInfo, null, title);
                messageMonitorMapper.create(monitorEntity);
            }
        } else {
            monitorEntity = SentMessageUtil.createMessageMonitor(monitorEntity, msgTemEntity, null, content, userInfo, null, title);
            messageMonitorMapper.create(monitorEntity);
        }
    }
 
    public JSONObject SendWXGzhChat(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, String> contentMsg, Map<String, Object> parameterMap) {
        //获取短信配置
        AccountConfigEntity accountEntity = accountConfigMapper.getInfo(entity.getAccountConfigId());
        // 获取消息模板详情
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigMapper.getInfo(entity.getTemplateId());
        //消息监控
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
        for (String userId : toUserIdsList) {
            MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
            monitorEntity.setId(RandomUtil.uuId());
            monitorEntity.setSendTime(DateUtil.getNowDate());
            monitorEntity.setCreatorTime(DateUtil.getNowDate());
            monitorEntity.setCreatorUserId(userInfo.getUserId());
            error = new StringBuilder();
            if (StringUtil.isEmpty(userId)) {
                code = false;
                error = error.append(";").append("接收人为空!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            UserEntity userEntity = userApi.getInfoById(userId);
            if (ObjectUtil.isEmpty(userEntity)) {
                code = false;
                error = error.append(";").append("用户不存在!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            monitorEntity.setReceiveUser(userId);
 
            if (ObjectUtil.isEmpty(msgTemEntity)) {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":消息模板数据不存在!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            monitorEntity.setMessageTemplateId(msgTemEntity.getId());
            String content = msgTemEntity.getContent();
            String templateKId = msgTemEntity.getTemplateCode();
            if (ObjectUtil.isEmpty(accountEntity)) {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":公众号账号配置数据不存在!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            monitorEntity.setAccountId(accountEntity.getId());
            //创建消息监控
            monitorEntity = SentMessageUtil.createMessageMonitor(monitorEntity, msgTemEntity, accountEntity, content, userInfo, toUserIdsList, null);
            // 获取系统配置
            String appId = accountEntity.getAppId();
            String appsecret = accountEntity.getAppSecret();
            String wxxcxAppId = msgTemEntity.getXcxAppId();
            String type = msgTemEntity.getWxSkip();
 
            String title = "";
            //获取消息模板参数
            Map<String, Object> msgMap = SentMessageUtil.getParamMap(entity.getId(), parameterMap);
//            if(parameterMap.containsKey("@flowLink")){
//                parameterMap.put("@flowLink",link);
//            }
            //微信公众号参数
            Map<String, Object> smsMap = new HashMap<>();
            if (entity != null) {
                smsMap = smsFieldMapper.getParamMap(entity.getTemplateId(), msgMap);
            }
            if (smsMap.containsKey("title")) {
                title = smsMap.get("title").toString();
                smsMap.keySet().removeIf(k -> k.equals("title"));
            }
            monitorEntity.setTitle(title);
            // 相关参数验证
            if (StringUtil.isEmpty(templateKId)) {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":微信公众号模板id未创建!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            if (StringUtil.isEmpty(appId)) {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":公众号appid为空为空!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            if (StringUtil.isEmpty(appsecret)) {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":公众号appsecret为空为空!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            // 获取微信公众号的token
            String token = WXGZHWebChatUtil.getAccessToken(appId, appsecret);
            if (StringUtil.isEmpty(token)) {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":获取微信公众号token失败!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            // 微信公众号发送消息
            String msg = contentMsg.get(userId) != null ? contentMsg.get(userId) : "{}";
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            String encode = Base64.getEncoder().encodeToString(bytes);
            //流程审批页面链接地址
            String pcLink = "/workFlowDetail?config=" + encode;
            String appLink = "/pages/workFlow/flowBefore/index?config=" + encode;
            //转换为短链
            String shortLink = shortLInkMapper.shortLink(pcLink + userId + msgTemEntity.getMessageType());
            shortLink = getShortLink(pcLink, userId, shortLink, msgTemEntity.getMessageType());
            if (!"1".equals(type)) {
                //链接数据保存
                this.saveShortLink(pcLink, appLink, shortLink, userInfo, userId, msg);
            }
            String link = configValueUtil.getApiDomain() + "/api/message/ShortLink/" + shortLink;
            if (StringUtil.isNotBlank(userInfo.getTenantId())) {
                link = link + "/" + userInfo.getTenantId();
            }
            if (ObjectUtil.isNotEmpty(smsMap)) {
                for (String key : smsMap.keySet()) {
                    if (smsMap.get(key).equals("@FlowLink")) {
                        smsMap.put(key, link);
                    }
                }
            } else {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":公众号模板参数为空!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            WechatUserEntity wechatUserEntity = wechatUserMapper.getInfoByGzhId(userId, accountEntity.getAppKey());
            if (wechatUserEntity != null) {
                if (StringUtil.isNotBlank(wechatUserEntity.getOpenId())) {
                    String openid = wechatUserEntity.getOpenId();
                    String apptoken = authUtil.loginTempUser(userId, userInfo.getTenantId());
                    String pagepath = "/pages/workFlow/flowBefore/index?config=" + encode + "&token=" + apptoken;
                    if (ObjectUtil.isNotEmpty(smsMap)) {
                        //参数封装
                        String message = WXGZHWebChatUtil.messageJson(templateKId, openid, wxxcxAppId, pagepath, smsMap, title, type, link);
                        //发送信息
                        retJson = WXGZHWebChatUtil.sendMessage(token, message);
                    }
                    JSONObject rstObj = WXGZHWebChatUtil.getMessageList(token);
                    List<WxgzhMessageModel> wxgzhMessageModelList = JsonUtil.getJsonToList(rstObj.get("template_list"), WxgzhMessageModel.class);
                    WxgzhMessageModel messageModel = wxgzhMessageModelList.stream().filter(t -> t.getTemplateId().equals(templateKId)).findFirst().orElse(null);
                    if (ObjectUtil.isNotEmpty(messageModel)) {
                        content = messageModel.getContent();
                        if (StringUtil.isNotBlank(content) && !"null".equals(content)) {
                            if (ObjectUtil.isNotEmpty(smsMap) && !"null".equals(smsMap)) {
                                if (content.contains(".DATA}")) {
                                    for (String key : smsMap.keySet()) {
                                        content = content.replace(key, smsMap.get(key).toString());
                                    }
                                }
                            }
                        }
                    }
                    if (!retJson.getBoolean("code")) {
                        code = false;
                        error = error.append(";").append(userEntity.getRealName() + ":" + retJson.get("error"));
                        messageMonitorMapper.create(monitorEntity);
                        continue;
                    }
                    messageMonitorMapper.create(monitorEntity);
                    continue;
 
                } else {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":" + "账号未绑定公众号");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
            } else {
                code = false;
                error = error.append(";").append(userEntity.getRealName() + ":" + "账号未绑定公众号");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
        }
        if (code) {
            retJson.put("code", true);
            retJson.put("error", MsgCode.SU012.get());
        } else {
            String msg = error.toString();
            if (StringUtil.isNotBlank(msg)) {
                msg = msg.substring(1);
            }
            retJson.put("code", false);
            retJson.put("error", msg);
        }
        return retJson;
    }
 
    public boolean sentNotice(List<String> toUserIds, MessageEntity entity) {
        // 存到redis中的key对象
        UserInfo userInfo = UserProvider.getUser();
        List<String> idList = new ArrayList<>();
        // 修改发送状态
        entity.setEnabledMark(1);
        entity.setLastModifyTime(new Date());
        entity.setLastModifyUserId(userInfo.getUserId());
        messageMapper.updateById(entity);
        // 存到redis,生成Redis的key
        Callable executeInsert = () -> {
            executeInsert(toUserIds, idList);
            return true;
        };
        Future<Boolean> submit = ThreadPoolExecutorUtil.getExecutor().submit(executeInsert);
        try {
            if (submit.get()) {
                // 执行发送公告操作
                Runnable runnable = () -> executeBatch(idList, entity, userInfo);
                ThreadPoolExecutorUtil.getExecutor().submit(runnable);
            }
            return true;
        } catch (Exception e) {
            // 还原公告状态
            entity.setEnabledMark(0);
            entity.setLastModifyTime(null);
            entity.setLastModifyUserId(null);
            messageMapper.updateById(entity);
        }
        return false;
    }
 
    private void executeBatch(List<String> idList, MessageEntity entity, UserInfo userInfo) {
        if (idList.size() == 0 || "3".equals(String.valueOf(entity.getRemindCategory()))) {
            return;
        }
        SentMessageForm sentMessageForm = new SentMessageForm();
        List<String> toUserId = new ArrayList<>();
        for (String cacheKey : idList) {
            List<String> cacheValue = (List) redisUtil.get(cacheKey, 0, -1);
            toUserId.addAll(cacheValue);
        }
        sentMessageForm.setToUserIds(toUserId);
        sentMessageForm.setTitle(entity.getTitle());
        sentMessageForm.setContent(entity.getBodyText());
        sentMessageForm.setContentMsg(Collections.EMPTY_MAP);
        sentMessageForm.setUserInfo(userInfo);
        sentMessageForm.setType(1);
        sentMessageForm.setId(entity.getId());
 
        // 站内信
        if ("1".equals(String.valueOf(entity.getRemindCategory()))) {
            message(sentMessageForm);
        } else if ("2".equals(String.valueOf(entity.getRemindCategory()))) {
            SendMessageConfigEntity sendMessageConfigEntity = sendMessageConfigMapper.getInfo(entity.getSendConfigId());
            if (sendMessageConfigEntity != null) {
                List<SendConfigTemplateEntity> configTemplateEntityList = sendConfigTemplateMapper.getDetailListByParentId(sendMessageConfigEntity.getId());
                for (SendConfigTemplateEntity sendConfigTemplateEntity : configTemplateEntityList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("Title", entity.getTitle());
                    map.put("Content", entity.getBodyText());
                    map.put("Remark", entity.getExcerpt());
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("@Title", entity.getTitle());
                    paramMap.put("@Content", entity.getBodyText());
                    paramMap.put("@Remark", entity.getExcerpt());
                    paramMap.put("@CreatorUserName", userInfo.getUserName());
                    paramMap.put("@SendTime",  DateUtil.getNow().substring(11));
                    paramMap.put(sendConfigTemplateEntity.getId()+"@Title", entity.getTitle());
                    paramMap.put(sendConfigTemplateEntity.getId()+"@Content", entity.getBodyText());
                    paramMap.put(sendConfigTemplateEntity.getId()+"@Remark", entity.getExcerpt());
                    paramMap.put(sendConfigTemplateEntity.getId()+"@CreatorUserName", userInfo.getUserName());
                    paramMap.put(sendConfigTemplateEntity.getId()+"@SendTime",  DateUtil.getNow().substring(11));
                    switch (sendConfigTemplateEntity.getMessageType()) {
                        case "1":
                            MessageTemplateConfigEntity configEntity = messageTemplateConfigMapper.getInfo(sendConfigTemplateEntity.getTemplateId());
                            if (configEntity != null) {
                                sentMessageForm.setTitle(configEntity.getTitle());
                            }
                            message(sentMessageForm);
                            break;
                        case "2":
                            // 邮件
                            sentMessageUtil.SendMail(toUserId, userInfo, "2", sendConfigTemplateEntity, new HashMap<>(), map);
                            break;
                        case "3":
                            // 发送短信
                            sentMessageUtil.sendSms(toUserId, userInfo, sendConfigTemplateEntity, paramMap, new HashMap<>());
                            break;
                        case "4":
                            // 钉钉
                            JSONObject jsonObject1 = sentMessageUtil.SendDingTalk(toUserId, userInfo, "4", sendConfigTemplateEntity, new HashMap<>(), map);
                            if (!(Boolean) jsonObject1.get("code")) {
                                log.error("发送企业微信消息失败,错误:" + jsonObject1.get("error"));
                            }
                            break;
                        case "5":
                            // 企业微信
                            JSONObject jsonObject = sentMessageUtil.SendQyWebChat(toUserId, userInfo, "5", sendConfigTemplateEntity, new HashMap<>(), map);
                            if (!(Boolean) jsonObject.get("code")) {
                                log.error("发送企业微信消息失败,错误:" + jsonObject.get("error"));
                            }
                            break;
                        case "6":
                            // webhook
                            this.SendWebHook(null, userInfo, sendConfigTemplateEntity, new HashMap<>(), map);
                            break;
                        case "7":
                            // 微信公众号
                            this.SendWXGzhChat(toUserId, userInfo, "7", sendConfigTemplateEntity, new HashMap<>(), paramMap);
                            break;
                        default:
                            break;
                    }
                }
 
            }
        }
    }
 
    private void message(SentMessageForm sentMessageForm) {
        List<String> toUserIds = sentMessageForm.getToUserIds();
        Integer type = sentMessageForm.getType();
        String title = sentMessageForm.getTitle();
        String content = sentMessageForm.getContent();
        String bodyText = Objects.equals(type, 3) ? content : JsonUtil.getObjectToString(sentMessageForm.getContentMsg());
        UserInfo userInfo = sentMessageForm.getUserInfo();
        MessageReceiveEntity messageReceiveEntity = new MessageReceiveEntity();
        messageReceiveEntity.setIsRead(0);
        messageReceiveEntity.setId(RandomUtil.uuId());
        messageReceiveEntity.setType(sentMessageForm.getType());
        if (type != null) {
            messageReceiveEntity.setId(sentMessageForm.getId());
            messageReceiveEntity.setType(type);
            messageReceiveEntity.setCreatorUserId(userInfo.getUserId());
            messageReceiveEntity.setCreatorTime(DateUtil.getNowDate());
        }
        //消息监控写入
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        MessageEntity messageEntity = messageMapper.getInfo(sentMessageForm.getId());
        if (!"1".equals(String.valueOf(messageReceiveEntity.getType()))) {
            monitorEntity.setMessageSource(sentMessageForm.getType() + "");
            messageReceiveEntity.setFlowType(sentMessageForm.getFlowType());
            monitorEntity.setTitle(title);
        } else {
            monitorEntity.setMessageSource("1");
            title = title.replaceAll("\\{@Title}", messageEntity.getTitle())
                    .replaceAll("\\{@CreatorUserName}", userInfo.getUserName())
                    .replaceAll("\\{@SendTime}", DateUtil.getNow().substring(11))
                    .replaceAll("\\{@Content}", messageEntity.getBodyText())
                    .replaceAll("\\{@Remark}", StringUtil.isNotEmpty(messageEntity.getExcerpt()) ? messageEntity.getExcerpt() : "");
            monitorEntity.setTitle(title);
 
            MessageEntity messageEntity2 = new MessageEntity();
            messageEntity2.setId(messageEntity.getId());
            bodyText = JsonUtil.getObjectToString(messageEntity2);
        }
        Map<String, MessageReceiveEntity> map = new HashMap<>();
        for (String item : toUserIds) {
            MessageReceiveEntity messageReceiveEntitys = new MessageReceiveEntity();
            BeanUtils.copyProperties(messageReceiveEntity, messageReceiveEntitys);
            messageReceiveEntitys.setId(RandomUtil.uuId());
            messageReceiveEntitys.setUserId(item);
            messageReceiveEntitys.setTitle(title);
//            if(ObjectUtil.isNotEmpty(messageEntity)) {
//                messageReceiveEntitys.setTitle(title.replaceAll("\\{@Title}", messageEntity.getTitle())
//                        .replaceAll("\\{@CreatorUserName}", userInfo.getUserName())
//                        .replaceAll("\\{@Content}", messageEntity.getBodyText())
//                        .replaceAll("\\{@Remark}", StringUtil.isNotEmpty(messageEntity.getExcerpt()) ? messageEntity.getExcerpt() : ""));
//            }
            messageReceiveEntitys.setBodyText(bodyText);
            messagereceiveMapper.insert(messageReceiveEntitys);
            map.put(messageReceiveEntitys.getUserId(), messageReceiveEntitys);
        }
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setMessageType("1");
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIds));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        monitorEntity.setContent(content);
        messageMonitorMapper.insert(monitorEntity);
        //消息推送 - PC端
        PushMessageUtil.pushMessage(map, userInfo, type != null ? type : 2);
    }
 
 
    /**
     * 数据存到redis中
     *
     * @param toUserIds 接受者id
     */
    private void executeInsert(List<String> toUserIds, List<String> idList) throws Exception {
        List<String> key = new ArrayList<>();
        try {
            int frequency = 10000;
            int count = toUserIds.size() / frequency + 1;
            if (toUserIds.size() < 1) return;
            for (int i = 0; i < count; i++) {
                // 生成redis的key
                String cacheKey = RandomUtil.uuId() + toUserIds.get(i);
                // 存到redis
                int endSize = Math.min(((i + 1) * frequency), toUserIds.size());
                redisUtil.insert(cacheKey, toUserIds.subList(i * frequency, endSize));
                key.add(cacheKey);
            }
        } catch (Exception e) {
            key.forEach(k -> redisUtil.remove(k));
            key.clear();
            throw new Exception();
        }
        idList.addAll(key);
    }
 
    public void saveShortLink(String pcLink, String appLink, String shortLink, UserInfo userInfo, String userId, String bodyText) {
        ShortLinkEntity shortLinkEntity = shortLInkMapper.getInfoByLink(shortLink);
        if (shortLinkEntity == null) {
            ShortLinkEntity entity = new ShortLinkEntity();
            Map<String, String> sysConfig = getSystemConfig();
            String linkTime = sysConfig.get("linkTime");
            Integer isClick = 0;
            if (StringUtil.isNotBlank(sysConfig.get("isClick")) && !"null".equals(sysConfig.get("isClick"))) {
                isClick = Integer.parseInt(sysConfig.get("isClick"));
            }
            int unClickNum = 20;
            if (StringUtil.isNotBlank(sysConfig.get("unClickNum")) && !"null".equals(sysConfig.get("unClickNum"))) {
                unClickNum = Integer.parseInt(sysConfig.get("unClickNum"));
            }
            entity.setId(RandomUtil.uuId());
            entity.setRealPcLink(pcLink);
            entity.setRealAppLink(appLink);
            entity.setShortLink(shortLink);
            entity.setBodyText(bodyText);
//            entity.setTenantId(userInfo.getTenantId());
            entity.setUserId(userId);
            entity.setIsUsed(isClick);
            entity.setUnableNum(unClickNum);
            entity.setClickNum(0);
            if (StringUtil.isNotEmpty(linkTime)) {
                Date unableTime = SentMessageUtil.getUnableTime(linkTime);
                entity.setUnableTime(unableTime);
            } else {
                entity.setUnableTime(DateUtil.dateAddHours(DateUtil.getNowDate(), 24));
            }
            entity.setCreatorTime(DateUtil.getNowDate());
            entity.setCreatorUserId(userInfo.getUserId());
            shortLInkMapper.insert(entity);
        }
    }
 
    private Map<String, String> getSystemConfig() {
        // 获取系统配置
        List<SysConfigEntity> configList = sysconfigService.getList("SysConfig");
        Map<String, String> objModel = new HashMap<>(16);
        for (SysConfigEntity entity : configList) {
            objModel.put(entity.getFkey(), entity.getValue());
        }
        return objModel;
    }
 
    private String getShortLink(String pcLink, String userId, String shortLink, String type) {
        if (StringUtil.isNotBlank(shortLink)) {
            ShortLinkEntity entity = shortLInkMapper.getInfoByLink(shortLink);
            if (entity != null) {
                if (pcLink.equals(entity.getRealPcLink())) {
                    return shortLink;
                } else {
                    shortLink = shortLInkMapper.shortLink(pcLink + userId + type);
                    return getShortLink(pcLink, userId, shortLink, type);
                }
            } else {
                return shortLink;
            }
        } else {
            shortLink = shortLInkMapper.shortLink(pcLink + userId + type);
            return getShortLink(pcLink, userId, shortLink, type);
        }
    }
}