admin
2020-11-03 f71ae35c5b20e51c5fba91284cc436076c9c73df
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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
package com.yeshi.fanli.service.impl.user.cloud;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
 
import javax.annotation.Resource;
 
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.exception.taobao.TaoBaoConvertLinkException;
import com.yeshi.fanli.service.manger.goods.TaoBaoLinkManager;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.BigDecimalUtil;
import org.yeshi.utils.taobao.TbImgUtil;
 
import com.aliyun.openservices.ons.api.Message;
import com.yeshi.fanli.dao.mybatis.user.cloud.UserCloudMapper;
import com.yeshi.fanli.dto.aitaoker.RobotInfoDTO;
import com.yeshi.fanli.dto.aitaoker.WeiXinGroupDTO;
import com.yeshi.fanli.dto.jd.JDCouponInfo;
import com.yeshi.fanli.dto.jd.JDPingouInfo;
import com.yeshi.fanli.dto.mq.user.UserTopicTagEnum;
import com.yeshi.fanli.dto.mq.user.body.UserCloudMQMsg;
import com.yeshi.fanli.dto.pdd.PDDGoodsDetail;
import com.yeshi.fanli.dto.suning.SuningGoodsImg;
import com.yeshi.fanli.dto.suning.SuningGoodsInfo;
import com.yeshi.fanli.dto.vip.VIPConvertResultDTO;
import com.yeshi.fanli.dto.vip.goods.VIPGoodsInfo;
import com.yeshi.fanli.entity.bus.user.UserExtraTaoBaoInfo;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.cloud.CloudOrderMenuEnum;
import com.yeshi.fanli.entity.bus.user.cloud.UserCloud;
import com.yeshi.fanli.entity.bus.user.cloud.UserCloudGoods;
import com.yeshi.fanli.entity.bus.user.cloud.UserCloudGroup;
import com.yeshi.fanli.entity.bus.user.cloud.UserCloudManage;
import com.yeshi.fanli.entity.bus.user.cloud.UserCloudSendContent;
import com.yeshi.fanli.entity.bus.user.cloud.UserCloudSendRecord;
import com.yeshi.fanli.entity.dynamic.CommentInfo;
import com.yeshi.fanli.entity.dynamic.GoodsEvaluate;
import com.yeshi.fanli.entity.dynamic.GoodsEvaluate.EvaluateEnum;
import com.yeshi.fanli.entity.dynamic.ImgInfo;
import com.yeshi.fanli.entity.dynamic.ImgInfo.ImgEnum;
import com.yeshi.fanli.entity.goods.CommonGoods;
import com.yeshi.fanli.entity.jd.JDGoods;
import com.yeshi.fanli.entity.system.ConfigKeyEnum;
import com.yeshi.goods.facade.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.entity.taobao.TaoBaoLink;
import com.yeshi.fanli.exception.goods.ConvertLinkExceptionException;
import com.yeshi.fanli.exception.user.cloud.UserCloudException;
import com.yeshi.fanli.exception.user.cloud.UserCloudGoodsException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.dynamic.GoodsEvaluateService;
import com.yeshi.fanli.service.inter.goods.ShareGoodsService;
import com.yeshi.fanli.service.inter.goods.ShareGoodsTextTemplateService;
import com.yeshi.fanli.service.inter.msg.UserOtherMsgNotificationService;
import com.yeshi.fanli.service.inter.push.PushService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.cloud.UserCloudGoodsService;
import com.yeshi.fanli.service.inter.user.cloud.UserCloudGroupService;
import com.yeshi.fanli.service.inter.user.cloud.UserCloudManageService;
import com.yeshi.fanli.service.inter.user.cloud.UserCloudSendContentService;
import com.yeshi.fanli.service.inter.user.cloud.UserCloudSendRecordService;
import com.yeshi.fanli.service.inter.user.cloud.UserCloudService;
import com.yeshi.fanli.service.inter.user.tb.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.service.manger.goods.ConvertLinkManager;
import com.yeshi.fanli.service.manger.msg.RocketMQManager;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.ImageToBase64;
import org.yeshi.utils.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.RedisKeyEnum;
import com.yeshi.fanli.util.RedisManager;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.aitaoker.AitaokerApiUtil;
import com.yeshi.fanli.util.cache.JDGoodsCacheUtil;
import com.yeshi.fanli.util.cache.PinDuoDuoCacheUtil;
import com.yeshi.fanli.util.jd.JDApiUtil;
import com.yeshi.fanli.util.jd.JDUtil;
import com.yeshi.fanli.util.pinduoduo.PinDuoDuoApiUtil;
import com.yeshi.fanli.util.pinduoduo.PinDuoDuoUtil;
import com.yeshi.fanli.util.rocketmq.MQMsgBodyFactory;
import com.yeshi.fanli.util.rocketmq.MQTopicName;
import com.yeshi.fanli.util.suning.SuningApiUtil;
import com.yeshi.fanli.util.suning.SuningUtil;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.vipshop.VipShopApiUtil;
import com.yeshi.fanli.util.vipshop.VipShopUtil;
import com.yeshi.fanli.vo.goods.GoodsDetailVO;
 
@Service
public class UserCloudServiceImpl implements UserCloudService {
 
    @Resource
    private UserCloudMapper userCloudMapper;
 
    @Resource
    private UserCloudGroupService userCloudGroupService;
 
    @Resource
    private GoodsEvaluateService goodsEvaluateService;
 
    @Resource
    private ConvertLinkManager convertLinkManager;
 
    @Resource
    private UserCloudGoodsService userCloudGoodsService;
 
    @Resource
    private UserInfoExtraService userInfoExtraService;
 
    @Resource
    private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
 
    @Resource
    private UserInfoService userInfoService;
 
    @Resource
    private ShareGoodsService shareGoodsService;
 
    @Resource
    private ConfigService configService;
 
    @Resource
    private JDGoodsCacheUtil jdGoodsCacheUtil;
 
    @Resource
    private PinDuoDuoCacheUtil pinDuoDuoCacheUtil;
 
 
    @Resource
    private RedisManager redisManager;
 
    @Resource
    private ShareGoodsTextTemplateService shareGoodsTextTemplateService;
 
    @Resource
    private UserCloudSendRecordService userCloudSendRecordService;
 
    @Resource
    private UserCloudSendContentService userCloudSendContentService;
 
    @Resource
    private UserCloudManageService userCloudManageService;
 
    @Resource
    private RocketMQManager rocketMQManager;
 
    @Resource
    private UserOtherMsgNotificationService userOtherMsgNotificationService;
 
    @Resource
    private PushService pushService;
 
    @Resource(name = "taskExecutor")
    private TaskExecutor executor;
 
    @Resource
    private TaoBaoLinkManager taoBaoLinkManager;
 
    @Override
    public UserCloud getValidByUid(Long uid) {
        return userCloudMapper.getValidByUid(uid);
    }
 
    @Override
    public UserCloud getLastByUid(Long uid) {
        return userCloudMapper.getLastByUid(uid);
    }
 
    @Override
    public long countByUid(Long uid) {
        Long count = userCloudMapper.countByUid(uid);
        return count;
    }
 
    @Override
    public List<UserCloud> query(int page, int count, String key, Integer state) {
        return userCloudMapper.query((page - 1) * count, count, key, state);
    }
 
    @Override
    public long count(String key, Integer state) {
        Long count = userCloudMapper.count(key, state);
        if (count == null)
            count = 0L;
        return count;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWXInfo(Long uid, String wxId, String wxName, String wxPortrait) throws UserCloudException {
        UserCloud userCloud = userCloudMapper.getValidByUid(uid);
        if (userCloud == null)
            throw new UserCloudException(1, "云发单已过期");
 
        // 检测是否需要更新 - 1分钟间隔
        String key = "cloudLogin_" + uid;
        String result = redisManager.getCommonString(key);
        if (!StringUtil.isNullOrEmpty(result)) {
            return;
        }
        redisManager.cacheCommonString(key, "true", 60);
 
        // 更新信息
        UserCloud update = new UserCloud();
        update.setId(userCloud.getId());
        update.setWxId(wxId);
        update.setWxName(wxName);
        update.setWxPortrait(wxPortrait);
        userCloudMapper.updateByPrimaryKeySelective(update);
 
        try {
            userOtherMsgNotificationService.cloudMsg(uid, "云发单微信账号", "微信账号登录成功", "可以开启你的群发单了");
        } catch (Exception e) {
            LogHelper.errorDetailInfo(e);
        }
 
        // 更新提醒状态
        UserCloudManage cloudManage = userCloudManageService.selectForUpdate(uid);
        if (cloudManage == null) {
            userCloudManageService.save(uid, false, false);
        } else {
            UserCloudManage updateManage = new UserCloudManage();
            updateManage.setId(uid);
            updateManage.setOfflineNotice(false);
            userCloudManageService.updateByPrimaryKeySelective(updateManage);
        }
 
        // 微信号变化-清空群信息
        if (!wxId.equals(userCloud.getWxId())) {
            userCloudGroupService.deleteGroupByUid(uid);
        }
 
        // 加入朋友圈
        if (StringUtil.isNullOrEmpty(userCloud.getWxId())) {
            userCloudGroupService.addCircle(uid);
        }
    }
 
    @Override
    public void openCloud(Long uid, Long orderId, CloudOrderMenuEnum menuEnum) throws UserCloudException {
        UserCloud existCloud = userCloudMapper.getByOrderId(orderId);
        if (existCloud != null) {
            return; // 该订单已处理完成
        }
 
        boolean renew = false;
        UserCloud userCloud = userCloudMapper.getLastByUid(uid);
        if (userCloud != null) {
            // 续费
            if (userCloud.getEndTime().getTime() > java.lang.System.currentTimeMillis())
                renew = true;
            // 验证套餐是否相同
            if (renew && userCloud.getRobotType() != menuEnum.getRobotType()) {
                LogHelper.cloudInfo("方法openCloud: [uid=" + uid + "][订单ID=" + orderId + "]已有其他云发单套餐还未结束");
                throw new UserCloudException(1, "已有其他云发单套餐还未结束");
            }
        }
 
        RobotInfoDTO dto = null;
        if (renew) { // 续费
            dto = AitaokerApiUtil.robotRenewals(userCloud.getRobotId(), menuEnum.getMonth());
        } else { // 创建机器人
            dto = AitaokerApiUtil.robotCreate(menuEnum.getMonth(), menuEnum.getRobotType(), "wechatrobot", null);
        }
 
        if (dto == null) {
            LogHelper.cloudInfo("方法openCloud: [uid=" + uid + "][订单ID=" + orderId + "]机器人失败: 机器人创建失败");
        }
 
        Integer robotId = dto.getId();
        if (robotId == null) {
            LogHelper.cloudInfo("方法openCloud: [uid=" + uid + "][订单ID=" + orderId + "]机器人失败: 机器人ID返回为空");
        }
 
        String endTimeStr = dto.getEndTime();
        if (StringUtil.isNullOrEmpty(endTimeStr)) {
            LogHelper.cloudInfo("方法openCloud: [uid=" + uid + "][订单ID=" + orderId + "]机器人失败: 返回时间为空");
        }
 
        long endTime = 0;
        try {
            endTime = Long.parseLong(endTimeStr);
        } catch (Exception e) {
            LogHelper.cloudInfo("方法openCloud: [uid=" + uid + "][订单ID=" + orderId + "]机器人失败: 返回时间格式不正确");
        }
 
        Integer groupNum = dto.getGroupNum();
        if (groupNum == null) {
            LogHelper.cloudInfo("方法openCloud: [uid=" + uid + "][订单ID=" + orderId + "]机器人失败: groupNum返回为空");
        }
 
        UserCloud newCloud = new UserCloud();
        newCloud.setUid(uid);
        newCloud.setOrderId(orderId);
        newCloud.setGroupNum(groupNum);
        newCloud.setRobotId(robotId);
        newCloud.setRobotType(menuEnum.getRobotType());
        if (renew) {
            newCloud.setWxId(userCloud.getWxId());
            newCloud.setWxName(userCloud.getWxName());
            newCloud.setWxPortrait(userCloud.getPortrait());
            newCloud.setStartTime(userCloud.getStartTime());
        } else {
            newCloud.setStartTime(new Date());
        }
        newCloud.setEndTime(new Date(endTime * 1000)); // Unix 转换 普通时间
        newCloud.setCreateTime(new Date());
        userCloudMapper.insertSelective(newCloud);
 
        // 开启发圈功能
        userCloudManageService.save(uid, null, null);
 
        try {
            String item = null;
            if (renew) {
                item = "成功续费" + menuEnum.getDescShow();
            } else {
                item = "成功开通" + menuEnum.getDescShow();
            }
            String desc = "完成充值支付" + BigDecimal.valueOf(menuEnum.getMoney()).setScale(2, BigDecimal.ROUND_DOWN) + "元";
            userOtherMsgNotificationService.cloudMsg(uid, "云发单充值", item, desc);
        } catch (Exception e) {
            LogHelper.errorDetailInfo(e);
        }
    }
 
    @Override
    public void searchGroup(Long uid) throws UserCloudException {
        UserCloud userCloud = userCloudMapper.getValidByUid(uid);
        if (userCloud == null)
            throw new UserCloudException(1, "云发单已过期");
 
        Integer robotId = userCloud.getRobotId();
        if (robotId == null)
            throw new UserCloudException(1, "云发单机器人不存在");
 
        List<String> list = AitaokerApiUtil.getContract(robotId);
        if (list == null || list.size() == 0)
            throw new UserCloudException(1, "未检索到对应群");
 
        String wxId = userCloud.getWxId();
        for (String roomId : list) {
            String key = RedisKeyEnum.cloudMatchGroup.getKey() + StringUtil.Md5(wxId + "_" + roomId);
            String result = redisManager.getCommonString(key);
            if (!StringUtil.isNullOrEmpty(result)) {
                String groupName = null;
                WeiXinGroupDTO groupDetail = AitaokerApiUtil.getGroupDetail(robotId, roomId);
                if (groupDetail != null) {
                    groupName = groupDetail.getGroupName();
                }
                userCloudGroupService.addGroup(uid, roomId, groupName, userCloud.getGroupNum());
            }
        }
    }
 
    @Override
    public void cacheMatchGroup(String wxId, String groupId) {
        if (StringUtil.isNullOrEmpty(wxId) || StringUtil.isNullOrEmpty(groupId))
            return;
        String key = RedisKeyEnum.cloudMatchGroup.getKey() + StringUtil.Md5(wxId + "_" + groupId);
        redisManager.cacheCommonString(key, "true", 60 * 20);
    }
 
    @Override
    public void sendByDynamic(Long uid, String id) throws UserCloudException {
        sendCircleByDynamic(uid, id, UserCloudSendRecord.SEND_WAY_MANUAL);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoSendByDynamic(Long uid, String id) {
        boolean official = false;
        UserCloudManage cloudManage = userCloudManageService.selectByPrimaryKey(uid);
        if (cloudManage != null) {
            if (cloudManage.getOfficial() != null)
                official = cloudManage.getOfficial();
        }
 
        if (!official)
            return;
 
        try {
            sendCircleByDynamic(uid, id, UserCloudSendRecord.SEND_WAY_AUTO);
        } catch (UserCloudException e) {
            LogHelper.cloudInfo("autoSendByDynamic - [uid:" + uid + " 动态id:" + id + "]原因:" + e.getMsg());
        }
    }
 
    private void sendCircleByDynamic(Long uid, String id, int way) throws UserCloudException {
        long time1 = java.lang.System.currentTimeMillis();
        UserInfo user = userInfoService.getUserByIdWithMybatis(uid);
        if (user == null)
            throw new UserCloudException(1, "用户信息不存在");
 
        if (user != null && user.getState() != UserInfo.STATE_NORMAL) {
            throw new UserCloudException(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC);
        }
 
        String inviteCode = userInfoExtraService.getInviteCodeByUid(uid);
        if (StringUtil.isNullOrEmpty(inviteCode))
            throw new UserCloudException(3, "邀请码未激活");
 
        UserExtraTaoBaoInfo taoBaoInfo = userExtraTaoBaoInfoService.getByUid(uid);
        String relationId = null;
        if (taoBaoInfo != null && taoBaoInfo.getRelationId() != null && taoBaoInfo.getRelationValid() != null
                && taoBaoInfo.getRelationValid() == true)
            relationId = taoBaoInfo.getRelationId();
 
        if (StringUtil.isNullOrEmpty(relationId))
            throw new UserCloudException(2, "淘宝未授权,请前往\"我的\"绑定淘宝账号");
 
        long time2 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByDynamic保验证用户状态:" + (time2 - time1));
 
 
        // 验证是否开通
        UserCloud userCloud = userCloudMapper.getValidByUid(uid);
        if (userCloud == null)
            throw new UserCloudException(1001, "云发单已过期");
 
        Integer robotId = userCloud.getRobotId();
        if (robotId == null)
            throw new UserCloudException(1002, "云发单机器人不存在");
 
        String wxId = userCloud.getWxId();
        if (StringUtil.isNullOrEmpty(wxId))
            throw new UserCloudException(1003, "微信号不存在,请先微信登录");
 
        long time3 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByDynamic验证是否满足开通:" + (time3 - time2));
 
 
        // 验证开启状态
        List<UserCloudGroup> listGroup = userCloudGroupService.listByUid(uid);
        if (listGroup == null || listGroup.size() == 0)
            throw new UserCloudException(1004, "请先微信登录");
 
        List<UserCloudGroup> listOpen = new ArrayList<>();
        for (UserCloudGroup cloudGrou : listGroup) {
            if (cloudGrou.getState()) {
                listOpen.add(cloudGrou);
            }
        }
        if (listOpen.size() == 0)
            throw new UserCloudException(1005, "请先开启云发单群功能");
 
        long time4 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByDynamic验证是否开启:" + (time4 - time3));
 
        // 验证发圈是否可行
        GoodsEvaluate evaluate = goodsEvaluateService.getById(id);
        if (evaluate == null || evaluate.getState() == 0)
            throw new UserCloudException(1, "该内容已下架");
 
        if (evaluate.getType() != EvaluateEnum.single && evaluate.getType() != EvaluateEnum.activity)
            throw new UserCloudException(1, "该内容不支持云发单");
 
        // 验证是否可转链
        List<CommentInfo> comments = evaluate.getComments();
        if (comments == null || comments.size() == 0)
            throw new UserCloudException(1, "该内容不能转链");
 
        long time5 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByDynamic验证发圈内容是否满足:" + (time5 - time4));
 
        // 检测微信是否登录状态
        if (!AitaokerApiUtil.onlineCheck(robotId)) {
            // 通知登录微信
            offlineNotification(uid);
 
            throw new UserCloudException(1003, "微信已掉线,需要重新扫描二维码登录");
        }
 
        long time6 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByDynamic验证发是否登录:" + (time6 - time5));
 
        boolean hasToken = false;
        List<String> listComment = new ArrayList<>();
        for (CommentInfo commentInfo : comments) {
            String comment = null;
            try {
                comment = convertLinkManager.convertLinkFromText(commentInfo.getContent(), uid, true,false);
                hasToken = true;
            } catch (ConvertLinkExceptionException e) {
                if (e.getCode() != ConvertLinkExceptionException.CODE_NONE) {
                    throw new UserCloudException(1, e.getMsg());
                }
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
                throw new UserCloudException(1, "该内容包含可转链口令或链接");
            }
 
            if (StringUtil.isNullOrEmpty(comment))
                comment = commentInfo.getContent();
 
            // 替换价格
            if (evaluate.getType() == EvaluateEnum.single) {
                GoodsDetailVO goods = evaluate.getGoods();
                comment = comment.replace("[原价]", MoneyBigDecimalUtil.getWithNoZera(goods.getZkPrice()) + "");
                if (!goods.isHasCoupon()) {
                    comment = comment.replace("领券抢购", "抢购");
                    comment = comment.replace("【券后价】[券后价]元", "");
                } else {
                    comment = comment.replace("[券后价]", MoneyBigDecimalUtil.getWithNoZera(goods.getCouponPrice()) + "");
                }
                comment = comment.replace("\r\n\r\n", "\r\n").replace("\r\n\r\n", "\r\n").replace("\r\n\r\n", "\r\n");
            }
 
            listComment.add(comment);
        }
 
        if (!hasToken)
            throw new UserCloudException(1, "该内容包含可转链口令或链接");
 
        // 异步执行发送
        executor.execute(new Runnable() {
            @Override
            public void run() {
                sendEvaluate(uid, evaluate, way, userCloud, listOpen, listComment);
            }
        });
    }
 
    private void sendEvaluate(Long uid, GoodsEvaluate evaluate, int way, UserCloud userCloud,
                              List<UserCloudGroup> listOpen, List<String> listComment) {
        ImgInfo imgVideo = null;
        List<String> listImg = new ArrayList<>();
 
        List<ImgInfo> imgs = evaluate.getImgList();
        if (imgs != null && imgs.size() > 0) {
            for (ImgInfo imgInfo : imgs) {
                if (imgInfo.getType() == ImgEnum.video) {
                    imgVideo = imgInfo;
                    continue;
                }
                listImg.add(imgInfo.getUrl());
            }
        }
 
 
        String wxId = userCloud.getWxId();
        Integer robotId = userCloud.getRobotId();
        // 保存发送记录
        UserCloudSendRecord sendRecord = new UserCloudSendRecord();
        sendRecord.setUid(uid);
        sendRecord.setSendId(evaluate.getId());
        sendRecord.setSendWay(way);
        sendRecord.setWxId(wxId);
        sendRecord.setRobotId(robotId);
        sendRecord.setSendTime(new Date());
        sendRecord.setSendOrigin(UserCloudSendRecord.ORIGIN_EVALUATE);
        UserCloudSendRecord result = userCloudSendRecordService.save(sendRecord);
        String pid = result.getId();
 
 
        for (UserCloudGroup cloudGroup : listOpen) {
            String title = evaluate.getTitle();
 
            UserCloudSendContent sendContent = new UserCloudSendContent();
            sendContent.setPid(pid);
            sendContent.setUid(uid);
            sendContent.setGroupId(cloudGroup.getGroupId());
            sendContent.setCreateTime(new Date());
 
            if (cloudGroup.getType() == UserCloudGroup.TYPE_CIRCLE) { // 朋友圈
                String circleId = null;
                sendContent.setType(UserCloudSendContent.TYPE_CIRCLE);
 
                if (imgVideo == null) {
 
                    // 发送图文
                    String picUrl = "";
                    if (listImg.size() > 0) {
                        for (String img : listImg) {
                            picUrl += img + ";";
                        }
                        if (picUrl.endsWith(";"))
                            picUrl = picUrl.substring(0, picUrl.length() - 1);
                    }
                    String picUrlUpload = AitaokerApiUtil.macsendUpload(robotId, picUrl);
                    sendContent.setPicUrlUpload(picUrlUpload);
                    sendContent.setTitle(title);
                    sendContent.setPicUrl(picUrl);
                    circleId = AitaokerApiUtil.macsendCircle(robotId, title, picUrlUpload);
                } else {
                    // 发送视频
                    sendContent.setPicUrl(imgVideo.getUrl());
                    sendContent.setVideoUrl(imgVideo.getVideoUrl());
                    circleId = AitaokerApiUtil.macsendCircleVideo(robotId, imgVideo.getVideoUrl(), imgVideo.getUrl());
                }
 
                // 评论文本
                if (!StringUtil.isNullOrEmpty(circleId)) {
                    sendContent.setState(true);
                    List<String> list = new ArrayList<>();
                    for (String comment : listComment) {
                        boolean macsend = AitaokerApiUtil.macsendCircleComment(robotId, wxId, circleId, comment);
                        if (macsend) {
                            list.add(comment);
                        }
                    }
                    sendContent.setComments(list);
                }
            } else { // 群
                sendContent.setType(UserCloudSendContent.TYPE_GROUP);
 
                // 发送文本
                if (!StringUtil.isNullOrEmpty(title)) {
                    boolean macsend = AitaokerApiUtil.macsendText(robotId, cloudGroup.getGroupId(), title);
                    if (macsend)
                        sendContent.setTitle(title);
                }
                SystemEnum system = userInfoService.getUserSystem(uid);
                // 发送图片
                int num = 1;
                String picNum = configService.getValue(ConfigKeyEnum.robotCloudGroupPictureNum.getKey(), system);
                if (!StringUtil.isNullOrEmpty(picNum)) {
                    num = Integer.parseInt(picNum);
                }
 
                if (listImg.size() > 0)
                    for (int i = 0; i < num && i < listImg.size(); i++) {
                        try {
                            String imgBase64 = ImageToBase64.NetImageToBase64(listImg.get(i));
                            boolean macsend = AitaokerApiUtil.macsendImgBase64(robotId, cloudGroup.getGroupId(),
                                    imgBase64);
                            if (macsend)
                                sendContent.setPicUrl(listImg.get(i));
                        } catch (Exception e) {
                            LogHelper.errorDetailInfo(e);
                        }
                    }
 
                // 评论文本
                List<String> list = new ArrayList<>();
                for (String comment : listComment) {
                    boolean macsend = AitaokerApiUtil.macsendText(robotId, cloudGroup.getGroupId(), comment);
                    if (macsend) {
                        list.add(comment);
                    }
                }
                sendContent.setState(true);
                sendContent.setComments(list);
            }
            userCloudSendContentService.save(sendContent);
        }
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendCustomGoods(Long uid, Long goodsId, Integer goodsType, Long sellerId) throws UserCloudException {
        sendCircleByGoods(uid, goodsId, goodsType, null, sellerId, UserCloudSendRecord.SEND_WAY_MANUAL);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoSendCustomGoods(Long uid, Long id) {
        boolean custom = false;
        UserCloudManage cloudManage = userCloudManageService.selectByPrimaryKey(uid);
        if (cloudManage != null) {
            if (cloudManage.getCustom() != null)
                custom = cloudManage.getCustom();
        }
 
        if (!custom) {
            return;
        }
 
        UserCloudGoods cloudGoods = userCloudGoodsService.selectByPrimaryKey(id);
        if (cloudGoods == null) {
            return;
        }
        CommonGoods cgoods = cloudGoods.getCommonGoods();
        if (cgoods == null)
            return;
 
        try {
            // 发送商品
            sendCircleByGoods(uid, cgoods.getGoodsId(), cgoods.getGoodsType(), id, cgoods.getSellerId(),
                    UserCloudSendRecord.SEND_WAY_AUTO);
        } catch (UserCloudException e) {
            LogHelper.cloudInfo("autoSendCustomGoods - [uid:" + uid + " 库id:" + id + "]原因:" + e.getMsg());
        }
    }
 
    private void sendCircleByGoods(Long uid, Long goodsId, Integer goodsType, Long storeId, Long sellerId, int way)
            throws UserCloudException {
        long begainTime = java.lang.System.currentTimeMillis();
 
        // 验证是否授权
        UserInfo user = userInfoService.getUserByIdWithMybatis(uid);
        if (user == null)
            throw new UserCloudException(1, "用户信息不存在");
 
        if (user != null && user.getState() != UserInfo.STATE_NORMAL) {
            throw new UserCloudException(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC);
        }
 
        String inviteCode = userInfoExtraService.getInviteCodeByUid(uid);
        if (StringUtil.isNullOrEmpty(inviteCode))
            throw new UserCloudException(3, "邀请码未激活");
 
        UserExtraTaoBaoInfo taoBaoInfo = userExtraTaoBaoInfoService.getByUid(uid);
        String relationId = null;
        if (taoBaoInfo != null && taoBaoInfo.getRelationId() != null && taoBaoInfo.getRelationValid() != null
                && taoBaoInfo.getRelationValid() == true)
            relationId = taoBaoInfo.getRelationId();
 
        if (StringUtil.isNullOrEmpty(relationId))
            throw new UserCloudException(2, "淘宝未授权,请前往\"我的\"绑定淘宝账号");
 
        long time2 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByGoods验证用户耗时:" + (time2 - begainTime));
 
 
        // 验证是否开通
        UserCloud userCloud = userCloudMapper.getValidByUid(uid);
        if (userCloud == null)
            throw new UserCloudException(1001, "云发单已过期");
 
        long time3 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByGoods验证是否开通:" + (time3 - time2));
 
        long time4 = time3;
        // 加入我的备选库
        if (storeId == null) {
            try {
                UserCloudGoods cloudGoods = userCloudGoodsService.addGoods(uid, goodsId, goodsType, sellerId);
                if (cloudGoods != null)
                    storeId = cloudGoods.getId();
            } catch (UserCloudGoodsException e) {
                LogHelper.cloudInfo("sendCustomGoods - [uid:" + uid + "goodsId:" + goodsId + "goodsType" + goodsType
                        + "]原因:" + e.getMsg());
                throw new UserCloudException(1, "加入云发单备选库失败");
            }
            time4 = java.lang.System.currentTimeMillis();
            LogHelper.test("sendCircleByGoods加入备选库:" + (time4 - time3));
        }
 
        // 自选库商品是否打开
        boolean custom = false;
        UserCloudManage cloudManage = userCloudManageService.selectByPrimaryKey(uid);
        if (cloudManage != null) {
            if (cloudManage.getCustom() != null)
                custom = cloudManage.getCustom();
        }
        if (!custom) {
            return;
        }
 
        Integer robotId = userCloud.getRobotId();
        if (robotId == null)
            throw new UserCloudException(1, "云发单机器人不存在");
 
        String wxId = userCloud.getWxId();
        if (StringUtil.isNullOrEmpty(wxId))
            throw new UserCloudException(1002, "请先登录微信");
 
        // 验证开启状态
        List<UserCloudGroup> listGroup = userCloudGroupService.listByUid(uid);
        if (listGroup == null || listGroup.size() == 0)
            throw new UserCloudException(1003, "请先登录微信");
 
        long time5 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByGoods验证是否绑定微信:" + (time5 - time4));
 
        List<UserCloudGroup> listOpen = new ArrayList<>();
        for (UserCloudGroup cloudGrou : listGroup) {
            if (cloudGrou.getState()) {
                listOpen.add(cloudGrou);
            }
        }
 
        if (listOpen.size() == 0)
            throw new UserCloudException(1004, "请先开启云发单群功能");
 
        // 检测微信是否登录状态
        if (!AitaokerApiUtil.onlineCheck(robotId)) {
            // 通知登录微信
            offlineNotification(uid);
 
            throw new UserCloudException(1003, "微信已掉线,需要重新扫描二维码登录");
        }
 
        long time6 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByGoods验证是否登录微信:" + (time6 - time5));
 
        // 保存发送记录
        UserCloudSendRecord sendRecord = new UserCloudSendRecord();
        sendRecord.setUid(uid);
        sendRecord.setGoodsId(goodsId + "");
        sendRecord.setGoodsType(goodsType + "");
        sendRecord.setWxId(wxId);
        sendRecord.setRobotId(robotId);
        sendRecord.setSendTime(new Date());
        if (storeId != null) {
            sendRecord.setSendId(storeId + "");
            sendRecord.setSendOrigin(UserCloudSendRecord.ORIGIN_STORE);
            sendRecord.setSendWay(UserCloudSendRecord.SEND_WAY_AUTO);
        } else {
            sendRecord.setSendWay(UserCloudSendRecord.SEND_WAY_MANUAL);
        }
        UserCloudSendRecord result = userCloudSendRecordService.save(sendRecord);
 
        long time7 = java.lang.System.currentTimeMillis();
        LogHelper.test("sendCircleByGoods保存发送记录:" + (time7 - time6));
 
        try {
            if (goodsType == Constant.SOURCE_TYPE_TAOBAO) {
                sendTaoBaoGoods(user, robotId, wxId, goodsId, relationId, listOpen, result.getId());
            } else if (goodsType == Constant.SOURCE_TYPE_JD) {
                sendJDGoods(user, robotId, wxId, goodsId, relationId, listOpen, result.getId());
            } else if (goodsType == Constant.SOURCE_TYPE_PDD) {
                sendPDDGoods(user, robotId, wxId, goodsId, relationId, listOpen, result.getId());
            } else if (goodsType == Constant.SOURCE_TYPE_VIP) {
                sendVIPGoods(user, robotId, wxId, goodsId, relationId, listOpen, result.getId());
            } else if (goodsType == Constant.SOURCE_TYPE_SUNING) {
                sendSuNingGoods(user, robotId, wxId, goodsId, sellerId, relationId, listOpen, result.getId());
            }
            // 更新发单记录
            if (storeId != null) {
                UserCloudGoods record = new UserCloudGoods();
                record.setId(storeId);
                record.setState(UserCloudGoods.STATE_SHARED);
                record.setSendTime(new Date());
                record.setUpdateTime(new Date());
                userCloudGoodsService.updateByPrimaryKeySelective(record);
            }
            long time8 = java.lang.System.currentTimeMillis();
            LogHelper.test("sendCircleByGoods执行发送:" + (time8 - time7));
        } catch (UserCloudException e) {
            LogHelper.cloudInfo("autoSendCustomGoods - [uid:" + uid + " 库id:" + storeId + "]原因:" + e.getMsg());
            // 更新发单记录
            if (storeId != null) {
                UserCloudGoods record = new UserCloudGoods();
                record.setId(storeId);
                record.setState(UserCloudGoods.STATE_INVALID);
                record.setSendTime(new Date());
                record.setUpdateTime(new Date());
                userCloudGoodsService.updateByPrimaryKeySelective(record);
            }
        }
 
    }
 
    /**
     * 淘宝商品信息处理
     *
     * @param user
     * @param robotId
     * @param wxId
     * @param goodsId
     * @param relationId
     * @param listOpen
     * @throws UserCloudException
     */
    private void sendTaoBaoGoods(UserInfo user, int robotId, String wxId, Long goodsId, String relationId,
                                 List<UserCloudGroup> listOpen, String pid) throws UserCloudException {
        TaoBaoLink taoBaoLink = null;
        try {
            taoBaoLink = taoBaoLinkManager.getTaoBaoLinkForShare(user.getId(), goodsId, relationId, null);
        } catch (TaoBaoConvertLinkException e) {
            LogHelper.errorDetailInfo(e);
            throw new UserCloudException(1, "该商品已下架");
        }
        if (taoBaoLink == null)
            throw new UserCloudException(1, "该商品已下架");
 
        TaoBaoGoodsBrief goods = taoBaoLink.getGoods();
        boolean coupon = false;
        if (!StringUtil.isNullOrEmpty(goods.getCouponInfo())) {
            coupon = true;
        }
 
        String quanPrice = "";
        String description = "";
        String couponAmount = "";
        if (coupon) {
            description = goods.getDescription();
            quanPrice = TaoBaoUtil.getAfterUseCouplePrice(goods) + "";
            couponAmount = MoneyBigDecimalUtil.getWithNoZera(goods.getCouponAmount()).toString();
        }
        String sales = TaoBaoUtil.getSaleCount(goods.getBiz30day());
 
        SystemEnum system = userInfoService.getUserSystem(user.getId());
 
        // 获取推荐语
        String recommendText = shareGoodsTextTemplateService.getRecommendText(coupon, goods.getTitle(), sales,
                couponAmount, description, system);
        // 获取评论语
        String commentText = shareGoodsTextTemplateService.getCommentTextByTaoToken(coupon, taoBaoLink.getTaoToken(),
                goods.getZkPrice().toString(), quanPrice, system);
 
        // 异步执行发送
        executor.execute(new Runnable() {
            @Override
            public void run() {
                sendGoods(robotId, wxId, listOpen, recommendText, commentText, goods.getImgList(), user.getId(), pid);
            }
        });
    }
 
    /**
     * 京东商品云发单
     *
     * @param user
     * @param robotId
     * @param wxId
     * @param goodsId
     * @param relationId
     * @param listOpen
     * @throws UserCloudException
     */
    private void sendJDGoods(UserInfo user, int robotId, String wxId, Long goodsId, String relationId,
                             List<UserCloudGroup> listOpen, String pid) throws UserCloudException {
        JDGoods jdGoods = jdGoodsCacheUtil.getGoodsInfo(goodsId);
        if (jdGoods == null)
            throw new UserCloudException(1, "该商品已下架");
 
        String couponUrl = null;
        JDCouponInfo couponInfo = JDUtil.getShowCouponInfo(jdGoods);
        if (couponInfo != null) {
            couponUrl = couponInfo.getLink();
        }
        String materialId = "https://item.jd.com/" + goodsId + ".html";
        String jumpLink = JDApiUtil.convertLinkWithSubUnionId(materialId, couponUrl, null,JDApiUtil.POSITION_SHARE + "",
                user.getId() + "");
 
        boolean coupon = false;
        if (couponInfo != null) {
            coupon = true;
        }
 
        String quanPrice = "";
        String couponAmount = "";
        if (coupon) {
            quanPrice = BigDecimalUtil.getWithNoZera(JDUtil.getQuanPrice(jdGoods)).toString() + "";
            couponAmount = BigDecimalUtil.getWithNoZera(couponInfo.getDiscount()).toString();
        }
 
        String sales = JDUtil.getSaleCount(jdGoods.getInOrderCount30Days());
 
        SystemEnum system = userInfoService.getUserSystem(user.getId());
 
        // 获取推荐语
        String recommendText = shareGoodsTextTemplateService.getRecommendText(coupon, jdGoods.getSkuName(), sales,
                couponAmount, null, system);
 
        // 获取评论语
        BigDecimal price = jdGoods.getPrice();
        JDPingouInfo pinGouInfo = jdGoods.getPinGouInfo();
        if (pinGouInfo != null) {
            price = pinGouInfo.getPingouPrice();
        }
        String zkPrice = BigDecimalUtil.getWithNoZera(price).toString();
        String commentText = shareGoodsTextTemplateService.getCommentTextByLink(coupon, jumpLink, zkPrice, quanPrice,
                ConfigKeyEnum.quickShareJDCommentText, system);
 
        // 异步执行发送
        executor.execute(new Runnable() {
            @Override
            public void run() {
                sendGoods(robotId, wxId, listOpen, recommendText, commentText, jdGoods.getImageList(), user.getId(), pid);
            }
        });
 
    }
 
    /**
     * 京东商品云发单
     *
     * @param user
     * @param robotId
     * @param wxId
     * @param goodsId
     * @param relationId
     * @param listOpen
     * @throws UserCloudException
     */
    private void sendPDDGoods(UserInfo user, int robotId, String wxId, Long goodsId, String relationId,
                              List<UserCloudGroup> listOpen, String pid) throws UserCloudException {
        PDDGoodsDetail goods = pinDuoDuoCacheUtil.getGoodsInfo(goodsId);
        if (goods == null)
            throw new UserCloudException(1, "该商品已下架");
 
        String jumpLink = PinDuoDuoApiUtil.getPromotionUrl(goodsId, PinDuoDuoApiUtil.PID_SHARE + "", user.getId() + "");
 
        boolean coupon = true;
        if (goods.getHasCoupon() == null || !goods.getHasCoupon()) {
            coupon = false;
        }
 
        String quanPrice = "";
        String couponAmount = "";
        if (coupon) {
            BigDecimal hundred = new BigDecimal(100);
            BigDecimal amount = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponDiscount()), hundred);
            quanPrice = BigDecimalUtil.getWithNoZera(amount).toString();
            couponAmount = BigDecimalUtil.getWithNoZera(PinDuoDuoUtil.getQuanPrice(goods)).toString();
        }
 
        String sales = goods.getSalesTip();
        if (StringUtil.isNullOrEmpty(sales)) {
            sales = "0";
        }
 
        SystemEnum system = userInfoService.getUserSystem(user.getId());
 
        // 获取推荐语
        String recommendText = shareGoodsTextTemplateService.getRecommendText(coupon, goods.getGoodsName(), sales,
                couponAmount, null, system);
 
        // 获取评论语
        String zkPrice = MoneyBigDecimalUtil.div(new BigDecimal(goods.getMinGroupPrice()), new BigDecimal(100))
                .setScale(2).toString();
        String commentText = shareGoodsTextTemplateService.getCommentTextByLink(coupon, jumpLink, zkPrice, quanPrice,
                ConfigKeyEnum.quickSharePDDCommentText, system);
 
        List<String> list = null;
        String[] goodsGalleryUrls = goods.getGoodsGalleryUrls();
        if (goodsGalleryUrls != null && goodsGalleryUrls.length > 0) {
            list = Arrays.asList(goodsGalleryUrls);
        }
 
        List<String> list2 = list;
        // 异步执行发送
        executor.execute(new Runnable() {
            @Override
            public void run() {
                sendGoods(robotId, wxId, listOpen, recommendText, commentText, list2, user.getId(), pid);
            }
        });
 
    }
 
    /**
     * 唯品会商品
     *
     * @param user
     * @param robotId
     * @param wxId
     * @param goodsId
     * @param relationId
     * @param listOpen
     * @param pid
     * @throws UserCloudException
     */
    private void sendVIPGoods(UserInfo user, int robotId, String wxId, Long goodsId, String relationId,
                              List<UserCloudGroup> listOpen, String pid) throws UserCloudException {
        VIPGoodsInfo goods = VipShopApiUtil.getGoodsDetail(goodsId + "");
        if (goods == null)
            throw new UserCloudException(1, "该商品已下架");
 
        VIPConvertResultDTO resultDTO = VipShopApiUtil.convertLink(goodsId + "",
                VipShopUtil.getShareChanTag(user.getId()));
        String jumpLink = resultDTO.getUrl();
 
        boolean coupon = false;
        String quanPrice = "";
        String couponAmount = "";
        SystemEnum system = userInfoService.getUserSystem(user.getId());
        // 获取推荐语
        String recommendText = shareGoodsTextTemplateService.getRecommendText(coupon, goods.getGoodsName(), null,
                couponAmount, null, system);
        // 获取评论语
        String commentText = shareGoodsTextTemplateService.getCommentTextByLink(coupon, jumpLink,
                goods.getMarketPrice(), quanPrice, ConfigKeyEnum.quickShareVIPCommentText, system);
 
        // 异步执行发送
        executor.execute(new Runnable() {
            @Override
            public void run() {
                sendGoods(robotId, wxId, listOpen, recommendText, commentText, goods.getGoodsDetailPictures(), user.getId(),
                        pid);
            }
        });
    }
 
    /**
     * 京东商品云发单
     *
     * @param user
     * @param robotId
     * @param wxId
     * @param goodsId
     * @param relationId
     * @param listOpen
     * @throws UserCloudException
     */
    private void sendSuNingGoods(UserInfo user, int robotId, String wxId, Long goodsId, Long sellerId,
                                 String relationId, List<UserCloudGroup> listOpen, String pid) throws UserCloudException {
        SuningGoodsInfo goods = SuningApiUtil.getGoodsDetail(goodsId + "", sellerId + "");
        if (goods == null)
            throw new UserCloudException(1, "该商品已下架");
 
        String couponLink = goods.getCouponInfo().getCouponUrl();
        String jumpLink = SuningApiUtil.convertLink(SuningUtil.getProductUrl(sellerId + "", goodsId + ""),
                StringUtil.isNullOrEmpty(couponLink) ? null : couponLink, SuningApiUtil.PID_SHARE, user.getId() + "");
 
        boolean coupon = false;
        String couponAmount = "";
        String sales = null;
        if (goods.getCouponInfo() != null && !StringUtil.isNullOrEmpty(goods.getCouponInfo().getCouponUrl())) {// 有券
            couponAmount = new BigDecimal(goods.getCouponInfo().getCouponValue()).toString();
            coupon = true;
        }
 
        SystemEnum system = userInfoService.getUserSystem(user.getId());
 
        // 获取推荐语
        String recommendText = shareGoodsTextTemplateService.getRecommendText(coupon,
                goods.getCommodityInfo().getCommodityName(), sales, couponAmount, null, system);
 
        // 生成快捷分享内容
        String template = configService.getValue(ConfigKeyEnum.quickShareSuNingCommentText.getKey(), system);
        String commentText = shareGoodsTextTemplateService.createQuickShareTextSuNing(template, goods, jumpLink);
 
        List<String> imgList = new ArrayList<>();
        for (SuningGoodsImg img : goods.getCommodityInfo().getPictureUrl()) {
            imgList.add(img.getPicUrl());
        }
 
        executor.execute(new Runnable() {
            @Override
            public void run() {
                // 云发单
                sendGoods(robotId, wxId, listOpen, recommendText, commentText, imgList, user.getId(), pid);
            }
        });
    }
 
    /**
     * 发送商品
     *
     * @param robotId
     * @param title
     * @param comment
     * @param listImg
     * @param wxId
     * @param listOpen
     */
    private void sendGoods(int robotId, String wxId, List<UserCloudGroup> listOpen, String title, String comment,
                           List<String> listImg, Long uid, String pid) {
        // 遍历群-朋友圈
        for (UserCloudGroup cloudGroup : listOpen) {
            UserCloudSendContent sendContent = new UserCloudSendContent();
            sendContent.setPid(pid);
            sendContent.setUid(uid);
            sendContent.setGroupId(cloudGroup.getGroupId());
            sendContent.setCreateTime(new Date());
 
            if (cloudGroup.getType() == UserCloudGroup.TYPE_CIRCLE) { // 朋友圈
                sendContent.setType(UserCloudSendContent.TYPE_CIRCLE);
                String picUrl = "";
                if (listImg.size() > 0) {
                    for (String img : listImg) {
                        picUrl += TbImgUtil.getTBSize220Img(img) + ";";
                    }
                    if (picUrl.endsWith(";"))
                        picUrl = picUrl.substring(0, picUrl.length() - 1);
                }
 
                String picUrlUpload = AitaokerApiUtil.macsendUpload(robotId, picUrl);
                sendContent.setPicUrlUpload(picUrlUpload);
                sendContent.setTitle(title);
                sendContent.setPicUrl(picUrl);
                // 发圈内容
                String circleId = AitaokerApiUtil.macsendCircle(robotId, title, picUrlUpload);
                // 评论文本
                if (!StringUtil.isNullOrEmpty(circleId)) {
                    sendContent.setState(true);
                    List<String> list = new ArrayList<>();
                    boolean macsend = AitaokerApiUtil.macsendCircleComment(robotId, wxId, circleId, comment);
                    if (macsend) {
                        list.add(comment);
                    }
                    sendContent.setComments(list);
                }
            } else {
                sendContent.setType(UserCloudSendContent.TYPE_GROUP);
                // 发送文本
                if (!StringUtil.isNullOrEmpty(title)) {
                    boolean macsend = AitaokerApiUtil.macsendText(robotId, cloudGroup.getGroupId(), title);
                    if (macsend)
                        sendContent.setTitle(title);
                }
                SystemEnum system = userInfoService.getUserSystem(uid);
                // 发送图片
                int num = 1;
                String picNum = configService.getValue(ConfigKeyEnum.robotCloudGroupPictureNum.getKey(), system);
                if (!StringUtil.isNullOrEmpty(picNum)) {
                    num = Integer.parseInt(picNum);
                }
 
                if (listImg.size() > 0)
                    for (int i = 0; i < num && i < listImg.size(); i++) {
                        try {
                            String imgBase64 = ImageToBase64.NetImageToBase64(listImg.get(i));
                            boolean macsend = AitaokerApiUtil.macsendImgBase64(robotId, cloudGroup.getGroupId(),
                                    imgBase64);
                            if (macsend)
                                sendContent.setPicUrl(listImg.get(i));
                        } catch (Exception e) {
                            LogHelper.errorDetailInfo(e);
                        }
                    }
 
                // 评论文本
                List<String> list = new ArrayList<>();
                boolean macsend = AitaokerApiUtil.macsendText(robotId, cloudGroup.getGroupId(), comment);
                if (macsend) {
                    list.add(comment);
                }
                sendContent.setState(true);
                sendContent.setComments(list);
            }
            userCloudSendContentService.save(sendContent);
        }
    }
 
    @Override
    public void fixedTimeSend(List<GoodsEvaluate> listActivity, List<GoodsEvaluate> listGoods, boolean timeLimit) {
        if (listGoods == null && listActivity == null)
            return;
        // 一个小时之前
        Date lastTime = new Date(java.lang.System.currentTimeMillis() - 1000 * 60 * 60);
        for (int i = 0; i < 1000; i++) {
            // 查询哪些用户开通
            List<Long> listUser = userCloudMapper.listValidUid(i * 1000, 1000);
            if (listUser == null || listUser.size() == 0) {
                break;
            }
 
            // 遍历用户
            for (Long uid : listUser) {
                try {// 判断是否开通官方采集
                    UserCloudManage cloudManage = userCloudManageService.selectByPrimaryKey(uid);
                    if (cloudManage == null || cloudManage.getOfficial() == null || !cloudManage.getOfficial()) {
                        continue;
                    }
 
                    // 时间间隔:是否在一个小时内已发送过
                    if (timeLimit) {
                        UserCloudSendRecord last = userCloudSendRecordService.getLastByUid(uid, lastTime);
                        if (last != null)
                            continue;
                    }
 
 
                    String evaluateId = null;
                    // 活动
                    if (listActivity != null && listActivity.size() > 0) {
                        for (GoodsEvaluate evaluate : listActivity) {
                            UserCloudSendRecord record = userCloudSendRecordService.getByUidAndSendId(uid,
                                    evaluate.getId());
                            if (record != null)
                                continue;
 
                            evaluateId = evaluate.getId();
                            break;
                        }
                    }
                    // 单品
                    if (StringUtil.isNullOrEmpty(evaluateId) && listGoods != null && listGoods.size() > 0) {
                        for (GoodsEvaluate evaluate : listGoods) {
                            UserCloudSendRecord record = userCloudSendRecordService.getByUidAndSendId(uid,
                                    evaluate.getId());
                            if (record != null)
                                continue;
 
                            evaluateId = evaluate.getId();
                            break;
                        }
                    }
 
                    if (!StringUtil.isNullOrEmpty(evaluateId)) {
                        UserCloudMQMsg msg = new UserCloudMQMsg(uid, evaluateId, UserCloudMQMsg.TYPE_EVALUATE);
                        Message message = MQMsgBodyFactory.create(MQTopicName.TOPIC_USER, UserTopicTagEnum.userCloud,
                                msg);
                        rocketMQManager.sendNormalMsg(message, null);
                    }
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
            }
        }
    }
 
    private void offlineNotification(Long uid) {
        UserCloudManage cloudManage = userCloudManageService.selectForUpdate(uid);
        if (cloudManage == null) {
            return;
        }
 
        Boolean offlineNotice = cloudManage.getOfflineNotice();
        if (offlineNotice != null && offlineNotice) {
            return;
        }
 
        try {
            userOtherMsgNotificationService.cloudMsg(uid, "云发单微信账号", "微信账号掉线", "需要你重新扫描二维码登录");
        } catch (Exception e) {
            LogHelper.errorDetailInfo(e);
        }
 
        // 站内信通知
        offlineNotificationZNX(uid);
 
        // 延迟10分钟再次提醒
        if (!Constant.IS_TEST) {
            UserCloudMQMsg msg = new UserCloudMQMsg(uid, UserCloudMQMsg.TYPE_PUSH);
            Message message = MQMsgBodyFactory.create(MQTopicName.TOPIC_USER, UserTopicTagEnum.userCloud, msg);
            message.setStartDeliverTime(java.lang.System.currentTimeMillis() + 1000 * 60 * 10);
            rocketMQManager.sendNormalMsg(message, null);
        }
 
        // 更新已提醒
        UserCloudManage updateManage = new UserCloudManage();
        updateManage.setId(uid);
        updateManage.setOfflineNotice(true);
        userCloudManageService.updateByPrimaryKeySelective(updateManage);
    }
 
    // 站内信通知
    @Override
    public void offlineNotificationZNX(Long uid) {
        // 验证是否开通
        UserCloud userCloud = userCloudMapper.getValidByUid(uid);
        if (userCloud == null)
            return;
 
        Integer robotId = userCloud.getRobotId();
        if (robotId == null)
            return;
 
        // 登录状态
        if (AitaokerApiUtil.onlineCheck(robotId)) {
            return;
        }
 
        SystemEnum system = userInfoService.getUserSystem(uid);
 
        try {
            pushService.pushZNX(uid, "【重要通知】你的云发单微信已掉线。", "需要你重新扫描二维码登录", null, null, system);
        } catch (Exception e) {
            LogHelper.errorDetailInfo(e);
        }
    }
 
}