liujie
2026-06-09 c96fbe6b0aeb413a17c429133ee6d81d138144b9
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
package com.xiaopeng.operation.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaopeng.api.dto.account.UcUserInfo;
import com.xiaopeng.api.dto.operation.SmsDto;
import com.xiaopeng.api.dto.operation.XpActivityDto;
import com.xiaopeng.api.feignClient.account.UserResourcesClient;
import com.xiaopeng.api.feignClient.account.XpAppUserCouponClient;
import com.xiaopeng.api.feignClient.operation.SmsClient;
import com.xiaopeng.api.feignClient.operation.XpCouponClient;
import com.xiaopeng.api.feignClient.order.XpOrderClient;
import com.xiaopeng.api.feignClient.pushMessage.SubscribeMessageClient;
import com.xiaopeng.api.model.account.XpAppUserCoupon;
import com.xiaopeng.api.model.operation.*;
import com.xiaopeng.api.query.operation.XpActivityPageListQuery;
import com.xiaopeng.api.vo.account.AppUserCouponSaveBatchVo;
import com.xiaopeng.api.vo.operation.SmsVo;
import com.xiaopeng.api.vo.pushMessage.SendCouponMessageVo;
import com.xiaopeng.api.vo.pushMessage.SendSubscribeMessageVo;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.common.core.enums.MessageTemplateEnum;
import com.xiaopeng.common.core.utils.bean.BeanUtils;
import com.xiaopeng.common.core.web.page.PageInfo;
import com.xiaopeng.operation.mapper.XpActicityMapper;
import com.xiaopeng.operation.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 活动管理 服务实现类
 * </p>
 *
 * @author mitao
 * @since 2026-02-03
 */
@Slf4j
@Service
public class XpActicityServiceImpl extends ServiceImpl<XpActicityMapper, XpActivity> implements IXpActicityService {
 
    @Resource
    private IXpActicityStrategyService strategyService;
 
    @Resource
    private IXpActicityUserService userService;
 
    @Resource
    private XpOrderClient xpOrderClient;
 
    @Resource
    private IXpActicityStrategyService xpActicityStrategyService;
 
    @Resource
    private IXpActicityService xpActicityService;
 
    @Resource
    private IXpActicityUserService xpActicityUserService;
 
    @Resource
    private IXpWhitelistService xpWhitelistService;
 
    @Resource
    private IXpActicityCouponService xpActicityCouponService;
 
    @Resource
    private IXpCouponService xpCouponService;
 
    @Resource
    private XpAppUserCouponClient xpAppUserCouponClient;
 
    @Resource
    private UserResourcesClient userResourcesClient;
 
    @Resource
    private SubscribeMessageClient subscribeMessageClient;
 
    @Resource
    private XpCouponClient xpCouponClient;
 
    @Resource
    private SmsClient smsClient;
 
    @Value("${sms.appid:1476153389173952512}")
    private String sms_appid;
 
    private static final ThreadPoolExecutor RETRY_EXECUTOR = new ThreadPoolExecutor(
            4,
            16,
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(512),
            new ThreadFactory() {
                private final AtomicInteger counter = new AtomicInteger(0);
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r, "route-push-retry-" + counter.incrementAndGet());
                    t.setDaemon(true);
                    return t;
                }
            },
            new ThreadPoolExecutor.CallerRunsPolicy()
    );
 
 
 
    @Override
    public PageInfo<XpActivityDto> pageList(XpActivityPageListQuery query) {
        PageInfo<XpActivityDto> pageInfo = new PageInfo<>(query.getPageNum(),query.getPageSize());
        List<XpActivityDto> list = this.baseMapper.pageList(pageInfo,query);
        pageInfo.setRecords(list);
        return pageInfo;
    }
 
    @Override
    public List<String> findListToIds(String acticityName){
        LambdaQueryWrapper<XpActivity> query = new LambdaQueryWrapper<>();
        query.select(XpActivity::getId);
        query.eq(XpActivity::getDeleted, 0);
        query.like(XpActivity::getActicityName, acticityName);
        return listObjs(query, Object::toString);
    }
 
    @Override
    public List<XpActivity> activiting(Long uid) {
        //获取当前用户可参与的活动
        List<Integer> actitctiyIds = new ArrayList<>();
        //全部用户
        List<XpActicityUser> list = userService.list(new QueryWrapper<XpActicityUser>().eq("is_deleted", 0).eq("user_type", 1));
        actitctiyIds.addAll(list.stream().map(XpActicityUser::getActitcityId).collect(Collectors.toList()));
        //判断用户类型 2=老用户,3=新用户,4=流失用户
        Integer userType = xpOrderClient.determineUserType(uid).getData();
        list = userService.list(new QueryWrapper<XpActicityUser>().eq("is_deleted", 0).eq("user_type", userType));
        actitctiyIds.addAll(list.stream().map(XpActicityUser::getActitcityId).collect(Collectors.toList()));
        //指定用户
        list = userService.list(new QueryWrapper<XpActicityUser>().eq("is_deleted", 0).eq("user_type", 5)
                .last("  and JSON_CONTAINS(user_list, '" + uid + "', '$')"));
        actitctiyIds.addAll(list.stream().map(XpActicityUser::getActitcityId).collect(Collectors.toList()));
 
        List<XpActivity> one = this.list(new QueryWrapper<XpActivity>().eq("status", 2).eq("is_deleted", 0)
                .eq("mini_program_notification", 1).in(!actitctiyIds.isEmpty(), "id", actitctiyIds)
                .last(" and now() between start_time and end_time"));
        return one;
    }
 
    @Override
    public void save(XpActivityDto dto) {
 
        XpActivity activity = new XpActivity();
        BeanUtils.copyBeanProp(activity, dto);
        activity.setActicityType(dto.getActivityType());
        activity.setAggregateLimit(dto.getEnableTotalLimit() ? 1 : 0);
        activity.setLimitation(dto.getTotalLimit());
        activity.setCoverImage(dto.getImg());
        activity.setRemarks(dto.getRichText());
        save(activity);
 
        List<XpActicityStrategy> strategy = dto.getStrategy();
        List<XpActicityUser> activityUser = dto.getActivityUser();
        for (XpActicityStrategy xpActicityStrategy : strategy) {
            xpActicityStrategy.setActitcityId(activity.getId().intValue());
            xpActicityStrategy.setDeleted(false);
            strategyService.save(xpActicityStrategy);
 
            List<Long> couponIds = xpActicityStrategy.getCouponIds();
            for (Long couponId : couponIds) {
                XpActicityCoupon xpActicityCoupon = new XpActicityCoupon();
                xpActicityCoupon.setActicityStrategyId(xpActicityStrategy.getId().longValue());
                xpActicityCoupon.setCouponId(couponId);
                xpActicityCoupon.setActivityId(activity.getId());
                xpActicityCouponService.save(xpActicityCoupon);
            }
 
        }
        Map<String, XpActicityStrategy> strategyMap = strategy.stream().collect(Collectors.toMap(
                XpActicityStrategy::getName,
                Function.identity()
        ));
        for (XpActicityUser xpActicityUser : activityUser) {
            xpActicityUser.setActitcityId(activity.getId().intValue());
            xpActicityUser.setActitcityStrategeId(strategyMap.get(xpActicityUser.getStrategyName()).getId());
            userService.save(xpActicityUser);
        }
 
        //执行修改活动状态
        updateStatus(activity.getId());
    }
 
    @Override
    public XpActivityDto detail(Long id) {
        XpActivity byId = getById(id);
        XpActivityDto ret = new XpActivityDto();
        BeanUtils.copyBeanProp(ret, byId);
        ret.setActicityType(byId.getActicityType());
        ret.setEnableTotalLimit(byId.getAggregateLimit() == 1);
        ret.setTotalLimit(byId.getLimitation());
        ret.setImg(byId.getCoverImage());
        ret.setRichText(byId.getRemarks());
        ret.setStrategy(strategyService.listByActicityId(id));
        ret.setActivityUser(userService.listByActicityId(id));
        return ret;
    }
 
 
    /**
     * 获取悬浮弹窗活动数据
     * @param uid
     * @return
     */
    @Override
    public XpActivity getFloatActicity(Long uid) {
        //获取当前用户可参与的活动
        List<Integer> actitctiyIds = new ArrayList<>();
        //全部用户
        List<XpActicityUser> list = userService.list(new QueryWrapper<XpActicityUser>().eq("is_deleted", 0).eq("user_type", 1));
        actitctiyIds.addAll(list.stream().map(XpActicityUser::getActitcityId).collect(Collectors.toList()));
        //判断用户类型 2=老用户,3=新用户,4=流失用户
        Integer userType = xpOrderClient.determineUserType(uid).getData();
        list = userService.list(new QueryWrapper<XpActicityUser>().eq("is_deleted", 0).eq("user_type", userType));
        actitctiyIds.addAll(list.stream().map(XpActicityUser::getActitcityId).collect(Collectors.toList()));
        //指定用户
        list = userService.list(new QueryWrapper<XpActicityUser>().eq("is_deleted", 0).eq("user_type", 5)
                .last("  and JSON_CONTAINS(user_list, '" + uid + "', '$')"));
        actitctiyIds.addAll(list.stream().map(XpActicityUser::getActitcityId).collect(Collectors.toList()));
 
        XpActivity one = this.getOne(new QueryWrapper<XpActivity>().eq("status", 2).eq("is_deleted", 0)
                .eq("enable_float_window", 1).in(!actitctiyIds.isEmpty(), "id", actitctiyIds)
                .last(" and now() between start_time and end_time order by float_window_priority desc limit 1"));
        return one;
    }
 
 
    public void updateStatus(Long activityId) {
        XpActivity xpActivity = xpActicityService.getById(activityId);
        Integer status = xpActivity.getStatus();
        //即将开始的活动推送socket给前端用户
        if(1 == status && LocalDateTime.now().isBefore(xpActivity.getStartTime())){
 
        }
 
        //即将结束的活动推送给前端用户
 
        //生效的活动修改状态和发放一次优惠券
        if(1 == status && LocalDateTime.now().isAfter(xpActivity.getStartTime()) && LocalDateTime.now().isBefore(xpActivity.getEndTime())){
            xpActivity.setStatus(2);
            //发放优惠券-发放一次的优惠券
            List<XpActicityStrategy> list1 = xpActicityStrategyService.list(new QueryWrapper<XpActicityStrategy>().eq("actitcity_id", xpActivity.getId())
                    .eq("distribution_rules", 2));
            for (XpActicityStrategy xpActicityStrategy : list1) {
                pushCoupon(xpActivity, xpActicityStrategy);
            }
 
        }
        xpActicityService.updateById(xpActivity);
    }
 
 
    @Override
    public void updateStatus() {
        List<XpActivity> list = xpActicityService.list(new QueryWrapper<XpActivity>().in("status", Arrays.asList(1, 2)).eq("is_deleted", 0));
        for (XpActivity xpActivity : list) {
            Integer status = xpActivity.getStatus();
            //生效的活动修改状态和发放一次优惠券
            if(1 == status && LocalDateTime.now().isAfter(xpActivity.getStartTime()) && LocalDateTime.now().isBefore(xpActivity.getEndTime())){
                xpActivity.setStatus(2);
                //发放优惠券-发放一次的优惠券
                List<XpActicityStrategy> list1 = xpActicityStrategyService.list(new QueryWrapper<XpActicityStrategy>().eq("actitcity_id", xpActivity.getId())
                        .eq("distribution_rules", 2));
                for (XpActicityStrategy xpActicityStrategy : list1) {
                    pushCoupon(xpActivity, xpActicityStrategy);
                }
            }
            //到期的活动修改状态为已结束
            if(2 == status & LocalDateTime.now().isAfter(xpActivity.getEndTime())){
                xpActivity.setStatus(3);
            }
            xpActicityService.updateById(xpActivity);
        }
    }
 
 
    /**
     * 发放优惠券
     * @param xpActivity
     * @param xpActicityStrategy
     */
    public void pushCoupon(XpActivity xpActivity, XpActicityStrategy xpActicityStrategy){
        log.info("发放优惠券:{}", JSON.toJSONString(xpActivity));
        List<XpActicityCoupon> acticityCoupons = xpActicityCouponService.list(new QueryWrapper<XpActicityCoupon>().eq("acticity_strategy_id", xpActicityStrategy.getId()));
        List<XpCoupon> xpCoupons = xpCouponService.listByIds(acticityCoupons.stream().map(XpActicityCoupon::getCouponId).collect(Collectors.toList()));
        //总发放数量
        Integer distributionsTotal = xpActicityStrategy.getDistributionsTotal();
        //没人限量数量
        Integer limitNumber = xpActicityStrategy.getLimitNumber();
        List<XpActicityUser> list2 = xpActicityUserService.list(new QueryWrapper<XpActicityUser>().eq("actitcity_stratege_id", xpActicityStrategy.getId()));
        for (XpActicityUser xpActicityUser : list2) {
            Integer userType = xpActicityUser.getUserType();
            //全部白名单用户
            if(1 == userType){
                log.info("全部白名单用户发送");
                List<XpWhitelist> list3 = xpWhitelistService.list(new QueryWrapper<XpWhitelist>().eq("is_deleted", 0).eq("status", 1));
                List<XpAppUserCoupon> xpAppUserCoupons = new ArrayList<>();
                for (XpWhitelist xpWhitelist : list3) {
                    for (XpActicityCoupon acticityCoupon : acticityCoupons) {
                        XpCoupon xpCoupon = xpCoupons.stream().filter(s -> s.getId().equals(acticityCoupon.getCouponId())).findFirst().orElse(null);
                        if(null != xpCoupon){
                            for (Integer i = 0; i < limitNumber; i++) {
                                XpAppUserCoupon xpAppUserCoupon = new XpAppUserCoupon();
                                xpAppUserCoupon.setFullMoney(xpCoupon.getConditionalAmount());
                                xpAppUserCoupon.setMoney(xpCoupon.getAmount());
 
                                Integer effectiveRules = xpActicityStrategy.getEffectiveRules();
                                // 领取后生效
                                if(1 == effectiveRules){
                                    xpAppUserCoupon.setEffectiveTime(LocalDateTime.now());
                                }
                                // 指定日期生效
                                if(2 == effectiveRules){
                                    String format = xpActicityStrategy.getEffectiveDays().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                    xpAppUserCoupon.setEffectiveTime(LocalDateTime.parse(format + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                }
 
                                Integer expireRules = xpActicityStrategy.getExpireRules();
                                //次日0点失效
                                if(1 == expireRules){
                                    LocalDateTime now = LocalDateTime.now();
                                    LocalDateTime localDateTime = now.plusDays(1);
                                    LocalDateTime localDateTime1 = localDateTime.withHour(0).withMinute(0).withSecond(0);
                                    xpAppUserCoupon.setExpirationTime(localDateTime1);
                                }
                                //指定有效天数
                                if(2 == expireRules){
                                    LocalDateTime now = LocalDateTime.now();
                                    xpAppUserCoupon.setExpirationTime(now.plusDays(xpActicityStrategy.getExpireDays()));
                                }
                                //指定日期失效
                                if(3 == expireRules){
                                    String format = xpActicityStrategy.getExpireDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                    LocalDateTime localDateTime = LocalDateTime.parse(format + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    xpAppUserCoupon.setExpirationTime(localDateTime);
                                }
 
                                xpAppUserCoupon.setCouponId(acticityCoupon.getCouponId());
                                xpAppUserCoupon.setAppUserId(xpWhitelist.getAppUserId());
                                xpAppUserCoupon.setStatus(1);
                                xpAppUserCoupon.setActivityId(xpActivity.getId());
                                xpAppUserCoupon.setCouponName(xpCoupon.getCouponName());
                                xpAppUserCoupon.setDeleted(false);
                                xpAppUserCoupon.setCreateTime(LocalDateTime.now());
                                xpAppUserCoupon.setUpdateTime(LocalDateTime.now());
                                xpAppUserCoupon.setPhone(xpWhitelist.getAccount());
                                xpAppUserCoupon.setTimeJson(JSON.toJSONString(xpActicityStrategy.getUsagePeriod()));
                                xpAppUserCoupons.add(xpAppUserCoupon);
                                if(null == distributionsTotal){
                                    continue;
                                }
                                distributionsTotal--;
                                if(distributionsTotal <= 0){
                                    break;
                                }
                            }
 
                        }
                    }
                    if(null == distributionsTotal){
                        continue;
                    }
                    if(distributionsTotal <= 0){
                        break;
                    }
                }
                if(!xpAppUserCoupons.isEmpty()){
                    AppUserCouponSaveBatchVo vo = new AppUserCouponSaveBatchVo();
                    vo.setXpAppUserCoupons(xpAppUserCoupons);
                    xpAppUserCouponClient.saveBatch(vo);
                    //发送到账提醒消息
                    pushMessage(xpActivity, xpAppUserCoupons);
                }
                if(null == distributionsTotal){
                    continue;
                }
                if(distributionsTotal <= 0){
                    break;
                }
            }
            //老用户
            if(2 == userType || 3 == userType || 4 == userType){
                List<Long> longList = xpOrderClient.getUserTypeIdList(userType).getData();
                log.info("特定用户群体发送 {}", JSON.toJSONString(longList));
                List<XpAppUserCoupon> xpAppUserCoupons = new ArrayList<>();
                for (Long userId : longList) {
                    UcUserInfo baseUserByUid = userResourcesClient.getBaseUserByUid(userId.toString());
                    for (XpActicityCoupon acticityCoupon : acticityCoupons) {
                        XpCoupon xpCoupon = xpCoupons.stream().filter(s -> s.getId().equals(acticityCoupon.getCouponId())).findFirst().orElse(null);
                        if(null != xpCoupon){
                            for (Integer i = 0; i < limitNumber; i++) {
                                XpAppUserCoupon xpAppUserCoupon = new XpAppUserCoupon();
                                xpAppUserCoupon.setFullMoney(xpCoupon.getConditionalAmount());
                                xpAppUserCoupon.setMoney(xpCoupon.getAmount());
 
                                Integer expireRules = xpActicityStrategy.getExpireRules();
                                //次日0点失效
                                if(1 == expireRules){
                                    LocalDateTime now = LocalDateTime.now();
                                    LocalDateTime localDateTime = now.plusDays(1);
                                    LocalDateTime localDateTime1 = localDateTime.withHour(0).withMinute(0).withSecond(0);
                                    xpAppUserCoupon.setExpirationTime(localDateTime1);
                                }
                                //指定有效天数
                                if(2 == expireRules){
                                    LocalDateTime now = LocalDateTime.now();
                                    xpAppUserCoupon.setExpirationTime(now.plusDays(xpActicityStrategy.getExpireDays()));
                                }
                                //指定日期失效
                                if(3 == expireRules){
                                    String format = xpActicityStrategy.getExpireDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                    LocalDateTime localDateTime = LocalDateTime.parse(format + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    xpAppUserCoupon.setExpirationTime(localDateTime);
                                }
 
                                xpAppUserCoupon.setCouponId(acticityCoupon.getCouponId());
                                xpAppUserCoupon.setAppUserId(userId);
                                xpAppUserCoupon.setStatus(1);
                                xpAppUserCoupon.setActivityId(xpActivity.getId());
                                xpAppUserCoupon.setCouponName(xpCoupon.getCouponName());
                                xpAppUserCoupon.setDeleted(false);
                                xpAppUserCoupon.setCreateTime(LocalDateTime.now());
                                xpAppUserCoupon.setUpdateTime(LocalDateTime.now());
                                xpAppUserCoupon.setPhone(baseUserByUid.getMobile());
                                xpAppUserCoupon.setTimeJson(JSON.toJSONString(xpActicityStrategy.getUsagePeriod()));
                                xpAppUserCoupons.add(xpAppUserCoupon);
                                if(null == distributionsTotal){
                                    continue;
                                }
                                distributionsTotal--;
                                if(distributionsTotal <= 0){
                                    break;
                                }
                            }
                        }
                        if(null == distributionsTotal){
                            continue;
                        }
                        if(distributionsTotal <= 0){
                            break;
                        }
                    }
                }
                if(!xpAppUserCoupons.isEmpty()){
                    AppUserCouponSaveBatchVo vo = new AppUserCouponSaveBatchVo();
                    vo.setXpAppUserCoupons(xpAppUserCoupons);
                    xpAppUserCouponClient.saveBatch(vo);
                    //发送到账提醒消息
                    pushMessage(xpActivity, xpAppUserCoupons);
                }
                if(null == distributionsTotal){
                    continue;
                }
                if(distributionsTotal <= 0){
                    break;
                }
            }
            //指定用户
            if(5 == userType){
                List<Integer> userList = xpActicityUser.getUserList();
                log.info("指定用户发送 {}", JSON.toJSONString(userList));
                List<XpAppUserCoupon> xpAppUserCoupons = new ArrayList<>();
                for (Integer userId : userList) {
                    XpWhitelist xpWhitelist = xpWhitelistService.getById(userId);
                    if(null == xpWhitelist){
                        continue;
                    }
                    for (XpActicityCoupon acticityCoupon : acticityCoupons) {
                        XpCoupon xpCoupon = xpCoupons.stream().filter(s -> s.getId().equals(acticityCoupon.getCouponId())).findFirst().orElse(null);
                        if(null != xpCoupon){
                            for (Integer i = 0; i < limitNumber; i++) {
                                XpAppUserCoupon xpAppUserCoupon = new XpAppUserCoupon();
                                xpAppUserCoupon.setFullMoney(xpCoupon.getConditionalAmount());
                                xpAppUserCoupon.setMoney(xpCoupon.getAmount());
 
                                Integer expireRules = xpActicityStrategy.getExpireRules();
                                //次日0点失效
                                if(1 == expireRules){
                                    LocalDateTime now = LocalDateTime.now();
                                    LocalDateTime localDateTime = now.plusDays(1);
                                    LocalDateTime localDateTime1 = localDateTime.withHour(0).withMinute(0).withSecond(0);
                                    xpAppUserCoupon.setExpirationTime(localDateTime1);
                                }
                                //指定有效天数
                                if(2 == expireRules){
                                    LocalDateTime now = LocalDateTime.now();
                                    xpAppUserCoupon.setExpirationTime(now.plusDays(xpActicityStrategy.getExpireDays()));
                                }
                                //指定日期失效
                                if(3 == expireRules){
                                    String format = xpActicityStrategy.getExpireDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                    LocalDateTime localDateTime = LocalDateTime.parse(format + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    xpAppUserCoupon.setExpirationTime(localDateTime);
                                }
 
                                xpAppUserCoupon.setCouponId(acticityCoupon.getCouponId());
                                xpAppUserCoupon.setAppUserId(xpWhitelist.getAppUserId());
                                xpAppUserCoupon.setStatus(1);
                                xpAppUserCoupon.setActivityId(xpActivity.getId());
                                xpAppUserCoupon.setCouponName(xpCoupon.getCouponName());
                                xpAppUserCoupon.setDeleted(false);
                                xpAppUserCoupon.setCreateTime(LocalDateTime.now());
                                xpAppUserCoupon.setUpdateTime(LocalDateTime.now());
                                xpAppUserCoupon.setPhone(xpWhitelist.getAccount());
                                xpAppUserCoupon.setTimeJson(JSON.toJSONString(xpActicityStrategy.getUsagePeriod()));
                                xpAppUserCoupons.add(xpAppUserCoupon);
                                if(null == distributionsTotal){
                                    continue;
                                }
                                distributionsTotal--;
                                if(distributionsTotal <= 0){
                                    break;
                                }
                            }
 
                        }
                        if(null == distributionsTotal){
                            continue;
                        }
                        if(distributionsTotal <= 0){
                            break;
                        }
                    }
 
                    if(null == distributionsTotal){
                        continue;
                    }
                    if(distributionsTotal <= 0){
                        break;
                    }
                }
                if(!xpAppUserCoupons.isEmpty()){
                    AppUserCouponSaveBatchVo vo = new AppUserCouponSaveBatchVo();
                    vo.setXpAppUserCoupons(xpAppUserCoupons);
                    xpAppUserCouponClient.saveBatch(vo);
                    //发送到账提醒消息
                    pushMessage(xpActivity, xpAppUserCoupons);
                }
            }
        }
    }
 
 
    /**
     * 推送提醒消息
     * @param xpActivity
     * @param list
     */
    private void pushMessage(XpActivity xpActivity, List<XpAppUserCoupon> list) {
        pushWxCouponMessage(xpActivity, list);
        pushSmsCouponMessage(xpActivity, list);
    }
 
 
    /**
     * 微信通知
     */
    private void pushWxCouponMessage(XpActivity xpActivity, List<XpAppUserCoupon> list) {
        log.info("开始执行优惠券到账微信提醒消息发送 {}", JSON.toJSONString(xpActivity));
        //微信通知活动开始提醒(0=否,1=是)
        Integer wechatReceivedReminder = xpActivity.getWechatReceivedReminder();
        if(null != wechatReceivedReminder && 1 == wechatReceivedReminder){
            RETRY_EXECUTOR.execute(() -> {
                for (XpAppUserCoupon xpAppUserCoupon : list) {
                    XpCoupon coupon = xpCouponClient.getCouponById(xpAppUserCoupon.getCouponId()).getData();
                    SendSubscribeMessageVo vo = new SendSubscribeMessageVo();
                    vo.setUserId(xpAppUserCoupon.getAppUserId());
                    vo.setTemplateId(MessageTemplateEnum.C.getTemplateId());
                    String json = MessageTemplateEnum.C.getRemarks();
                    json = json.replace("活动名称", xpAppUserCoupon.getCouponName());
                    json = json.replace("温馨提示", coupon.getCouponDescription());
                    vo.setJson(json);
                    R<?> r = subscribeMessageClient.sendSubscribeMessage(vo);
                }
            });
        }
    }
 
 
    /**
     * 短信通知
     * @param xpActivity
     */
    private void pushSmsCouponMessage(XpActivity xpActivity, List<XpAppUserCoupon> list) {
        log.info("开始执行优惠券短信提醒消息发送 {}", JSON.toJSONString(xpActivity));
        Integer now = Integer.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmm")));
        if(StringUtils.hasLength(xpActivity.getSmsStartBlockingTime())){
            String[] smsStartBlockingTime = xpActivity.getSmsStartBlockingTime().split(",");
            String[] smsEndBlockingTime = xpActivity.getSmsEndBlockingTime().split(",");
            for (int i = 0; i < smsStartBlockingTime.length; i++) {
                Integer start = Integer.valueOf(smsStartBlockingTime[i].replace(":", ""));
                Integer end = Integer.valueOf(smsEndBlockingTime[i].replace(":", ""));
                if(start <= now && now <= end){
                    log.info("当前时间在短信发送时间区间内,不发送短信");
                    return;
                }
            }
        }
 
 
        //短信通知到账提醒(0=否,1=是)
        Integer smsReceivedReminder = xpActivity.getSmsReceivedReminder();
        if(null != smsReceivedReminder && 1 == smsReceivedReminder){
            RETRY_EXECUTOR.execute(() -> {
                for (XpAppUserCoupon xpAppUserCoupon : list) {
                    UcUserInfo ucUserInfo = userResourcesClient.getBaseUserByUid(xpAppUserCoupon.getAppUserId().toString());
                    if(null == ucUserInfo || !StringUtils.hasLength(ucUserInfo.getMobile())){
                        log.info("用户信息不存在,跳过");
                        continue;
                    }
                    XpCoupon coupon = xpCouponClient.getCouponById(xpAppUserCoupon.getCouponId()).getData();
                    SmsVo vo = new SmsVo();
                    vo.setAppId(sms_appid);
                    vo.setPushType(1);
                    vo.setReceivers(ucUserInfo.getMobile());
                    vo.setTemplateCode("RTActivityStartTpl");
                    vo.setAppPushConfigCode("RTActivityStartSms");
                    vo.setParams(new HashMap<>());
                    vo.getParams().put("name", xpAppUserCoupon.getCouponName());
                    SmsDto smsDto = smsClient.pushSms(vo);
                    if(null == smsDto || smsDto.getCode() != 200){
                        log.info("短信发送失败");
                    }
                }
            });
        }
    }
 
}