刘光辉
12 小时以前 34981c30a78e8bbd7791131059a9210f9928b62c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
package jnpf.message.util;
 
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import jnpf.base.SmsModel;
import jnpf.base.SynThirdInfoApi;
import jnpf.base.SysConfigApi;
import jnpf.base.UserInfo;
import jnpf.base.entity.SynThirdInfoEntity;
import jnpf.base.entity.SysConfigEntity;
import jnpf.constant.KeyConst;
import jnpf.constant.MsgCode;
import jnpf.constant.MsgSysParam;
import jnpf.exception.DataException;
import jnpf.message.entity.*;
import jnpf.message.enums.MessageTypeEnum;
import jnpf.message.model.EmailModel;
import jnpf.message.model.WxgzhMessageModel;
import jnpf.message.model.messagetemplateconfig.TemplateParamModel;
import jnpf.message.model.sendmessageconfig.SendConfigTemplateModel;
import jnpf.message.service.*;
import jnpf.model.SocialsSysConfig;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.util.message.SmsUtil;
import jnpf.util.third.DingTalkUtil;
import jnpf.util.third.QyWebChatUtil;
import jnpf.util.wxutil.mp.WXGZHWebChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.stereotype.Component;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
 
@Slf4j
@Component
@RequiredArgsConstructor
public class TestSendConfigUtil {
 
    private final UserApi userService;
    private final SysConfigApi sysconfigService;
    private final MessageService messageService;
    private final SynThirdInfoApi synThirdInfoApi;
    private final MessageTemplateConfigService messageTemplateConfigService;
    private final SmsFieldService smsFieldService;
    private final AccountConfigService accountConfigService;
    private final MessageMonitorService messageMonitorService;
    private final WechatUserService wechatUserService;
 
    private static final String MSG_NO_USER = "接收人为空!";
    private static final String ERRCODE = "errcode";
    private static final String ERRMSG = "errmsg";
 
    /**
     * 测试发送配置
     */
    public String sendMessage(SendConfigTemplateModel model, UserInfo userInfo) {
        // 获取消息模板详情
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        List<String> toUserIdsList = model.getToUser();
        if (msgTemEntity == null || toUserIdsList == null) {
            throw new DataException("消息模板数据不存在!");
        }
        // 参数
        Map<String, Object> parameterMap = new HashMap<>();
        List<TemplateParamModel> paramModelList = JsonUtil.getJsonToList(model.getParamJson(), TemplateParamModel.class);
        if (paramModelList != null && !paramModelList.isEmpty()) {
            for (TemplateParamModel paramModel : paramModelList) {
                parameterMap.put(paramModel.getField(), paramModel.getValue());
            }
        }
        // 替换参数
        String content = msgTemEntity.getContent();
        if ("5".equals(msgTemEntity.getMessageSource()) && "1".equals(msgTemEntity.getMessageType())) {
            Map<String, Object> map = new HashMap<>();
            map.put("formDataId", parameterMap.get(MsgSysParam.FORM_DATA_ID));
            map.put("formTemplateId", parameterMap.get(MsgSysParam.FORM_TEMPLATE_ID));
            content = JsonUtil.getObjectToString(map);
        }
        // 替换参数
        if (StringUtil.isNotEmpty(content)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            content = strSubstitutor.replace(content);
        }
        if ("6".equals(msgTemEntity.getMessageSource())) {
            String menuUrl = msgTemEntity.getMenuUrl();
            if (StringUtil.isNotEmpty(menuUrl)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                menuUrl = strSubstitutor.replace(menuUrl);
            }
            content = MenuMessageUtil.toJson(menuUrl, content);
        }
        MessageTypeEnum typeEnum = MessageTypeEnum.getByCode(msgTemEntity.getMessageType());
        String sendType = msgTemEntity.getMessageType();
        switch (typeEnum) {
            case SYS_MESSAGE:
                // 站内消息
                String title = msgTemEntity.getTitle();
                if (StringUtil.isNotEmpty(title)) {
                    StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                    title = strSubstitutor.replace(title);
                }
 
                Integer source = Integer.parseInt(msgTemEntity.getMessageSource());
                Integer type = Integer.parseInt(msgTemEntity.getMessageType());
                messageService.sentMessage(toUserIdsList, title, content, userInfo, source, type, true);
                break;
            case SMS_MESSAGE:
                // 发送短信
                JSONObject jsonObject1 = sendSms(toUserIdsList, model, parameterMap);
                if (!jsonObject1.getBooleanValue(KeyConst.CODE)) {
                    return "发送短信消息失败,错误:" + jsonObject1.get(KeyConst.ERROR);
                }
                break;
            case MAIL_MESSAGE:
                // 邮件
                JSONObject jsonObject2 = sendMail(toUserIdsList, userInfo, sendType, model, parameterMap);
                if (!jsonObject2.getBooleanValue(KeyConst.CODE)) {
                    return "发送邮件消息失败,错误:" + jsonObject2.get(KeyConst.ERROR);
                }
                break;
            case QY_MESSAGE:
                // 企业微信
                JSONObject jsonObject3 = sendQyWebChat(toUserIdsList, userInfo, sendType, model, parameterMap);
                if (!jsonObject3.getBooleanValue(KeyConst.CODE)) {
                    return "发送企业微信消息失败,错误:" + jsonObject3.get(KeyConst.ERROR);
                }
                break;
            case DING_MESSAGE:
                // 钉钉
                JSONObject jsonObject4 = sendDingTalk(toUserIdsList, userInfo, sendType, model, parameterMap);
                if (!jsonObject4.getBooleanValue(KeyConst.CODE)) {
                    return "发送钉钉消息失败,错误:" + jsonObject4.get(KeyConst.ERROR);
                }
                break;
            case WEB_HOOK_MESSAGE:
                // webhook
                JSONObject jsonObject5 = sendWebHook(sendType, userInfo, model, parameterMap);
                if (!jsonObject5.getBooleanValue(KeyConst.CODE)) {
                    return "发送webhook消息失败,错误:" + jsonObject5.get(KeyConst.ERROR);
                }
                break;
            case WECHAT_MESSAGE:
                // 微信公众号
                JSONObject jsonObject6 = sendWXGzhChat(toUserIdsList, userInfo, sendType, model, parameterMap);
                if (!jsonObject6.getBooleanValue(KeyConst.CODE)) {
                    return "发送微信公众号消息失败,错误:" + jsonObject6.get(KeyConst.ERROR);
                }
                break;
            default:
                break;
        }
        return null;
    }
 
    private JSONObject sendWebHook(String sendType, UserInfo userInfo, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        if (msgTemEntity == null) {
            log.info(sendType);
            throw new DataException("消息模板数据不存在!");
        }
        String content = msgTemEntity.getContent();
        JSONObject retJson = new JSONObject();
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
 
        // 替换参数
        if (StringUtil.isNotEmpty(content)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            content = strSubstitutor.replace(content);
        }
        AccountConfigEntity accountEntity = accountConfigService.getInfo(model.getAccountConfigId());
        if (accountEntity == null) {
            throw new DataException("webhook账号地址配置错误配置数据不存在!");
        }
        //消息监控-消息模板写入
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
        String title = msgTemEntity.getTitle();
        if (StringUtil.isNotEmpty(title)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            title = strSubstitutor.replace(title);
        }
        monitorEntity.setTitle(title);
        monitorEntity.setReceiveUser(accountEntity.getWebhookAddress());
        monitorEntity.setContent(content);
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        //消息监控-账号配置写入
        monitorEntity.setAccountId(accountEntity.getId());
        monitorEntity.setAccountCode(accountEntity.getEnCode());
        monitorEntity.setAccountName(accountEntity.getFullName());
        switch (accountEntity.getWebhookType()) {
            case 1:
                //钉钉
                if (Objects.equals(1, accountEntity.getApproveType())) {
                    JSONObject result = WebHookUtil.sendDDMessage(accountEntity.getWebhookAddress(), content);
                    messageMonitorService.create(monitorEntity);
                    if (ObjectUtil.isNotEmpty(result)) {
                        if (!"0".equals(result.get(ERRCODE).toString())) {
                            retJson.put(KeyConst.CODE, false);
                            retJson.put(KeyConst.ERROR, result.get(ERRMSG));
                            return retJson;
                        }
                    } else {
                        retJson.put(KeyConst.CODE, false);
                        retJson.put(KeyConst.ERROR, "webhook账号地址配置错误!");
                        return retJson;
                    }
                } else if (Objects.equals(2, accountEntity.getApproveType())) {
                    JSONObject result = WebHookUtil.sendDingDing(accountEntity.getWebhookAddress(), accountEntity.getBearer(), content);
                    messageMonitorService.create(monitorEntity);
                    if (ObjectUtil.isNotEmpty(result)) {
                        if (!"0".equals(result.get(ERRCODE).toString())) {
                            retJson.put(KeyConst.CODE, false);
                            retJson.put(KeyConst.ERROR, result.get(ERRMSG));
                            return retJson;
                        }
                    } else {
                        retJson.put(KeyConst.CODE, false);
                        retJson.put(KeyConst.ERROR, "webhook账号地址配置错误!");
                        return retJson;
                    }
                }
                break;
            case 2:
                if (Objects.equals(1, accountEntity.getApproveType())) {
                    JSONObject result = WebHookUtil.callWeChatBot(accountEntity.getWebhookAddress(), content);
                    messageMonitorService.create(monitorEntity);
                    if (!"0".equals(result.get(ERRCODE).toString())) {
                        retJson.put(KeyConst.CODE, false);
                        retJson.put(KeyConst.ERROR, result.get(ERRMSG));
                        return retJson;
                    }
                }
                break;
            default:
                break;
        }
        retJson.put(KeyConst.CODE, true);
        retJson.put(KeyConst.ERROR, MsgCode.SU012.get());
        return retJson;
    }
 
    /**
     * 发送企业微信消息
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    private JSONObject sendQyWebChat(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        if (msgTemEntity == null) {
            throw new DataException("消息模板数据不存在!");
        }
        //创建消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        //消息监控-消息模板写入
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
 
        String content = msgTemEntity.getContent();
        // 替换参数
        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);
        }
        monitorEntity.setTitle(title);
        monitorEntity.setContent(content);
        // 获取系统配置
        SocialsSysConfig config = sysconfigService.getSocialsConfig();
        String corpId = config.getQyhCorpId();
        String agentId = config.getQyhAgentId();
        // 获取的应用的Secret值(某个修复导致俩个秘钥反了,只能反正修复了)
        String corpSecret = config.getQyhCorpSecret();
        // 相关参数验证
        if (StringUtil.isEmpty(corpId)) {
            throw new DataException("企业ID为空!");
        }
        if (StringUtil.isEmpty(corpSecret)) {
            throw new DataException("凭证密钥为空!");
        }
        if (StringUtil.isEmpty(agentId)) {
            throw new DataException("企业微信应用凭证为空!");
        }
        if (StringUtil.isEmpty(content)) {
            throw new DataException("内容为空!");
        }
 
        for (String userId : toUserIdsList) {
            UserEntity userEntity = userService.getInfoById(userId);
            if (userEntity != null) {
                String wxUserId = "";
                StringBuilder toWxUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
 
                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));
 
                // 获取接收人员的企业微信号、创建消息用户实体
                wxUserId = "";
                // 从同步表获取对应的企业微信ID
                SynThirdInfoEntity synThirdInfoEntity = synThirdInfoApi.getInfoBySysObjId("1", "2", userId, userInfo.getTenantId());
                if(synThirdInfoEntity == null){
                    synThirdInfoEntity = synThirdInfoApi.getInfoBySysObjId("11", "2", userId, userInfo.getTenantId());
                }
                if (synThirdInfoEntity != null) {
                    wxUserId = synThirdInfoEntity.getThirdObjId();
                }
                if (StringUtil.isEmpty(wxUserId)) {
                    nullUserInfo = nullUserInfo.append(",").append(userId);
                } else {
                    toWxUserId = toWxUserId.append("|").append(wxUserId);
                }
                JnpfMessageUtil.setMessageReceiveEntity(userId, title, Integer.valueOf(sendType));
 
                // 处理企业微信号信息串并验证
                toUserIdAll = toWxUserId.toString();
                if (StringUtil.isNotEmpty(toUserIdAll)) {
                    toUserIdAll = toUserIdAll.substring(1);
                }
                if (StringUtil.isEmpty(toUserIdAll)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName()).append(":").append("接收人对应的企业微信号全部为空!");
                    messageMonitorService.create(monitorEntity);
                } else {
                    // 批量发送企业信息信息
                    retJson = QyWebChatUtil.sendWxMessage(corpId, corpSecret, agentId, toUserIdAll, content);
                    if (!retJson.getBooleanValue(KeyConst.CODE)) {
                        code = false;
                        error = error.append(";").append(userEntity.getRealName()).append(":").append(retJson.get(KeyConst.ERROR));
                        messageMonitorService.create(monitorEntity);
                    } else {
                        // 企业微信号为空的信息写入备注
                        if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                            messageEntity.setExcerpt(nullUserInfo.substring(1) + "对应的企业微信号为空");
                            messageMonitorService.create(monitorEntity);
                        }
                    }
                }
            } else {
                code = false;
                error = error.append(";").append("用户不存在!");
                messageMonitorService.create(monitorEntity);
            }
        }
 
        if (code) {
            retJson.put(KeyConst.CODE, true);
            retJson.put(KeyConst.ERROR, MsgCode.SU012.get());
        } else {
            String msg = error.toString();
            msg = msg.substring(1);
            retJson.put(KeyConst.CODE, false);
            retJson.put(KeyConst.ERROR, msg);
        }
        return retJson;
    }
 
    /**
     * List<String> toUserIdsList, UserInfo userInfo, String sendType, MessageTemplateEntity entity, Map<String, String> parameterMap
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    private JSONObject sendDingTalk(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
        //创建消息监控
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        if (msgTemEntity == null) {
            throw new DataException("消息模板数据不存在!");
        }
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        //消息监控-消息模板写入
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
 
        String content = msgTemEntity.getContent();
        // 替换参数
        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);
        }
        monitorEntity.setTitle(title);
        monitorEntity.setContent(content);
        // 获取系统配置
        SocialsSysConfig config = sysconfigService.getSocialsConfig();
        String appKey = config.getDingSynAppKey();
        String appSecret = config.getDingSynAppSecret();
        String agentId = config.getDingAgentId();
        // 相关参数验证
        if (StringUtil.isEmpty(appKey)) {
            throw new DataException("AppKey为空!");
        }
        if (StringUtil.isEmpty(appSecret)) {
            throw new DataException("AppSecret为空!");
        }
        if (StringUtil.isEmpty(agentId)) {
            throw new DataException("AgentId为空!");
        }
        if (StringUtil.isEmpty(content)) {
            throw new DataException("内容为空!");
        }
 
        for (String userId : toUserIdsList) {
            UserEntity userEntity = userService.getInfoById(userId);
            if (userEntity != null) {
                String dingUserId = "";
                StringBuilder toDingUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));
 
                // 获取接收人员的钉钉号、创建消息用户实体
                dingUserId = "";
                // 从同步表获取对应用户的钉钉ID
                SynThirdInfoEntity synThirdInfoEntity = synThirdInfoApi.getInfoBySysObjId("2", "2", userId, userInfo.getTenantId());
                if(synThirdInfoEntity == null){
                    synThirdInfoEntity = synThirdInfoApi.getInfoBySysObjId("22", "2", userId, userInfo.getTenantId());
                }
                if (synThirdInfoEntity != null) {
                    dingUserId = synThirdInfoEntity.getThirdObjId();
                }
                if (StringUtil.isEmpty(dingUserId)) {
                    nullUserInfo = nullUserInfo.append(",").append(userId);
                } else {
                    toDingUserId = toDingUserId.append(",").append(dingUserId);
                }
                JnpfMessageUtil.setMessageReceiveEntity(userId, title, Integer.valueOf(sendType));
 
                // 处理接收人员的钉钉号信息串并验证
                toUserIdAll = toDingUserId.toString();
                if (StringUtil.isNotEmpty(toUserIdAll)) {
                    toUserIdAll = toUserIdAll.substring(1);
                }
                if (StringUtil.isEmpty(toUserIdAll)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName()).append(":").append("接收人对应的钉钉号为空!");
                    messageMonitorService.create(monitorEntity);
                } else {
                    // 批量发送钉钉信息
                    retJson = DingTalkUtil.sendDingMessage(appKey, appSecret, agentId, toUserIdAll, content);
                    if (!retJson.getBooleanValue(KeyConst.CODE)) {
                        code = false;
                        error = error.append(";").append(userEntity.getRealName()).append(":").append(retJson.get(KeyConst.ERROR));
                        messageMonitorService.create(monitorEntity);
                    } else {
                        // 钉钉号为空的信息写入备注
                        if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                            messageEntity.setExcerpt(nullUserInfo.toString().substring(1) + "对应的钉钉号为空!");
                            messageMonitorService.create(monitorEntity);
                        }
                    }
                }
            } else {
                code = false;
                error = error.append(";").append("用户不存在!");
                messageMonitorService.create(monitorEntity);
            }
        }
 
        if (code) {
            retJson.put(KeyConst.CODE, true);
            retJson.put(KeyConst.ERROR, MsgCode.SU012.get());
        } else {
            String msg = error.toString();
            msg = msg.substring(1);
            retJson.put(KeyConst.CODE, false);
            retJson.put(KeyConst.ERROR, msg);
        }
        return retJson;
    }
 
    /**
     * 发送邮件
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    private JSONObject sendMail(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
        //创建消息监控
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        if (msgTemEntity == null) {
            throw new DataException("消息模板数据不存在!");
        }
        AccountConfigEntity accountEntity = accountConfigService.getInfo(model.getAccountConfigId());
        if (accountEntity == null) {
            throw new DataException("webhook账号地址配置错误配置数据不存在!");
        }
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        //消息监控-消息模板写入
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
        //消息监控-账号配置写入
        monitorEntity.setAccountId(accountEntity.getId());
        monitorEntity.setAccountCode(accountEntity.getEnCode());
        monitorEntity.setAccountName(accountEntity.getFullName());
        String content = msgTemEntity.getContent();
        // 替换参数
        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);
        }
        monitorEntity.setTitle(title);
        monitorEntity.setContent(content);
 
        // 相关参数验证
        Map<String, String> objModel = new HashMap<>();
        objModel.put("emailSmtpHost", accountEntity.getSmtpServer());
        objModel.put("emailSmtpPort", accountEntity.getSmtpPort().toString());
        objModel.put("emailSenderName", accountEntity.getAddressorName());
        objModel.put("emailAccount", accountEntity.getSmtpUser());
        objModel.put("emailPassword", accountEntity.getSmtpPassword());
        objModel.put("emailSsl", accountEntity.getSslLink().equals(1) ? "true" : "false");
 
        EmailModel emailModel = JsonUtil.getJsonToBean(objModel, EmailModel.class);
        if (StringUtil.isEmpty(emailModel.getEmailSmtpHost())) {
            throw new DataException("SMTP服务为空!");
        }
        if (StringUtil.isEmpty(emailModel.getEmailSmtpPort())) {
            throw new DataException("SMTP端口为空!");
        }
        if (StringUtil.isEmpty(emailModel.getEmailAccount())) {
            throw new DataException("发件人邮箱为空!");
        }
        if (StringUtil.isEmpty(emailModel.getEmailPassword())) {
            throw new DataException("发件人密码为空!");
        }
        for (String userId : toUserIdsList) {
            UserEntity userEntity = userService.getInfoById(userId);
            if (userEntity != null) {
                StringBuilder nullUserInfo = new StringBuilder();
                StringBuilder toUserMail = new StringBuilder();
                String userEmailAll = "";
                String userEmail = "";
                String userName = "";
 
                // 设置邮件标题
                emailModel.setEmailTitle(title);
                // 设置邮件内容
                emailModel.setEmailContent(content);
                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), emailModel.getEmailTitle(), emailModel.getEmailContent(), Integer.parseInt(sendType));
                // 获取收件人的邮箱地址、创建消息用户实体
                if (userEntity != null) {
                    userEmail = StringUtil.isEmpty(userEntity.getEmail()) ? "" : userEntity.getEmail();
                    userName = userEntity.getRealName();
                }
                if (userEmail != null && !"".equals(userEmail)) {
                    if (EmailUtil.isEmail(userEmail)) {
                        toUserMail = toUserMail.append(",").append(userName).append("<").append(userEmail).append(">");
                    }
                } else {
                    nullUserInfo = nullUserInfo.append(",").append(userId);
                }
                JnpfMessageUtil.setMessageReceiveEntity(userId, title, Integer.valueOf(sendType));
 
                // 处理接收人员的邮箱信息串并验证
                userEmailAll = toUserMail.toString();
                if (StringUtil.isNotEmpty(userEmailAll)) {
                    userEmailAll = userEmailAll.substring(1);
                }
                if (StringUtil.isEmpty(userEmailAll)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName()).append(":").append(MSG_NO_USER);
                    messageMonitorService.create(monitorEntity);
                } else {
                    // 设置接收人员
                    emailModel.setEmailToUsers(userEmailAll);
                    // 发送邮件
                    retJson = EmailUtil.sendMail(emailModel);
                    if (!retJson.getBooleanValue(KeyConst.CODE)) {
                        code = false;
                        error = error.append(";").append(userEntity.getRealName()).append(":").append(retJson.get(KeyConst.ERROR));
                        messageMonitorService.create(monitorEntity);
                    } else {
                        // 邮箱地址为空的信息写入备注
                        if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                            messageEntity.setExcerpt(nullUserInfo.substring(1) + "对应的邮箱为空");
                            messageMonitorService.create(monitorEntity);
                        }
                    }
                }
            }
        }
 
        if (code) {
            retJson.put(KeyConst.CODE, true);
            retJson.put(KeyConst.ERROR, MsgCode.SU012.get());
        } else {
            String msg = error.toString();
            msg = msg.substring(1);
            retJson.put(KeyConst.CODE, false);
            retJson.put(KeyConst.ERROR, msg);
        }
        return retJson;
    }
 
    /**
     * 发送短信
     *
     * @param toUserIdsList
     * @param parameterMap
     * @return
     */
    private JSONObject sendSms(List<String> toUserIdsList, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        UserInfo userInfo = UserProvider.getUser();
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
 
        //创建消息监控
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        if (msgTemEntity == null) {
            throw new DataException("消息模板数据不存在!");
        }
        AccountConfigEntity accountEntity = accountConfigService.getInfo(model.getAccountConfigId());
        if (accountEntity == null) {
            throw new DataException("webhook账号地址配置错误配置数据不存在!");
        }
        //账号配置——短信
        Map<String, String> objModel = new HashMap<>(16);
        objModel.put("aliAccessKey", accountEntity.getAppId());
        objModel.put("aliSecret", accountEntity.getAppSecret());
        objModel.put("tencentSecretId", accountEntity.getAppId());
        objModel.put("tencentSecretKey", accountEntity.getAppSecret());
        objModel.put("tencentAppId", accountEntity.getSdkAppId());
        objModel.put("tencentAppKey", accountEntity.getAppKey());
        SmsModel smsConfig = JsonUtil.getJsonToBean(objModel, SmsModel.class);
        Map<String, Object> smsMap = smsFieldService.getParamMap(msgTemEntity.getId(), parameterMap);
 
        String content = msgTemEntity.getContent();
        // 替换参数
        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);
        }
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        //消息监控-消息模板写入
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
        //消息监控-账号配置写入
        monitorEntity.setAccountId(accountEntity.getId());
        monitorEntity.setAccountCode(accountEntity.getEnCode());
        monitorEntity.setAccountName(accountEntity.getFullName());
        monitorEntity.setTitle(title);
        monitorEntity.setContent(content);
 
        for (String userId : toUserIdsList) {
            UserEntity userEntity = userService.getInfoById(userId);
            if (userEntity != null) {
                int company = accountEntity.getChannel();
                // 组装接受用户
                StringBuilder toUserIdList = new StringBuilder();
                if (isPhone(userEntity.getMobilePhone())) {
                    toUserIdList.append(userEntity.getMobilePhone());
                    toUserIdList.append(",");
                }
                // 发送短信
                String endPoint = "";
                if (Objects.equals(1, accountEntity.getChannel())) {
                    endPoint = accountEntity.getEndPoint();
                } else if (Objects.equals(2, accountEntity.getChannel())) {
                    endPoint = accountEntity.getZoneName();
                }
                content = SmsUtil.querySmsTemplateContent(company, smsConfig, endPoint, accountEntity.getZoneParam(), msgTemEntity.getTemplateCode());
                if (StringUtils.isNotBlank(content) && !"null".equals(content)) {
                    if (Objects.equals(1, accountEntity.getChannel())) {
                        if (content.contains("${")) {
                            for (Map.Entry<String, Object> keyItem : smsMap.entrySet()) {
                                if (keyItem.getValue() != null && StringUtils.isNotBlank(keyItem.getValue().toString())) {
                                    content = content.replace("{" + keyItem.getKey() + "}", keyItem.getValue().toString());
                                }
                            }
                        }
                    } else if (Objects.equals(2, accountEntity.getChannel()) && content.contains("{")) {
                        for (Map.Entry<String, Object> keyItem : smsMap.entrySet()) {
                            if (keyItem.getValue() != null && StringUtils.isNotBlank(keyItem.getValue().toString())) {
                                content = content.replace("{" + keyItem.getKey() + "}", keyItem.getValue().toString());
                            }
                        }
                    }
                }
                monitorEntity.setContent(content);
                if (StringUtils.isEmpty(toUserIdList)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName()).append(":").append("手机号码格式错误!");
                    messageMonitorService.create(monitorEntity);
                } else {
                    String result = SmsUtil.sentSms(company, smsConfig, endPoint, accountEntity.getZoneParam(), toUserIdList.toString(), accountEntity.getSmsSignature(), msgTemEntity.getTemplateCode(), smsMap);
                    if (!"Ok".equalsIgnoreCase(result)) {
                        code = false;
                        error = error.append(";").append(userEntity.getRealName()).append(":").append(result);
                        messageMonitorService.create(monitorEntity);
                    }
                }
            }
        }
        if (code) {
            retJson.put(KeyConst.CODE, true);
            retJson.put(KeyConst.ERROR, MsgCode.SU012.get());
        } else {
            String msg = error.toString();
            msg = msg.substring(1);
            retJson.put(KeyConst.CODE, false);
            retJson.put(KeyConst.ERROR, msg);
        }
        return retJson;
    }
 
    /**
     * 发送微信公众号消息
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param parameterMap
     * @return
     */
    public JSONObject sendWXGzhChat(List<String> toUserIdsList, UserInfo userInfo, String
            sendType, SendConfigTemplateModel model, Map<String, Object> parameterMap) {
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
        //创建消息监控
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(model.getTemplateId());
        if (msgTemEntity == null) {
            log.error(sendType);
            throw new DataException("消息模板数据不存在!");
        }
        AccountConfigEntity accountEntity = accountConfigService.getInfo(model.getAccountConfigId());
        if (accountEntity == null) {
            throw new DataException("账号配置数据不存在!");
        }
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        //消息监控-消息模板写入
        monitorEntity.setMessageType(msgTemEntity.getMessageType());
        monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
        monitorEntity.setMessageTemplateId(msgTemEntity.getId());
        //消息监控-账号配置写入
        monitorEntity.setAccountId(accountEntity.getId());
        monitorEntity.setAccountCode(accountEntity.getEnCode());
        monitorEntity.setAccountName(accountEntity.getFullName());
        String content = msgTemEntity.getContent();
        // 替换参数
        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);
        }
        monitorEntity.setTitle(title);
        monitorEntity.setContent(content);
        //微信公众号参数
        Map<String, Object> smsMap = new HashMap<>();
        if (model != null) {
            smsMap = smsFieldService.getParamMap(model.getTemplateId(), parameterMap);
        }
        if (smsMap.containsKey(KeyConst.TITLE)) {
            title = smsMap.get(KeyConst.TITLE).toString();
            smsMap.keySet().removeIf(k -> k.equals(KeyConst.TITLE));
        }
 
        // 获取系统配置
        String appId = accountEntity.getAppId();
        String appsecret = accountEntity.getAppSecret();
        String wxxcxAppId = msgTemEntity.getXcxAppId();
        String templateKId = msgTemEntity.getTemplateCode();
        // 相关参数验证
        if (StringUtil.isEmpty(templateKId)) {
            throw new DataException("微信公众号模板id未创建!");
        }
        if (StringUtil.isEmpty(appId)) {
            throw new DataException("公众号appid为空为空!");
        }
        if (StringUtil.isEmpty(appsecret)) {
            throw new DataException("公众号appsecret为空为空!");
        }
        // 获取微信公众号的token
        String token = WXGZHWebChatUtil.getAccessToken(appId, appsecret);
        if (StringUtil.isEmpty(token)) {
            throw new DataException("获取微信公众号token失败!");
        }
        for (String userId : toUserIdsList) {
            UserEntity userEntity = userService.getInfoById(userId);
            monitorEntity.setTitle(title);
            if (userEntity != null) {
                //获取用户在对应微信公众号上的openid
                WechatUserEntity wechatUserEntity = wechatUserService.getInfoByGzhId(userId, accountEntity.getAppKey());
                if (wechatUserEntity != null) {
                    if (StringUtils.isNotBlank(wechatUserEntity.getOpenId())) {
                        String openid = wechatUserEntity.getOpenId();
                        String pagepath = "pages/login/index?tag=1&flowId=";
                        //参数封装
                        String message = WXGZHWebChatUtil.messageJson(templateKId, openid, wxxcxAppId, pagepath, smsMap, "2", null);
                        //发送信息
                        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 (messageModel != null) {
                            content = messageModel.getContent();
                            if (StringUtils.isNotBlank(content) && !"null".equals(content) && ObjectUtil.isNotEmpty(smsMap) && content.contains(".DATA}")) {
                                for (Map.Entry<String, Object> keyItem : smsMap.entrySet()) {
                                    content = content.replace(keyItem.getKey(), keyItem.getValue().toString());
                                }
 
                            }
                        }
                        //创建消息监控
                        monitorEntity.setContent(content);
                        if (!retJson.getBooleanValue(KeyConst.CODE)) {
                            code = false;
                            error = error.append(";").append(userEntity.getRealName()).append(":").append(retJson.get(KeyConst.ERROR));
                            messageMonitorService.create(monitorEntity);
                            continue;
                        }
                        messageMonitorService.create(monitorEntity);
                    } else {
                        code = false;
                        error = error.append(";").append(userEntity.getRealName()).append(":").append("账号未绑定公众号!");
                        messageMonitorService.create(monitorEntity);
                    }
                } else {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName()).append(":").append("账号未绑定公众号!");
                    messageMonitorService.create(monitorEntity);
                }
            }
        }
        if (code) {
            retJson.put(KeyConst.CODE, true);
            retJson.put(KeyConst.ERROR, MsgCode.SU012.get());
        } else {
            String msg = error.toString();
            msg = msg.substring(1);
            retJson.put(KeyConst.CODE, false);
            retJson.put(KeyConst.ERROR, msg);
        }
        return retJson;
    }
 
    public static boolean isPhone(String phone){
        if (StringUtils.isNotBlank(phone) && !"null".equals(phone)) {
            return Pattern.matches("^1[3-9]\\d{9}$", phone);
        }
        return false;
    }
}