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
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
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.base.model.synthirdinfo.DingTalkModel;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.MsgCode;
import jnpf.message.entity.*;
import jnpf.message.mapper.*;
import jnpf.message.model.EmailModel;
import jnpf.model.SocialsSysConfig;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.util.DateUtil;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.message.SmsUtil;
import jnpf.util.third.DingTalkUtil;
import jnpf.util.third.QyWebChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;
 
/**
 * 消息实体类
 *
 * @版本: V3.2.0
 * @版权: 引迈信息技术有限公司(https://www.jnpfsoft.com)
 * @作者: JNPF开发平台组
 * @日期: 2021/4/22 9:06
 */
@Component
@Slf4j
public class SentMessageUtil {
 
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private SysConfigApi sysconfigService;
    @Autowired
    private UserApi userApi;
    @Autowired
    private SynThirdInfoApi synThirdInfoApi;
 
    @Autowired
    private AccountConfigMapper accountConfigMapper;
    @Autowired
    private MessageTemplateConfigMapper messageTemplateConfigMapper;
    @Autowired
    private MessageMonitorMapper messageMonitorMapper;
    @Autowired
    private SmsFieldMapper smsFieldMapper;
    @Autowired
    private ShortLInkMapper shortLInkMapper;
 
    /**
     * 发送企业微信消息
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    public JSONObject SendQyWebChat(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, Object> parameterMap, Map<String, String> contentMsg) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigMapper.getInfo(entity.getTemplateId());
 
        JSONObject retJson = new JSONObject();
        boolean code = true;
        StringBuilder error = new StringBuilder();
        // 获取接收人员的企业微信号、创建消息用户实体
        for (String userId : toUserIdsList) {
            error = new StringBuilder();
            MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
            monitorEntity.setId(RandomUtil.uuId());
            monitorEntity.setSendTime(DateUtil.getNowDate());
            monitorEntity.setCreatorTime(DateUtil.getNowDate());
            monitorEntity.setCreatorUserId(userInfo.getUserId());
            if (StringUtil.isEmpty(userId)) {
                code = false;
                error = error.append(";").append("接收人为空!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            monitorEntity.setReceiveUser(userId);
            UserEntity userEntity = userApi.getInfoById(userId);
            if (ObjectUtil.isEmpty(userEntity)) {
                code = false;
                error = error.append(";").append("用户不存在!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            if (msgTemEntity != null) {
                //获取消息模板参数
                Map<String, Object> msgMap = getParamMap(entity.getId(), parameterMap);
                // 替换参数
                String content = msgTemEntity.getContent();
                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());
                String msgTC = msgTemEntity.getTitle() + msgTemEntity.getContent();
                if (StringUtil.isNotBlank(msgTC)) {
                    if (msgTC.contains("{@FlowLink}")) {
                        //链接数据保存
                        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 (StringUtil.isNotEmpty(content)) {
                    if (content.contains("{@FlowLink}")) {
                        content = content.replace("{@FlowLink}", link + " ");
                    }
                    StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                    content = strSubstitutor.replace(content);
                }
 
                // 替换参数
                String title = msgTemEntity.getTitle();
                if (StringUtil.isNotEmpty(title)) {
                    if (title.contains("{@FlowLink}")) {
                        title = title.replace("{@FlowLink}", link + " ");
                    }
                    StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                    title = strSubstitutor.replace(title);
                }
                title = systemParam(parameterMap, contentMsg, title, userInfo);
                content = systemParam(parameterMap, contentMsg, content, userInfo);
                monitorEntity.setTitle(title);
                monitorEntity.setContent(content);
                // 获取系统配置
                SocialsSysConfig config = sysconfigService.getSocialsConfig();
                String corpId = config.getQyhCorpId();
                String agentId = config.getQyhAgentId();
                // 获取的应用的Secret值(某个修复导致俩个秘钥反了,只能反正修复了)
                String corpSecret = config.getQyhCorpSecret();
                String wxUserId = "";
                StringBuilder toWxUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();
 
                // 相关参数验证
                if (StringUtil.isEmpty(corpId)) {
                    log.error("企业ID为空");
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":企业ID为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                if (StringUtil.isEmpty(corpSecret)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":Secret为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                if (StringUtil.isEmpty(agentId)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":AgentId为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                if (StringUtil.isEmpty(content)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":内容为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));
                //创建消息监控
                monitorEntity = createMessageMonitor(monitorEntity, msgTemEntity, null, content, userInfo, null, title);
                // 获取接收人员的企业微信号、创建消息用户实体
//                    for (String userId : toUserIdsList) {
                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);
                }
                messageReceiveList.add(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() + ":接收人对应的企业微信号全部为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                // 发送企业信息信息
                retJson = QyWebChatUtil.sendWxMessage(corpId, corpSecret, agentId, toUserIdAll, content);
                if (!retJson.getBoolean("code")) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":" + retJson.get("error"));
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                // 批量发送企业信息信息
//                    retJson = QyWebChatUtil.sendWxMessage(corpId, corpSecret, agentId, toUserIdAll, content);
//                    messageMonitorMapper.create(monitorEntity);
//                    if (!retJson.getBoolean("code")) {
//                        return retJson;
//                    }
 
                // 企业微信号为空的信息写入备注
                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                    messageEntity.setExcerpt(nullUserInfo.substring(1) + "对应的企业微信号为空");
                }
                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;
    }
 
    /**
     * List<String> toUserIdsList, UserInfo userInfo, String sendType, MessageTemplateEntity entity, Map<String, String> parameterMap
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    public JSONObject SendDingTalk(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, Object> parameterMap, Map<String, String> contentMsg) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigMapper.getInfo(entity.getTemplateId());
 
        boolean code = true;
        StringBuilder error = new StringBuilder();
        JSONObject retJson = new JSONObject();
        for (String userId : toUserIdsList) {
            error = new StringBuilder();
            //消息监控
            MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
            monitorEntity.setId(RandomUtil.uuId());
            monitorEntity.setSendTime(DateUtil.getNowDate());
            monitorEntity.setCreatorTime(DateUtil.getNowDate());
            monitorEntity.setCreatorUserId(userInfo.getUserId());
            monitorEntity.setReceiveUser(userId);
            if (StringUtil.isEmpty(userId)) {
                code = false;
                error = error.append(";").append("接收人为空!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            UserEntity userEntity = userApi.getInfoByIdInMessage(userId);
            if (ObjectUtil.isEmpty(userEntity)) {
                code = false;
                error = error.append(";").append("用户不存在!");
                messageMonitorMapper.create(monitorEntity);
                continue;
            }
            if (msgTemEntity != null) {
                String content = msgTemEntity.getContent();
                //获取消息模板参数
                Map<String, Object> msgMap = getParamMap(entity.getId(), parameterMap);
                //转换链接
                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());
                String msgTC = msgTemEntity.getTitle() + msgTemEntity.getContent();
                if (StringUtil.isNotBlank(msgTC)) {
                    if (msgTC.contains("{@FlowLink}")) {
                        //链接数据保存
                        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 (StringUtil.isNotEmpty(content)) {
                    if (content.contains("{@FlowLink}")) {
                        content = content.replace("{@FlowLink}", link + " ");
                    }
                    StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                    content = strSubstitutor.replace(content);
                }
                // 替换参数
                String title = msgTemEntity.getTitle();
                if (StringUtil.isNotEmpty(title)) {
                    if (title.contains("{@FlowLink}")) {
                        title = title.replace("{@FlowLink}", link + " ");
                    }
                    StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                    title = strSubstitutor.replace(title);
                }
 
                title = systemParam(parameterMap, contentMsg, title, userInfo);
                content = systemParam(parameterMap, contentMsg, content, userInfo);
                monitorEntity.setTitle(title);
                monitorEntity.setContent(content);
 
                Map<String, String> objModel = getSystemConfig();
                DingTalkModel dingTalkModel = JsonUtil.getJsonToBean(objModel, DingTalkModel.class);
                String appKey = dingTalkModel.getDingSynAppKey();
                String appSecret = dingTalkModel.getDingSynAppSecret();
                String agentId = dingTalkModel.getDingAgentId();
                String dingUserId = "";
                StringBuilder toDingUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();
 
                // 相关参数验证
                if (StringUtil.isEmpty(appKey)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":AppKey为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                if (StringUtil.isEmpty(appSecret)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":AppSecret为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                if (StringUtil.isEmpty(agentId)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":AgentId为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                if (StringUtil.isEmpty(content)) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":AgentId为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));
                //创建消息监控
                monitorEntity = createMessageMonitor(monitorEntity, msgTemEntity, null, content, userInfo, null, title);
                // 获取接收人员的钉钉号、创建消息用户实体
//                    for (String userId : toUserIdsList) {
                dingUserId = "";
                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);
                }
                messageReceiveList.add(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() + ":接收人对应的钉钉号为空!");
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
                // 发送钉钉信息
                retJson = DingTalkUtil.sendDingMessage(appKey, appSecret, agentId, toUserIdAll, content);
                if (!retJson.getBoolean("code")) {
                    code = false;
                    error = error.append(";").append(userEntity.getRealName() + ":" + retJson.get("error"));
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                }
 
                // 钉钉号为空的信息写入备注
                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                    messageEntity.setExcerpt(nullUserInfo.toString().substring(1) + "对应的钉钉号为空");
                }
                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;
    }
 
    /**
     * 发送邮件
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    public List<String> SendMail(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, Object> parameterMap, Map<String, String> contentMsg) {
        List<String> errList = new ArrayList<>();
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigMapper.getInfo(entity.getTemplateId());
        AccountConfigEntity accountEntity = accountConfigMapper.getInfo(entity.getAccountConfigId());
        for (String userId : toUserIdsList) {
            //消息监控
            MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
            monitorEntity.setId(RandomUtil.uuId());
            monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
            monitorEntity.setSendTime(DateUtil.getNowDate());
            monitorEntity.setCreatorTime(DateUtil.getNowDate());
            monitorEntity.setCreatorUserId(userInfo.getUserId());
            if (StringUtil.isEmpty(userId)) {
                log.error("接收人为空");
                messageMonitorMapper.create(monitorEntity);
                errList.add("接收人为空");
                continue;
            }
            monitorEntity.setReceiveUser(userId);
            UserEntity userEntity = userApi.getInfoByIdInMessage(userId);
            if (msgTemEntity != null) {
                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());
                String msgTC = msgTemEntity.getTitle() + msgTemEntity.getContent();
                if (StringUtil.isNotBlank(msgTC)) {
                    if (msgTC.contains("{@FlowLink}")) {
                        //链接数据保存
                        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();
                }
                Map<String, Object> msgMap = getParamMap(entity.getId(), parameterMap);
                // 设置邮件标题
                String title = msgTemEntity.getTitle();
                if (title.contains("{@FlowLink}")) {
                    title = title.replace("{@FlowLink}", link + " ");
                }
                if (StringUtil.isNotEmpty(title)) {
                    StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                    title = strSubstitutor.replace(title);
                }
                // 设置邮件内容
                String content = msgTemEntity.getContent();
                if (content.contains("{@FlowLink}")) {
                    content = content.replace("{@FlowLink}", link + " ");
                }
                //获取消息模板参数
                if (StringUtil.isNotEmpty(content)) {
                    StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                    content = strSubstitutor.replace(content);
                }
                title = systemParam(parameterMap, contentMsg, title, userInfo);
                content = systemParam(parameterMap, contentMsg, content, userInfo);
                monitorEntity.setTitle(title);
                monitorEntity.setContent(content);
                if (accountEntity != null) {
                    // 获取系统配置
                    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);
                    StringBuilder nullUserInfo = new StringBuilder();
                    List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();
                    StringBuilder toUserMail = new StringBuilder();
                    String userEmailAll = "";
                    String userEmail = "";
                    String userName = "";
 
                    // 相关参数验证
                    if (StringUtil.isEmpty(emailModel.getEmailSmtpHost())) {
                        log.error("SMTP服务为空");
                        messageMonitorMapper.create(monitorEntity);
                        errList.add("SMTP服务为空");
                        continue;
                    } else if (StringUtil.isEmpty(emailModel.getEmailSmtpPort())) {
                        log.error("SMTP端口为空");
                        messageMonitorMapper.create(monitorEntity);
                        errList.add("SMTP端口为空");
                        continue;
                    } else if (StringUtil.isEmpty(emailModel.getEmailAccount())) {
                        log.error("发件人邮箱为空");
                        messageMonitorMapper.create(monitorEntity);
                        errList.add("发件人邮箱为空");
                        continue;
                    } else if (StringUtil.isEmpty(emailModel.getEmailPassword())) {
                        log.error("发件人密码为空");
                        messageMonitorMapper.create(monitorEntity);
                        errList.add("发件人密码为空");
                        continue;
                    } else {
                        // 设置邮件标题
                        emailModel.setEmailTitle(title);
                        // 设置邮件内容
                        emailModel.setEmailContent(content);
 
                        // 创建消息实体
                        MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), title, emailModel.getEmailContent(), Integer.parseInt(sendType));
                        //创建消息监控
                        monitorEntity = createMessageMonitor(monitorEntity, msgTemEntity, accountEntity, content, userInfo, null, title);
                        // 获取收件人的邮箱地址、创建消息用户实体
//                        for (String userId : toUserIdsList) {
                        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);
                        }
                        messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(userId, title, Integer.parseInt(sendType)));
//                        }
 
                        // 处理接收人员的邮箱信息串并验证
                        userEmailAll = toUserMail.toString();
                        if (StringUtil.isNotEmpty(userEmailAll)) {
                            userEmailAll = userEmailAll.substring(1);
                        }
                        if (StringUtil.isEmpty(userEmailAll)) {
                            log.error("接收人对应的邮箱格式错误");
                            messageMonitorMapper.create(monitorEntity);
                            errList.add("接收人对应的邮箱格式错误");
                            continue;
                        } else {
                            // 设置接收人员
                            emailModel.setEmailToUsers(userEmailAll);
                            // 发送邮件
                            JSONObject retJson = EmailUtil.sendMail(emailModel);
                            messageMonitorMapper.create(monitorEntity);
                            if (!retJson.getBoolean("code")) {
                                log.error("发送失败");
                                errList.add("发送失败");
                                continue;
                            } else {
                                // 邮箱地址为空的信息写入备注
                                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                                    messageEntity.setExcerpt(nullUserInfo.substring(1) + "对应的邮箱为空");
                                }
                                continue;
                                // 写入系统的消息表、消息用户表
                            }
                        }
                    }
                }
                continue;
            }
            continue;
        }
        return errList;
    }
 
    /**
     * 发送短信
     *
     * @param toUserIdsList
     * @param entity
     * @param parameterMap
     * @return
     */
    public List<String> sendSms(List<String> toUserIdsList, UserInfo userInfo, SendConfigTemplateEntity entity, Map<String, Object> parameterMap, Map<String, String> contentMsg) {
        List<String> errList = new ArrayList<>();
        //获取短信配置
        AccountConfigEntity accountEntity = accountConfigMapper.getInfo(entity.getAccountConfigId());
        // 获取消息模板详情
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigMapper.getInfo(entity.getTemplateId());
        for (String toUserId : toUserIdsList) {
            //消息监控
            MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
            monitorEntity.setId(RandomUtil.uuId());
            monitorEntity.setSendTime(DateUtil.getNowDate());
            monitorEntity.setCreatorTime(DateUtil.getNowDate());
            monitorEntity.setCreatorUserId(userInfo.getUserId());
            monitorEntity.setReceiveUser(toUserId);
            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;
            String appLink = "/pages/workFlow/flowBefore/index?config=" + encode;
            //转换为短链
            String shortLink = shortLInkMapper.shortLink(pcLink + toUserId + msgTemEntity.getMessageType());
            shortLink = getShortLink(pcLink, toUserId, shortLink, msgTemEntity.getMessageType());
            //发送给用户的链接
            String link = configValueUtil.getApiDomain() + "/api/message/ShortLink/" + shortLink;
            if (StringUtil.isNotBlank(userInfo.getTenantId())) {
                link = link + "/" + userInfo.getTenantId();
            }
            //转换为短链
 
            if (accountEntity != null) {
                monitorEntity.setAccountId(accountEntity.getId());
                //账号配置——短信
                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);
                int company = accountEntity.getChannel();
                // 组装接受用户
                StringBuffer toUserIdList = new StringBuffer();
//                for (String toUserId : toUserIdsList) {
                UserEntity userEntity = userApi.getInfoById(toUserId);
                if (isPhone(userEntity.getMobilePhone())) {
                    toUserIdList.append(userEntity.getMobilePhone() + ",");
                }
//                }
                //获取消息模板参数
                Map<String, Object> msgMap = 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 (ObjectUtil.isNotEmpty(smsMap)) {
                        if (smsMap.containsValue("@FlowLink")) {
                            //链接数据保存
                            this.saveShortLink(pcLink, appLink, shortLink, userInfo, toUserId, msg);
                            for (String key : smsMap.keySet()) {
                                if (smsMap.get(key).equals("@FlowLink")) {
                                    smsMap.put(key, link + " ");
                                }
                            }
                        }
                    }
                }
//                if(smsMap.containsKey("title")) {
//                    smsMap.keySet().removeIf(k -> k.equals("title"));
//                }
                if (msgTemEntity != null) {
                    monitorEntity.setMessageTemplateId(msgTemEntity.getId());
                    String endPoint = "";
                    if (Objects.equals(1, accountEntity.getChannel())) {
                        endPoint = accountEntity.getEndPoint();
                    } else if (Objects.equals(2, accountEntity.getChannel())) {
                        endPoint = accountEntity.getZoneName();
                    }
                    String content = SmsUtil.querySmsTemplateContent(company, smsConfig, endPoint, accountEntity.getZoneParam(), msgTemEntity.getTemplateCode());
                    if (StringUtil.isNotBlank(content) && !"null".equals(content)) {
                        if (ObjectUtil.isNotEmpty(smsMap) && !"null".equals(smsMap)) {
                            if (Objects.equals(1, accountEntity.getChannel())) {
                                if (content.contains("${")) {
                                    for (String key : smsMap.keySet()) {
                                        content = content.replace("${" + key + "}", smsMap.get(key).toString());
                                    }
                                }
                            } else if (Objects.equals(2, accountEntity.getChannel())) {
                                if (content.contains("{")) {
                                    for (String key : smsMap.keySet()) {
                                        content = content.replace("{" + key + "}", smsMap.get(key).toString());
                                    }
                                }
                            }
                        }
                    }
                    //创建消息监控
                    monitorEntity = createMessageMonitor(monitorEntity, msgTemEntity, accountEntity, content, userInfo, null, null);
                    if (StringUtil.isEmpty(toUserIdList)) {
                        log.error("全部接收人对应的手机号码格式错误");
                        messageMonitorMapper.create(monitorEntity);
                        errList.add("全部接收人对应的手机号码格式错误");
                        continue;
                    }
                    SmsUtil.sentSms(company, smsConfig, endPoint, accountEntity.getZoneParam(), toUserIdList.toString(), accountEntity.getSmsSignature(), msgTemEntity.getTemplateCode(), smsMap);
                    messageMonitorMapper.create(monitorEntity);
                    continue;
                } else {
                    log.error("消息模板数据不存在");
                    messageMonitorMapper.create(monitorEntity);
                    errList.add("消息模板数据不存在");
                    continue;
                }
            } else {
                log.error("账号配置数据不存在");
                messageMonitorMapper.create(monitorEntity);
                errList.add("账号配置数据不存在");
                continue;
            }
        }
        return errList;
    }
 
    /**
     * 获取系统配置
     */
    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;
    }
 
    public static Map<String, Object> getParamMap(String templateId, Map<String, Object> paramMap) {
        Map<String, Object> map = new HashMap<>();
        for (String key : paramMap.keySet()) {
            if (key.contains(templateId)) {
                map.put(key.substring(templateId.length()), paramMap.get(key));
            }
        }
        return map;
    }
 
    public static MessageMonitorEntity createMessageMonitor(MessageMonitorEntity monitorEntity, MessageTemplateConfigEntity msgTemEntity, AccountConfigEntity accountEntity, String content, UserInfo userInfo, List<String> toUserIdsList, String title) {
        if (msgTemEntity != null) {
            monitorEntity.setMessageTemplateId(msgTemEntity.getId());
            monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
            if (StringUtil.isNotBlank(title)) {
                monitorEntity.setTitle(title);
            } else {
                monitorEntity.setTitle(msgTemEntity.getTitle());
            }
            monitorEntity.setMessageType(msgTemEntity.getMessageType());
            if ("6".equals(msgTemEntity.getMessageType()) && accountEntity != null) {
                monitorEntity.setReceiveUser(accountEntity.getWebhookAddress());
            } else {
                if (toUserIdsList != null && toUserIdsList.size() > 0) {
                    monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
                }
            }
        } else {
            if (StringUtil.isNotBlank(title)) {
                monitorEntity.setTitle(title);
            }
            monitorEntity.setMessageType("1");
        }
        if (accountEntity != null) {
            monitorEntity.setAccountId(accountEntity.getId());
            monitorEntity.setAccountCode(accountEntity.getEnCode());
            monitorEntity.setAccountName(accountEntity.getFullName());
        }
        monitorEntity.setContent(content);
        return monitorEntity;
    }
 
    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);
        }
    }
 
    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 = getUnableTime(linkTime);
                entity.setUnableTime(unableTime);
            } else {
                entity.setUnableTime(DateUtil.dateAddHours(DateUtil.getNowDate(), 24));
            }
            entity.setCreatorTime(DateUtil.getNowDate());
            entity.setCreatorUserId(userInfo.getUserId());
            shortLInkMapper.insert(entity);
        }
    }
 
    public static Date getUnableTime(String linkTime) {
        Double time = Double.parseDouble(linkTime);
        int second = Double.valueOf(time * 60 * 60).intValue();
        Date unableTime = DateUtil.dateAddSeconds(DateUtil.getNowDate(), second);
        return unableTime;
    }
 
    public static boolean isPhone(String phone) {
        if (StringUtil.isNotBlank(phone) && !"null".equals(phone)) {
            return Pattern.matches("^1[3-9]\\d{9}$", phone);
        }
        return false;
    }
 
    /**
     * 系统参数替换
     *
     * @param parameterMap
     * @param contentMsg
     * @param title
     * @param userInfo
     * @return
     */
    public static String systemParam(Map<String, Object> parameterMap, Map<String, String> contentMsg, String title, UserInfo userInfo) {
        if (parameterMap.isEmpty()) {
            return title = title.replaceAll("\\{@Title}", contentMsg.get("Title") != null ? contentMsg.get("Title") : "")
                    .replaceAll("\\{@CreatorUserName}", userInfo.getUserName())
                    .replaceAll("\\{@SendTime}", DateUtil.getNow().substring(11))
                    .replaceAll("\\{@Content}", contentMsg.get("Content") != null ? contentMsg.get("Content") : "")
                    .replaceAll("\\{@Remark}", contentMsg.get("Remark") != null ? contentMsg.get("Remark") : "")
                    .replaceAll("\\{@StartDate}", contentMsg.get("StartDate") != null ? contentMsg.get("StartDate") : "")
                    .replaceAll("\\{@StartTime}", contentMsg.get("StartTime") != null ? contentMsg.get("StartTime") : "")
                    .replaceAll("\\{@EndDate}", contentMsg.get("EndDate") != null ? contentMsg.get("EndDate") : "")
                    .replaceAll("\\{@FlowLink}", "")
                    .replaceAll("\\{@EndTime}", contentMsg.get("EndTime") != null ? contentMsg.get("EndTime") : "");
        }
        return title;
    }
 
}