fix
Helius
2021-07-15 9c7facb28b6c95717fd01030973bafe26c3ac2c1
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
package com.xzx.gc.order.service;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzx.gc.common.constant.Constants;
import com.xzx.gc.common.constant.UserEnum;
import com.xzx.gc.common.exception.RestException;
import com.xzx.gc.common.utils.ExceptionUtils;
import com.xzx.gc.common.utils.RedisUtil;
import com.xzx.gc.entity.*;
import com.xzx.gc.model.JsonResult;
import com.xzx.gc.model.admin.*;
import com.xzx.gc.model.comon.account.AllAcountParamDto;
import com.xzx.gc.order.mapper.PlatformAccountLogMapper;
import com.xzx.gc.order.mapper.RedPaperMapper;
import com.xzx.gc.service.AccountContext;
import com.xzx.gc.util.DoubleUtil;
import com.xzx.gc.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
 
@Service
@Transactional
public class RedPaperService {
 
 
    @Autowired
    private RedPaperMapper redPaperMapper;
 
    @Autowired
    private RedisUtil redisUtil;
 
 
    @Autowired
    private CityPartnerService cityPartnerService;
 
    @Autowired
    private RedpaperRebateService redpaperRebateService;
 
    @Autowired
    private PlatformAccountLogMapper platformAccountLogMapper;
 
    @Autowired
    private RedPaperRuleService redPaperRuleService;
    @Autowired
    private SessionUtil sessionUtil;
    @Autowired
    private RebateRuleService rebateRuleService;
 
    public RedPaper getOne(Integer ruleId){
        return redPaperMapper.getOne(ruleId);
    }
 
    /**
     * 领取红包
     * @param ruleId 规则id
     * @param userId 领取红包的用户Id
     */
    public RedPaper get(String ruleId,String userId){
        boolean lock=false;
        try {
            if(redisUtil.setnx(Constants.REDIS_USER_KEY+"redpaper:"+userId,ruleId)){
                lock=true;
                AllAcountParamDto allAcountParamDto=AllAcountParamDto.builder().type(7).ruleId(ruleId).userId(userId).
                        build();
//                return (RedPaper) accountFactory.getService(7).account(allAcountParamDto);
                return (RedPaper) new AccountContext(redpaperRebateService).account(allAcountParamDto);
            }
        }catch (RestException e){
            throw e;
        }catch (Exception e){
            ExceptionUtils.err("领取红包失败",e);
        }finally {
            if(lock){
                redisUtil.del(Constants.REDIS_USER_KEY+"redpaper:"+userId);
            }
        }
        return null;
    }
 
 
    /**
     * 检验用户是否在此规则下已领取过红包
     * @param userId
     * @param ruleId
     * @return
     */
    public boolean checkIsReceive(String userId,Integer ruleId){
        RedPaper redPaper=new RedPaper();
        redPaper.setReceiveUserId(userId);
        redPaper.setRuleId(ruleId);
        redPaper.setReceiveFlag(Convert.toShort(UserEnum.红包已领取.getValue()));
        int i = redPaperMapper.selectCount(redPaper);
        if(i>0){
            return true;
        }
        return false;
    }
 
 
 
 
 
 
 
    public String cancelRedPaper(CityPartner partner, String type){
        String day = DateUtil.now();
        Snowflake snowflake = IdUtil.getSnowflake(0, 3);
        String payOrderId = "ZF"+snowflake.nextIdStr();
        if(null!=partner){
            //合伙人退还红包
            //判断红包有效时间是否已经截止
            RedPaperRule rule = redPaperMapper.queryRuleByDay(Long.parseLong(partner.getId()+""),day,type);
            if(null!=rule){
                //查询规则未领完的红包金额
                String redMoney = queryMoneyByRuleId(rule.getId()+"");
                BigDecimal rd = new BigDecimal(redMoney);
                if(rd.compareTo(BigDecimal.ZERO)==0){
                    return "合伙人的红包已经领完,不能退还!";
                }else{
                    PartnerAccountModel partnerAccountModel = cityPartnerService.queryAccountIdByUserId(partner.getUserId());
                    UserAccountModel userAccountModel1 = cityPartnerService.queryPartnerAccountByUserId(partner.getUserId());
                    BigDecimal hbb = new BigDecimal(partnerAccountModel.getHbb()).add(new BigDecimal(redMoney));
                    //先写日志 UserAccountModel accountModel, String type, BigDecimal money, String payOrderId
                    cityPartnerService.insertAccountLogByPartner(userAccountModel1,"5",new BigDecimal(redMoney),payOrderId);
                    cityPartnerService.insertPartnerLogByPartner(partnerAccountModel,"8",redMoney,payOrderId,partner,DoubleUtil.roundTwo(hbb.toString()));
                    //修改合伙人环保币
                    partnerAccountModel.setHbb(DoubleUtil.roundTwo(hbb.toString()));
                    cityPartnerService.updatePartnerAccount(partnerAccountModel);
                    UserAccountModel userAccountModel = new UserAccountModel();
                    userAccountModel.setUserId(partner.getUserId());
                    userAccountModel.setMoney(Double.valueOf(DoubleUtil.roundTwo(hbb.toString())));
                    cityPartnerService.updateAccountPartner(userAccountModel);
                    redPaperMapper.deletePaperByRuleId(rule.getId());
                }
            }else{
                rule = redPaperMapper.queryRuleByDay(Long.parseLong(partner.getId()+""),null,type);
                String endTime =rule.getEndTime();
                if(null!=endTime&&!"".equals(endTime)){
                    String[] times = endTime.split("-");
                    return "请在红包结束时间"+times[0]+"年"+times[1]+"月"+times[2]+"日之后进行操作";
                }else{
                    return "没有规则,无法退红包!";
                }
            }
        }else{
            //平台管理员退还红包
            RedPaperRule rule = redPaperMapper.queryRuleByDay(null,day,type);
            if(null!=rule){
                String redMoney = queryMoneyByRuleId(rule.getId()+"");
                BigDecimal rd = new BigDecimal(redMoney);
                if(rd.compareTo(BigDecimal.ZERO)==0){
                    return "平台的红包已经领完,不能退还!";
                }else{
                    String acc = cityPartnerService.queryAccountByAdminId();
                    String[] accArr = acc.split(",");
                    String oldMoney = accArr[1];
                    String oldHbb = accArr[2];
                    BigDecimal newMoney = new BigDecimal(oldMoney).add(new BigDecimal(redMoney));
                    updateAdminAccount(redMoney,"0",oldHbb,oldMoney,oldHbb,DoubleUtil.roundTwo(newMoney.toString()),null,payOrderId);
                    cityPartnerService.updatePlatformMoney(DoubleUtil.roundTwo(newMoney.toString()));
                    redPaperMapper.deletePaperByRuleId(rule.getId());
                }
            }else{
                rule = redPaperMapper.queryRuleByDay(null,null,type);
                String endTime =rule.getEndTime();
                if(null!=endTime&&!"".equals(endTime)){
                    String[] times = endTime.split("-");
                    return "请在红包结束时间"+times[0]+"年"+times[1]+"月"+times[2]+"日之后进行操作";
                }else{
                    return "没有规则,无法退红包!";
                }
            }
        }
        return null;
    }
 
    public String queryMoneyByRuleId(String ruleId){
        return redPaperMapper.queryMoneyByRuleId(ruleId);
    }
    private void updateAdminAccount(String money,String hbb,String oldHbb,String oldMoney,String newHbb,String newMoney,CityPartner  partner,String payOrderId){
        CoreUser user = sessionUtil.getCurrentUser();
        PlatformAccountLogModel platformAccountLogModel = new PlatformAccountLogModel();
        platformAccountLogModel.setCreateTime(DateUtil.now());
        platformAccountLogModel.setCreateUserId(user.getId()+"");
        platformAccountLogModel.setMoney(money);
        platformAccountLogModel.setHbb(hbb);
        platformAccountLogModel.setOldHbb(oldHbb);
        platformAccountLogModel.setOldMoney(oldMoney);
        platformAccountLogModel.setNewHbb(newHbb);
        platformAccountLogModel.setNewMoney(newMoney);
        if(null!=partner){
            platformAccountLogModel.setCreateUserName(partner.getPartnerName());
            platformAccountLogModel.setCreateUserMobile(partner.getMobilePhone());
        }else{
            platformAccountLogModel.setCreateUserName(user.getName());
            platformAccountLogModel.setCreateUserMobile("-");
        }
        platformAccountLogModel.setCreateUserType("2");
        platformAccountLogModel.setFlowNo(payOrderId);
        platformAccountLogMapper.insertPlatFormLog(platformAccountLogModel);
    }
    public Map<String,Object> redPaperList(XzxUserRedpaperInfoModel model){
        List<String> partnerIds = cityPartnerService.queryPartnerByCurrent();
        model.setPartnerIds(partnerIds);
        Map<String,Object> map = new HashMap<>();
        PageHelper.startPage(model.getPage(),model.getLimit());
        List<XzxUserRedpaperInfoModel> list = redPaperMapper.redPaperList(model);
        for (XzxUserRedpaperInfoModel resultModel:list) {
            String name = resultModel.getName();
            if(name!=null&&!"".equals(name)){
                name =Base64.decodeStr(name);
            }
            resultModel.setName(name);
        }
        PageInfo<XzxUserRedpaperInfoModel> pageInfo=new PageInfo<>(list);
        Map<String,Object> totalmap = redPaperMapper.redPaperTotal(model);
        map.put("data",pageInfo.getList());
        map.put("count",pageInfo.getTotal());
        map.put("code",0);
        map.put("redPaperTotalNum",totalmap.get("count"));
        if(totalmap.get("money")!=null){
            map.put("redPaperTotalMoney",totalmap.get("money"));
        }else{
            map.put("redPaperTotalMoney","0");
        }
        return map;
    }
 
    public void batchInsertPaperInfo(List<RedPaper> list){
        redPaperMapper.batchInsertPaperInfo(list);
    }
 
 
    public String subPartnerAccount(String amount){
        List<String> partnerIds = cityPartnerService.queryPartnerByCurrent();
        Snowflake snowflake = IdUtil.getSnowflake(0, 3);
        String payOrderId = "ZF"+snowflake.nextIdStr();
        if(null!=partnerIds&&partnerIds.size()>0){
            PartnerAccountModel partnerAccount = new PartnerAccountModel();
            CityPartner  partner = cityPartnerService.queryById(partnerIds.get(0));
            partnerAccount = cityPartnerService.queryAccountIdByUserId(partner.getUserId());
            BigDecimal pHbb = new BigDecimal(partnerAccount.getHbb());
            BigDecimal subHbb = pHbb.subtract(new BigDecimal(amount));
            if(subHbb.compareTo(BigDecimal.ZERO)==-1){
                return "合伙人的余额为:"+partnerAccount.getHbb()+",不足以发红包金额:"+amount+",请充值环保币!";
            }
            //UserAccountModel userAccount = cityPatrnerService.queryPartnerAccountByUserId(partner.getUserId());
            cityPartnerService.insertPartnerAccountLog(partnerAccount,"5",new BigDecimal(amount),payOrderId,"8");
            //userAccount.setMoney(Double.valueOf(DoubleUtil.roundTwo(subHbb.toString())));
            //cityPatrnerService.updateAccountPartner(userAccount);
            partnerAccount.setHbb(DoubleUtil.roundTwo(subHbb.toString()));
            cityPartnerService.updatePartnerAccount(partnerAccount);
        }else{
            String acc = cityPartnerService.queryAccountByAdminId();
            String[] accArr = acc.split(",");
            String adminMoney = accArr[1];
            String adminhbb = accArr[2];
            //平台
            BigDecimal oldAdminhbb = new BigDecimal(adminhbb);
            //平台账户处理红包
            BigDecimal newAdminhbb = oldAdminhbb.subtract(new BigDecimal(amount));
            cityPartnerService.updatePlatformHbb(DoubleUtil.roundTwo(newAdminhbb.toString()));
            PlatformAccountLogModel platformAccountLogModel = new PlatformAccountLogModel();
            platformAccountLogModel.setCreateTime(DateUtil.now());
            platformAccountLogModel.setCreateUserId("1");
            platformAccountLogModel.setMoney(DoubleUtil.roundTwo("0"));
            platformAccountLogModel.setHbb("-" + DoubleUtil.roundTwo(amount));
            platformAccountLogModel.setOldHbb(DoubleUtil.roundTwo(adminhbb));
            platformAccountLogModel.setOldMoney(DoubleUtil.roundTwo(adminMoney));
            platformAccountLogModel.setNewHbb(DoubleUtil.roundTwo(newAdminhbb.toString()));
            platformAccountLogModel.setNewMoney(DoubleUtil.roundTwo(adminMoney));
            platformAccountLogModel.setCreateUserName("平台管理员");
            platformAccountLogModel.setCreateUserType("2");
            platformAccountLogModel.setCreateUserMobile("--");
            platformAccountLogModel.setFlowNo(payOrderId);
            cityPartnerService.insertPlatFormLog(platformAccountLogModel);
        }
        return null;
    }
 
    public String cancelRedPaper1(CityPartner partner,String type){
        String day = DateUtil.now();
        Snowflake snowflake = IdUtil.getSnowflake(0, 3);
        String payOrderId = "ZF"+snowflake.nextIdStr();
 
        if(null!=partner){
            RedPaperRule rule = redPaperMapper.queryRuleByDay(Long.parseLong(partner.getId()+""),day,type);
 
            if(null!=rule){
                //查询规则未领完的红包金额
                String redMoney = queryMoneyByRuleId(rule.getId()+"");
                BigDecimal rd = new BigDecimal(redMoney);
                if(rd.compareTo(BigDecimal.ZERO)==0){
                    return null;
                }else {
                    PartnerAccountModel partnerAccountModel = cityPartnerService.queryAccountIdByUserId(partner.getUserId());
                    UserAccountModel userAccountModel1 = cityPartnerService.queryPartnerAccountByUserId(partner.getUserId());
                    BigDecimal hbb = new BigDecimal(partnerAccountModel.getHbb()).add(new BigDecimal(redMoney));
                    //先写日志 UserAccountModel accountModel, String type, BigDecimal money, String payOrderId
                    cityPartnerService.insertAccountLogByPartner(userAccountModel1, "5", new BigDecimal(redMoney), payOrderId);
                    cityPartnerService.insertPartnerLogByPartner(partnerAccountModel, "8", redMoney, payOrderId, partner, DoubleUtil.roundTwo(hbb.toString()));
                    //修改合伙人环保币
                    partnerAccountModel.setHbb(DoubleUtil.roundTwo(hbb.toString()));
                    cityPartnerService.updatePartnerAccount(partnerAccountModel);
                    UserAccountModel userAccountModel = new UserAccountModel();
                    userAccountModel.setUserId(partner.getUserId());
                    userAccountModel.setMoney(Double.valueOf(DoubleUtil.roundTwo(hbb.toString())));
                    cityPartnerService.updateAccountPartner(userAccountModel);
                }
            }else{
                rule = redPaperMapper.queryRuleByDay(Long.parseLong(partner.getId()+""),null,type);
                String endTime =rule.getEndTime();
                if(null!=endTime&&!"".equals(endTime)){
                    String[] times = endTime.split("-");
                    return "请在红包结束时间"+times[0]+"年"+times[1]+"月"+times[2]+"日之后进行操作";
                }else{
                    return "没有规则,无法退红包!";
                }
            }
        }else{
            RedPaperRule rule = redPaperMapper.queryRuleByDay(null,day,type);
            if(null!=rule){
                String redMoney = queryMoneyByRuleId(rule.getId()+"");
                BigDecimal rd = new BigDecimal(redMoney);
                if(rd.compareTo(BigDecimal.ZERO)==0){
                    return null;
                }else{
                    String acc = cityPartnerService.queryAccountByAdminId();
                    String[] accArr = acc.split(",");
                    String oldMoney = accArr[1];
                    String oldHbb = accArr[2];
                    BigDecimal newMoney = new BigDecimal(oldMoney).add(new BigDecimal(redMoney));
                    updateAdminAccount(redMoney,"0",oldHbb,oldMoney,oldHbb,DoubleUtil.roundTwo(newMoney.toString()),null,payOrderId);
                    cityPartnerService.updatePlatformMoney(DoubleUtil.roundTwo(newMoney.toString()));
                }
            }else{
                rule = redPaperMapper.queryRuleByDay(null,null,type);
                String endTime =rule.getEndTime();
                if(null!=endTime&&!"".equals(endTime)){
                    String[] times = endTime.split("-");
                    return "请在红包结束时间"+times[0]+"年"+times[1]+"月"+times[2]+"日之后进行操作";
                }else{
                    return "没有规则,无法退红包!";
                }
            }
        }
        return null;
    }
 
    public void deleteJtRuleId(Integer ruleId){
        redPaperMapper.deleteJtRuleId(ruleId);
    }
    public void deletePaperByRuleId(Integer ruleId){
        redPaperMapper.deletePaperByRuleId(ruleId);
    }
 
 
    /**
     * 添加红包规则
     * @return
     */
    public JsonResult updateRedPaper(Map<String, Object> map){
        ObjectMapper objectMapper1 = new ObjectMapper();
        objectMapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        XzxUserRedpaperRuleModel model = objectMapper1.convertValue(map, XzxUserRedpaperRuleModel.class);
 
 
        //检查合伙人账户
        model.setRuleType(UserEnum.红包规则.getValue());
        checkPartnerAccountByRule(model);
        //检查规则时间是否交叉
        checkRuleTime(model,UserEnum.红包规则.getValue());
 
        RedPaperRule ru = redPaperRuleService.queryById(model.getId());
 
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        RedPaperRule rule = objectMapper.convertValue(model, RedPaperRule.class);
        rule.setUpdateTime(cn.hutool.core.date.DateUtil.now());
        rule.setDelFlag((short) 0);
        rule.setRuleType("1");
        rule.setSharingProfitType("REDPAPER_TEXT");
        rule.setId(ru.getId());
        redPaperRuleService.update(rule);
        return JsonResult.success(rule.getId());
 
    }
 
 
    /**
     * 修改阶梯或重量返利
     * @param map
     * @return
     */
    public JsonResult updateRebateRule(Map<String, Object> map){
        List<String> partnerIds = cityPartnerService.queryPartnerByCurrent();
        if(CollUtil.isEmpty(partnerIds)){
            throw new RestException("非法操作");
        }
        ObjectMapper objectMapper1 = new ObjectMapper();
        objectMapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        XzxUserRedpaperRuleModel model = objectMapper1.convertValue(map, XzxUserRedpaperRuleModel.class);
        RedPaperRule rule = redPaperRuleService.queryById(model.getId());
 
        //检查时间交叉
        XzxUserRedpaperRuleModel xzxUserRedpaperRuleModel=new XzxUserRedpaperRuleModel();
        BeanUtil.copyProperties(rule,xzxUserRedpaperRuleModel);
        checkRuleTime(xzxUserRedpaperRuleModel,xzxUserRedpaperRuleModel.getRuleType());
 
        String compareType=null;
        if(UserEnum.重量返利规则.getValue().equals(rule.getRuleType())){
            compareType=UserEnum.阶梯返利规则.getValue();
        }else if(UserEnum.阶梯返利规则.getValue().equals(rule.getRuleType())){
            compareType=UserEnum.重量返利规则.getValue();
        }
        try {
            xzxUserRedpaperRuleModel.setId(null);
            checkRuleTime(xzxUserRedpaperRuleModel,compareType);
        } catch (RestException e) {
            return JsonResult.failMessage("阶梯返利规则和重量返利不能同时开启");
        }
 
 
 
        List<RebateRule> rulePriceList = model.getRulePriceList();
        if (rule.getRuleType().equals("5")) {
            rulePriceList = model.getWeightRateList();
        }
        List<String> priceList = new ArrayList<>();
        for (int i = 0; i < rulePriceList.size(); i++) {
            priceList.add(rulePriceList.get(i).getRate());
        }
        boolean bool = com.xzx.gc.util.DateUtil.isSorted(priceList, priceList.size());
        if (!bool) {
            return JsonResult.failMessage("阶梯价格必须按顺序排列");
        }
        rule.setConversionPerUnit(model.getConversionPerUnit());
        rule.setStartTime(model.getStartTime());
        rule.setEndTime(model.getEndTime());
        if (rule.getRuleType().equals("5")) {
            rule.setRuleName("重量规则返利");
            rule.setRuleType("5");
            if (null != model.getProductType() && !"".equals(model.getProductType())) {
                rule.setProductType(model.getProductType());
            }
 
        } else {
            rule.setRuleName("阶梯价格规则");
            rule.setRuleType("3");
        }
        rule.setCreateTime(cn.hutool.core.date.DateUtil.now());
        rule.setDelFlag((short) 0);
        rule.setStatus(model.getStatus());
        rule.setConversionPerUnitFlag(model.getConversionPerUnitFlag());
        redPaperRuleService.update(rule);
 
        if (rule.getId() != null) {
            //删除原有阶梯
            redPaperRuleService.deleteByRuleId(rule.getId());
            for (int i = 0; i < rulePriceList.size(); i++) {
                RebateRule rulePrice = rulePriceList.get(i);
                rulePrice.setId(null);
                rulePrice.setCreateTime(cn.hutool.core.date.DateUtil.now());
                rulePrice.setRuleId(Long.parseLong(rule.getId() + ""));
                rulePrice.setSort(String.valueOf(i + 1));
                rulePrice.setDelFlag((short) 0);
                rebateRuleService.save(rulePrice);
            }
        }
 
        return JsonResult.success(rule.getId());
    }
 
 
    /**
     * 检查规则时间
     * @param model
     * @param ruleType
     */
    public void checkRuleTime(XzxUserRedpaperRuleModel model,String ruleType){
        if(model.getStatus().equals(Convert.toShort(1))) {
            List<RedPaperRule> queryList = redPaperRuleService.queryRedpaperListStartAndEnd(model.getStartTime(), model.getEndTime(), model.getPartnerId(), model.getId(), ruleType);
            if (queryList != null && queryList.size() > 0) {
                throw new RestException("该时间段内已经存在当前规则");
            }
        }
    }
 
 
    /**
     * 检查合伙人账户
     * @param model
     */
    public void checkPartnerAccountByRule(XzxUserRedpaperRuleModel model){
        List<String> partnerIds = cityPartnerService.queryPartnerByCurrent();
        if (null != partnerIds && partnerIds.size() > 0) {
            model.setPartnerId(partnerIds.get(0));
 
            if(UserEnum.红包规则.getValue().equals(model.getRuleType())) {
                //判断合伙人是否能建该红包
                BigDecimal totalAmount = new BigDecimal(model.getAmount());
                CityPartner partner = cityPartnerService.queryById(partnerIds.get(0));
                PartnerAccountModel partnerAccountModel = cityPartnerService.queryAccountIdByUserId(partner.getUserId());
                BigDecimal pHbb = new BigDecimal(partnerAccountModel.getHbb());
                BigDecimal ff = pHbb.subtract(totalAmount);
                if (ff.compareTo(BigDecimal.ZERO) == -1) {
                    throw new RestException("合伙人账户余额不足,当前余额为:" + DoubleUtil.roundTwo(pHbb.toString()));
                }
            }
        }else {
            if(!UserEnum.提佣规则.getValue().equals(model.getRuleType())) {
                throw new RestException("非法操作");
            }
        }
    }
 
    /**
     * 添加红包规则
     * @param model
     * @return
     */
    public JsonResult addRedPaper(XzxUserRedpaperRuleModel model){
        CoreUser user = sessionUtil.getCurrentUser();
        model.setRuleType(UserEnum.红包规则.getValue());
        checkPartnerAccountByRule(model);
        List<RedPaper> infoList = new ArrayList<>();
 
        checkRuleTime(model,UserEnum.红包规则.getValue());
 
        //限制红包金额是否有符合正态分布
        if (model.getIssuanceRules().equals("0")) {
            String amount = model.getAmount();
            String surplusNum = model.getRedEnvelopesNum();
            BigDecimal avg = new BigDecimal(amount).divide(new BigDecimal(surplusNum), 2, RoundingMode.HALF_UP);
            String minMoney = model.getMinMoney();
            if (minMoney != null && !"".equals(minMoney)) {
                if (new BigDecimal(minMoney).compareTo(avg) >= 0) {
                    return JsonResult.failMessage("平均金额必须大于最小金额!");
                }
            } else {
                minMoney = model.getRandomAmountAverage().split(",")[0];
                if (new BigDecimal(minMoney).compareTo(avg) >= 0) {
                    return JsonResult.failMessage("平均金额必须大于最小金额!");
                }
            }
        }
 
        //先保存规则
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        RedPaperRule rule = objectMapper.convertValue(model, RedPaperRule.class);
        rule.setCreateTime(cn.hutool.core.date.DateUtil.now());
        rule.setDelFlag((short) 0);
        rule.setRuleType("1");
 
        redPaperRuleService.save(rule);
 
        //通过规则关联红包
        String amount = model.getAmount();
        String redEnvelopesNum = model.getRedEnvelopesNum();
        //金额随机或者金额固定
        String issuanceRules = model.getIssuanceRules();
        String randomAmountAverage = model.getRandomAmountAverage();
        //合伙人设置红包,需要扣除合伙人的环保币余额
        String result1 = subPartnerAccount(amount);
        if (null != result1) {
            return new JsonResult().failMessage(result1);
        }
        if (issuanceRules.equals("0")) {
            //金额随机
            String[] random = randomAmountAverage.split(",");
            String minRadom = random[0];
            String maxRadom = random[1];
            long[] result = DoubleUtil.generate(amount, Integer.parseInt(redEnvelopesNum), maxRadom, minRadom);
            double total = 0;
            for (int i = 0; i < result.length; i++) {
                double money = (double) result[i] / 100.00;
                total += result[i];
                if (rule.getId() != null) {
                    RedPaper info = saveRedPaperInfo(rule.getId(), amount, money);
                    info.setCreateUserId(user.getId() + "");
                    infoList.add(info);
                }
            }
            batchInsertPaperInfo(infoList);
            total = total / 100;
        } else if (issuanceRules.equals("1")) {
            int num = Integer.parseInt(redEnvelopesNum);
            //金额固定
            for (int i = 0; i < num; i++) {
                RedPaper info = saveRedPaperInfo(rule.getId(), amount, Double.parseDouble(randomAmountAverage));
                info.setCreateUserId(user.getId() + "");
                infoList.add(info);
            }
            batchInsertPaperInfo(infoList);
        }
        return JsonResult.success(rule.getId());
    }
 
 
    /**
     * 开启规则
     * @param model
     * @return
     */
    public JsonResult<Object> openRule(XzxUserRedpaperRuleModel model){
        RedPaperRule ru = redPaperRuleService.queryById(model.getId());
 
        XzxUserRedpaperRuleModel xzxUserRedpaperRuleModel=new XzxUserRedpaperRuleModel();
        xzxUserRedpaperRuleModel.setAmount(ru.getAmount());
        xzxUserRedpaperRuleModel.setRuleType(ru.getRuleType());
        checkPartnerAccountByRule(xzxUserRedpaperRuleModel);
 
        ru.setPartnerId(xzxUserRedpaperRuleModel.getPartnerId());
 
 
        ru.setStatus(model.getStatus());
 
 
        XzxUserRedpaperRuleModel xzxUserRedpaperRuleModel1=new XzxUserRedpaperRuleModel();
        BeanUtil.copyProperties(ru,xzxUserRedpaperRuleModel1);
        checkRuleTime(xzxUserRedpaperRuleModel1,xzxUserRedpaperRuleModel1.getRuleType());
 
 
        String compareType=null;
        if(UserEnum.重量返利规则.getValue().equals(ru.getRuleType())){
            compareType=UserEnum.阶梯返利规则.getValue();
        }else if(UserEnum.阶梯返利规则.getValue().equals(ru.getRuleType())){
            compareType=UserEnum.重量返利规则.getValue();
        }
 
        try {
            xzxUserRedpaperRuleModel1.setId(null);
            checkRuleTime(xzxUserRedpaperRuleModel1,compareType);
        } catch (RestException e) {
            return JsonResult.failMessage("阶梯返利规则和重量返利不能同时开启");
        }
 
 
 
 
        boolean success = redPaperRuleService.update(ru);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("修改失败");
        }
 
    }
 
    private RedPaper saveRedPaperInfo(Integer ruleId, String total, double money) {
        String code = FastDateFormat.getInstance("yyyyMMddHHmmssSSS").format(new Date());
        RedPaper info = new RedPaper();
        info.setCode(code);
        info.setCreateTime(cn.hutool.core.date.DateUtil.now());
        info.setMoney(new BigDecimal(String.valueOf(money)));
        info.setTotalAmount(total);
        info.setRuleId(ruleId);
        info.setReceiveFlag((short) 1);
        return info;
    }
}