admin
2019-12-24 8dc8133fb93405c6fc34c9c3c6c6bbce09ebe7f0
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
package com.yeshi.fanli.service.manger.order;
 
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
 
import com.yeshi.fanli.dao.mybatis.HongBaoV2Mapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderGoodsMapper;
import com.yeshi.fanli.dao.mybatis.order.HongBaoOrderMapper;
import com.yeshi.fanli.dto.HongBao;
import com.yeshi.fanli.dto.order.OrderHongBaoRateParams;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
import com.yeshi.fanli.entity.bus.user.ThreeSale;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.order.CommonOrder;
import com.yeshi.fanli.entity.order.CommonOrderGoods;
import com.yeshi.fanli.entity.order.HongBaoOrder;
import com.yeshi.fanli.exception.order.HongBaoException;
import com.yeshi.fanli.exception.user.UserAccountException;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.order.config.HongBaoManageService;
import com.yeshi.fanli.service.inter.order.msg.UserOrderMsgNotificationService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.service.inter.user.invite.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.user.vip.UserVIPInfoService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.TaoBaoConstant;
import com.yeshi.fanli.util.TimeUtil;
 
@Component
public class HongBaoV2AddManager {
 
    @Resource
    private UserInfoService userInfoService;
 
    @Resource
    private ThreeSaleSerivce threeSaleSerivce;
 
    @Resource
    private HongBaoOrderMapper hongBaoOrderMapper;
 
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
 
    @Resource
    private UserOrderMsgNotificationService userOrderMsgNotificationService;
 
    @Resource
    private HongBaoManageService hongBaoManageService;
 
    @Resource
    private CommonOrderService commonOrderService;
 
    @Resource
    private UserSystemCouponRecordService userSystemCouponRecordService;
 
    @Resource
    private UserSystemCouponService userSystemCouponService;
 
    @Resource
    private CommonOrderGoodsMapper commonOrderGoodsMapper;
 
    @Resource
    private UserVIPInfoService userVIPInfoService;
 
    /**
     * 添加红包信息
     * 
     * @param commonOrderList
     * @param type
     * @return
     * @throws HongBaoException
     * @throws UserAccountException
     */
    public int addHongBao(List<CommonOrder> commonOrderList, int type) throws HongBaoException, UserAccountException {
 
        if (commonOrderList != null && commonOrderList.size() > 0) {
            int orderType = commonOrderList.get(0).getSourceType();
 
            Map<Integer, HongBaoOrder> notificationMap = new HashMap<>();
            int goodsCount = 0;
            boolean hasAdd = false;
            boolean hasUpdate = false;
            Set<Integer> stateSet = new HashSet<>();// 订单状态Set
            for (CommonOrder commonOrder : commonOrderList) {
                stateSet.add(commonOrder.getState());
                goodsCount += commonOrder.getCount();
                if (commonOrder == null || commonOrder.getId() == null || commonOrder.getUserInfo() == null)
                    throw new HongBaoException(1, "订单信息不完整");
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
                if (hongBaoOrder == null) {
                    saveHongBao(commonOrder, type, notificationMap);
                    hasAdd = true;
                } else {
                    boolean update = updateHongBao(hongBaoOrder, commonOrder, type, notificationMap);
                    if (update)
                        hasUpdate = true;
                }
            }
 
            /**
             * 通知用户的返利情况
             */
            int state = getOrderState(stateSet);
            if (!Constant.IS_TEST) {
                if (hasAdd) {
                    Iterator<Integer> its = notificationMap.keySet().iterator();
                    while (its.hasNext()) {
                        Integer t = its.next();
                        HongBaoV2 notify = notificationMap.get(t).getHongBaoV2();
                        CommonOrder commonOrder = notificationMap.get(t).getCommonOrder();
                        String orderId = commonOrderList.get(0).getOrderNo();
                        Long uid = notify.getUserInfo().getId();
                        BigDecimal money = notify.getMoney();
                        switch (t) {
                        case HongBaoV2.TYPE_ZIGOU:
                            userOrderMsgNotificationService.orderFanLiStatistic(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, goodsCount, state);
                            break;
                        case HongBaoV2.TYPE_SHARE_GOODS:
                            userOrderMsgNotificationService.orderShareStatistic(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, goodsCount, state);
                            break;
                        case HongBaoV2.TYPE_YIJI:
                            userOrderMsgNotificationService.orderInviteStatistic(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, goodsCount, state);
                            break;
                        case HongBaoV2.TYPE_ERJI:
                            userOrderMsgNotificationService.orderInviteStatistic(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, goodsCount, state);
                            break;
                        case HongBaoV2.TYPE_SHARE_YIJI:
                            userOrderMsgNotificationService.orderShareFirstLevelStatistic(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, goodsCount, state, notify.getBeizhu());
                            break;
                        }
                    }
                }
 
                // 添加新版本通知
 
                if (!hasAdd) {
                    Iterator<Integer> its = notificationMap.keySet().iterator();
                    while (its.hasNext()) {
                        Integer t = its.next();
                        HongBaoV2 notify = notificationMap.get(t).getHongBaoV2();
                        CommonOrder commonOrder = notificationMap.get(t).getCommonOrder();
                        String orderId = commonOrderList.get(0).getOrderNo();
                        Long uid = notify.getUserInfo().getId();
                        BigDecimal money = notify.getMoney();
                        switch (t) {
                        case HongBaoV2.TYPE_ZIGOU:
                            userOrderMsgNotificationService.orderFanLiStateChanged(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, state);
                            break;
                        case HongBaoV2.TYPE_SHARE_GOODS:
                            userOrderMsgNotificationService.orderShareStateChanged(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, state);
                            break;
                        case HongBaoV2.TYPE_YIJI:
                            userOrderMsgNotificationService.orderInviteStateChanged(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, state);
                            break;
                        case HongBaoV2.TYPE_ERJI:
                            userOrderMsgNotificationService.orderInviteStateChanged(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, state);
                            break;
                        case HongBaoV2.TYPE_SHARE_YIJI:
                            userOrderMsgNotificationService.orderShareFirstLevelStateChanged(uid, orderId, orderType,
                                    commonOrder.getPayment(), money, state);
                        }
                    }
                }
            }
 
            int resultCode = 0;
            if (hasAdd && hasUpdate)
                return 12;
            else if (hasAdd)
                return 1;
            else if (hasUpdate)
                return 2;
            return resultCode;
        }
        return 0;
    }
 
    private int getOrderState(Set<Integer> states) {
        if (states.size() == 1)
            return states.iterator().next();
        Iterator<Integer> its = states.iterator();
        while (its.hasNext()) {
            int tempState = its.next();
            if (tempState == CommonOrder.STATE_FK)
                return CommonOrder.STATE_FK;
            else if (tempState == CommonOrder.STATE_JS)
                return CommonOrder.STATE_JS;
        }
        return CommonOrder.STATE_SX;
    }
 
    @Transactional(rollbackFor = Exception.class)
    private boolean updateHongBao(HongBaoOrder hongBaoOrder, CommonOrder commonOrder, int type,
            Map<Integer, HongBaoOrder> notificationMap) throws HongBaoException, UserAccountException {
        System.out.println(commonOrder.getOrderNo());
        // 锁行
        HongBaoV2 oldHongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBaoOrder.getHongBaoV2().getId());
        if (oldHongBao == null)
            throw new HongBaoException(10, "红包对象不存在");
        // 已经失效,已经领取,新老状态一致的红包不做处理
        if (oldHongBao.getState() == HongBaoV2.STATE_SHIXIAO || oldHongBao.getState() == HongBaoV2.STATE_YILINGQU)
            return false;
 
        if (type == HongBaoV2.TYPE_ZIGOU) {// 获取自购的返利比例
            BigDecimal fanliRate = hongBaoManageService.getRate(new OrderHongBaoRateParams(0, type, false,
                    oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
            // 免单处理
            boolean mianDan = false;
            List<CommonOrder> orderList = commonOrderService.listBySourceTypeAndOrderId(Constant.SOURCE_TYPE_TAOBAO,
                    commonOrder.getOrderNo());
            if (orderList != null && orderList.size() == 1) {// 只有1个订单才参与免单
                BigDecimal payMent = commonOrder.getPayment();
                if (commonOrder.getState() == CommonOrder.STATE_JS)
                    payMent = commonOrder.getSettlement();
 
                if (payMent.compareTo(new BigDecimal(10)) < 0) {
                    mianDan = userSystemCouponRecordService.isSuccessMianDan(commonOrder.getSourceType(),
                            commonOrder.getOrderNo());
                }
            }
 
            HongBaoV2 hongBao = createFanLiUpdateHongBao(commonOrder, fanliRate, hongBaoOrder.getHongBaoV2().getId(),
                    mianDan);
 
            // 新老红包状态一致不处理
            if (oldHongBao.getState().intValue() == hongBao.getState())
                return false;
 
            if (hongBao.getState() == HongBaoV2.STATE_SHIXIAO) {
                if (mianDan) {
                    try {
                        userSystemCouponService.updateStateByDrawback(commonOrder.getOrderNo());
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new HongBaoException(12, "免单券退款出错");
                    }
                }
            }
 
            hongBaoV2Mapper.updateByPrimaryKeySelective(hongBao);
 
            // 加入通知
            if (notificationMap.get(type) == null) {
                HongBaoV2 tempHongBao = new HongBaoV2(oldHongBao.getId());
                tempHongBao.setUserInfo(oldHongBao.getUserInfo());
                tempHongBao.setMoney(hongBao.getMoney());
                CommonOrder tempCommonOrder = new CommonOrder(commonOrder.getId());
                tempCommonOrder.setPayment(commonOrder.getPayment());
                notificationMap.put(type, new HongBaoOrder(tempCommonOrder, tempHongBao));
            } else {
                // 增加付款金额与资金
                HongBaoOrder tempHongBaoOrder = notificationMap.get(type);
                tempHongBaoOrder.getCommonOrder()
                        .setPayment(tempHongBaoOrder.getCommonOrder().getPayment().add(commonOrder.getPayment()));
                tempHongBaoOrder.getHongBaoV2()
                        .setMoney(tempHongBaoOrder.getHongBaoV2().getMoney().add(hongBao.getMoney()));
                notificationMap.put(type, tempHongBaoOrder);
            }
 
            // 获取子红包
            List<HongBaoV2> children = hongBaoV2Mapper.listChildrenById(hongBao.getId());
            if (children != null && children.size() > 0) {
                for (HongBaoV2 child : children) {
                    if (child.getState() == HongBaoV2.STATE_YILINGQU)
                        continue;
                    BigDecimal rate = null;
                    if (child.getType() == HongBaoV2.TYPE_YIJI) {
                        rate = hongBaoManageService.getRate(new OrderHongBaoRateParams(1, oldHongBao.getType(), false,
                                oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
                    } else if (child.getType() == HongBaoV2.TYPE_ERJI) {
                        rate = hongBaoManageService.getRate(new OrderHongBaoRateParams(2, oldHongBao.getType(), false,
                                oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
                    }
 
                    HongBaoV2 childUpdate = createInviteUpdateHongBao(child, hongBao.getState(),
                            MoneyBigDecimalUtil.mul(hongBao.getMoney(), rate.divide(new BigDecimal(100))), commonOrder);
                    hongBaoV2Mapper.updateByPrimaryKeySelective(childUpdate);
 
                    // 加入通知
                    if (notificationMap.get(child.getType()) == null) {
                        HongBaoV2 tempHongBao = new HongBaoV2(child.getId());
                        tempHongBao.setUserInfo(child.getUserInfo());
                        tempHongBao.setMoney(child.getMoney());
                        CommonOrder tempCommonOrder = new CommonOrder(commonOrder.getId());
                        tempCommonOrder.setPayment(commonOrder.getPayment());
                        notificationMap.put(child.getType(), new HongBaoOrder(tempCommonOrder, tempHongBao));
                    } else {
                        // 增加付款金额与资金
                        HongBaoOrder tempHongBaoOrder = notificationMap.get(child.getType());
                        tempHongBaoOrder.getCommonOrder().setPayment(
                                tempHongBaoOrder.getCommonOrder().getPayment().add(commonOrder.getPayment()));
                        tempHongBaoOrder.getHongBaoV2()
                                .setMoney(tempHongBaoOrder.getHongBaoV2().getMoney().add(child.getMoney()));
                        notificationMap.put(child.getType(), tempHongBaoOrder);
                    }
                }
            } else {// 修复之前二级,三级订单未统计到的情况
                if (!mianDan) {
                    ThreeSale threeSale = threeSaleSerivce.selectByWorkerId(commonOrder.getUserInfo().getId());
                    if (threeSale != null && threeSale.getSucceedTime() != null
                            && threeSale.getSucceedTime() <= commonOrder.getThirdCreateTime().getTime()) {
                        UserInfo boss = threeSaleSerivce.getBoss(commonOrder.getUserInfo().getId());
                        if (boss != null) {
                            boss = userInfoService.selectAvailableByPrimaryKey(boss.getId());
                        }
 
                        if (boss != null) {
                            // 插入一级子红包
                            BigDecimal firstRate = hongBaoManageService.getRate(new OrderHongBaoRateParams(1, type,
                                    false, oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
                            if (firstRate != null && firstRate.compareTo(new BigDecimal(0)) > 0) {
                                HongBaoV2 firstHongbao = createInviteHongBao(boss.getId(), oldHongBao, commonOrder,
                                        HongBaoV2.TYPE_YIJI, MoneyBigDecimalUtil.mul(hongBao.getMoney(),
                                                firstRate.divide(new BigDecimal(100))));
                                if (firstHongbao != null)
                                    addInviteHongBao(firstHongbao, null, notificationMap, commonOrder);
                            }
                            boss = threeSaleSerivce.getBoss(boss.getId());
                            if (boss != null) {
                                boss = userInfoService.selectAvailableByPrimaryKey(boss.getId());
                            }
                            if (boss != null) {
                                // 二级红包
                                BigDecimal secondRate = hongBaoManageService.getRate(new OrderHongBaoRateParams(2, type,
                                        false, oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
                                if (secondRate != null && secondRate.compareTo(new BigDecimal(0)) > 0) {
                                    HongBaoV2 secondHongbao = createInviteHongBao(boss.getId(), oldHongBao, commonOrder,
                                            HongBaoV2.TYPE_ERJI, MoneyBigDecimalUtil.mul(hongBao.getMoney(),
                                                    secondRate.divide(new BigDecimal(100))));
                                    if (secondHongbao != null)
                                        addInviteHongBao(secondHongbao, null, notificationMap, commonOrder);
                                }
                            }
                        }
                    }
                }
            }
        } else if (type == HongBaoV2.TYPE_SHARE_GOODS) {
            BigDecimal fanliRate = hongBaoManageService.getRate(new OrderHongBaoRateParams(0, type, false,
                    oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
 
            HongBaoV2 hongBao = createShareUpdateHongBao(commonOrder, fanliRate, oldHongBao.getId());
            hongBaoV2Mapper.updateByPrimaryKeySelective(hongBao);
            // 通知
            if (notificationMap.get(type) == null) {
                HongBaoV2 tempHongBao = new HongBaoV2(hongBao.getId());
                tempHongBao.setUserInfo(hongBaoOrder.getHongBaoV2().getUserInfo());
                tempHongBao.setMoney(hongBao.getMoney());
                CommonOrder tempCommonOrder = new CommonOrder(commonOrder.getId());
                tempCommonOrder.setPayment(commonOrder.getPayment());
                notificationMap.put(type, new HongBaoOrder(tempCommonOrder, tempHongBao));
            } else {
                // 增加付款金额与资金
                HongBaoOrder tempHongBaoOrder = notificationMap.get(type);
                tempHongBaoOrder.getCommonOrder()
                        .setPayment(tempHongBaoOrder.getCommonOrder().getPayment().add(commonOrder.getPayment()));
                tempHongBaoOrder.getHongBaoV2()
                        .setMoney(tempHongBaoOrder.getHongBaoV2().getMoney().add(hongBao.getMoney()));
                notificationMap.put(type, tempHongBaoOrder);
            }
 
            // 获取子红包
            List<HongBaoV2> children = hongBaoV2Mapper.listChildrenById(hongBao.getId());
            if (children != null)
                for (HongBaoV2 child : children) {
                    if (child.getState() == HongBaoV2.STATE_YILINGQU)
                        continue;
 
                    BigDecimal rate = null;
                    if (child.getType() == HongBaoV2.TYPE_SHARE_YIJI) {
                        rate = hongBaoManageService.getRate(new OrderHongBaoRateParams(1, oldHongBao.getType(), false,
                                oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
                    } else if (child.getType() == HongBaoV2.TYPE_SHARE_ERJI) {
                        rate = hongBaoManageService.getRate(new OrderHongBaoRateParams(2, oldHongBao.getType(), false,
                                oldHongBao.getUrank() == 100, commonOrder.getThirdCreateTime()));
                    }
                    HongBaoV2 childUpdate = createInviteUpdateHongBao(child, hongBao.getState(),
                            MoneyBigDecimalUtil.mul(hongBao.getMoney(), rate.divide(new BigDecimal(100))), commonOrder);
                    hongBaoV2Mapper.updateByPrimaryKeySelective(childUpdate);
                    // 添加通知
                    if (notificationMap.get(child.getType()) == null) {
                        HongBaoV2 tempHongBao = new HongBaoV2(child.getId());
                        tempHongBao.setUserInfo(child.getUserInfo());
                        tempHongBao
                                .setMoney(childUpdate.getMoney() == null ? new BigDecimal(0) : childUpdate.getMoney());
                        CommonOrder tempCommonOrder = new CommonOrder(commonOrder.getId());
                        tempCommonOrder.setPayment(commonOrder.getPayment());
                        notificationMap.put(child.getType(), new HongBaoOrder(tempCommonOrder, tempHongBao));
                    } else {
                        // 增加付款金额与资金
                        HongBaoOrder tempHongBaoOrder = notificationMap.get(child.getType());
                        if (commonOrder.getPayment() != null)
                            tempHongBaoOrder.getCommonOrder().setPayment(
                                    tempHongBaoOrder.getCommonOrder().getPayment().add(commonOrder.getPayment()));
                        if (childUpdate.getMoney() != null)
                            tempHongBaoOrder.getHongBaoV2()
                                    .setMoney(tempHongBaoOrder.getHongBaoV2().getMoney().add(childUpdate.getMoney()));
                        notificationMap.put(child.getType(), tempHongBaoOrder);
                    }
 
                }
        } else
            throw new HongBaoException(2, "type错误");
 
        return true;
    }
 
    @Transactional(rollbackFor = Exception.class)
    private void saveHongBao(CommonOrder commonOrder, int type, Map<Integer, HongBaoOrder> notificationMap)
            throws HongBaoException, UserAccountException {
 
        boolean vip = commonOrder.getUrank() != null && commonOrder.getUrank() == 100;
        if (type == HongBaoV2.TYPE_ZIGOU) {// 获取自购的返利比例
            BigDecimal fanliRate = hongBaoManageService
                    .getRate(new OrderHongBaoRateParams(0, type, false, vip, commonOrder.getThirdCreateTime()));
            // 查询是否有免单计划
            BigDecimal mianDanMoney = null;
            if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_FK) {
                List<CommonOrder> orderList = commonOrderService.listBySourceTypeAndOrderId(commonOrder.getSourceType(),
                        commonOrder.getOrderNo());
                if (orderList != null && orderList.size() == 1) {// 只有1个订单才参与免单
                    BigDecimal payMent = commonOrder.getPayment();
                    if (commonOrder.getState() == CommonOrder.STATE_JS)
                        payMent = commonOrder.getSettlement();
 
                    CommonOrderGoods goods = commonOrderGoodsMapper
                            .selectByPrimaryKey(commonOrder.getCommonOrderGoods().getId());
                    if (goods != null) {
                        try {
                            if (userSystemCouponService.updateCouponRecordUsed(commonOrder.getUserInfo().getId(),
                                    commonOrder.getOrderNo(), payMent, Long.parseLong(goods.getGoodsId())))
                                mianDanMoney = payMent;
                        } catch (NumberFormatException e) {
                            throw new HongBaoException(10, "免单商品处理出错");
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new HongBaoException(11, "免单商品处理出错");
                        }
                    }
                }
            } else if (commonOrder.getState() == CommonOrder.STATE_SX) {// 设置免单券失效
                commonOrder.setPayment(new BigDecimal(0));// 订单失效后的付款金额设置为0
                try {
                    userSystemCouponService.updateStateByDrawback(commonOrder.getOrderNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
 
            HongBaoV2 hongBao = createFanLiHongBao(commonOrder, fanliRate, mianDanMoney, vip);
            if (hongBao == null)
                return;
            addFanLiOrShareHongBao(hongBao, commonOrder, notificationMap);
            UserInfo boss = threeSaleSerivce.getBoss(hongBao.getUserInfo().getId());
            if (boss != null && hongBao.getState() != HongBaoV2.STATE_SHIXIAO && mianDanMoney == null) {// 1级BOSS存在且红包未失效,免单不支持多级分销
                // 插入一级子红包
                BigDecimal firstRate = hongBaoManageService
                        .getRate(new OrderHongBaoRateParams(1, type, false, vip, commonOrder.getThirdCreateTime()));
                if (firstRate.compareTo(new BigDecimal(0)) <= 0)// 返利比例为0的不分成
                    return;
 
                HongBaoV2 firstHongbao = createInviteHongBao(boss.getId(), hongBao, commonOrder, HongBaoV2.TYPE_YIJI,
                        MoneyBigDecimalUtil.mul(hongBao.getMoney(), firstRate.divide(new BigDecimal(100))));
 
                addInviteHongBao(firstHongbao, null, notificationMap, commonOrder);
 
                // 插入二级子红包
                boss = threeSaleSerivce.getBoss(boss.getId());
                if (boss != null) {// 二级BOSS存在且是非会员订单
                    BigDecimal secondRate = hongBaoManageService
                            .getRate(new OrderHongBaoRateParams(2, type, false, vip, commonOrder.getThirdCreateTime()));
                    if (secondRate.compareTo(new BigDecimal(0)) <= 0)
                        return;
                    HongBaoV2 secondHongbao = createInviteHongBao(boss.getId(), hongBao, commonOrder,
                            HongBaoV2.TYPE_ERJI,
                            MoneyBigDecimalUtil.mul(hongBao.getMoney(), secondRate.divide(new BigDecimal(100))));
                    addInviteHongBao(secondHongbao, null, notificationMap, commonOrder);
                }
            }
 
        } else if (type == HongBaoV2.TYPE_SHARE_GOODS) {
            // 分享赚不加入失效的订单
            if (commonOrder.getState() == CommonOrder.STATE_SX || commonOrder.getState() == CommonOrder.STATE_WQ)
                return;
            // 分享赚
            BigDecimal shareRate = null;
            if (commonOrder.getSourceType() == Constant.SOURCE_TYPE_TAOBAO
                    && commonOrder.getSourcePosition().equalsIgnoreCase(TaoBaoConstant.TAOBAO_TLJ_RELATION_PID_DEFAULT))// 来自于淘礼金的分享
                shareRate = hongBaoManageService.getTLJShareRate(commonOrder.getCreateTime().getTime());
            else
                shareRate = hongBaoManageService
                        .getRate(new OrderHongBaoRateParams(0, type, false, vip, commonOrder.getThirdCreateTime()));
 
            if (shareRate.compareTo(new BigDecimal(0)) <= 0)
                return;
            HongBaoV2 hongBao = createShareHongBao(commonOrder, shareRate, vip);
            if (hongBao == null)
                return;
            addFanLiOrShareHongBao(hongBao, commonOrder, notificationMap);
            // 4月17日后才有一级分享赚
            if (commonOrder.getThirdCreateTime().getTime() > TimeUtil.convertToTimeTemp("2019-04-17", "yyyy-MM-dd")) {
                UserInfo boss = threeSaleSerivce.getBoss(hongBao.getUserInfo().getId());
                if (boss != null) {
                    BigDecimal firstLevelRate = hongBaoManageService
                            .getRate(new OrderHongBaoRateParams(1, type, false, vip, commonOrder.getThirdCreateTime()));
                    if (firstLevelRate == null || firstLevelRate.compareTo(new BigDecimal("0")) == 0)
                        return;
 
                    HongBaoV2 firstHongbao = createInviteHongBao(boss.getId(), hongBao, commonOrder,
                            HongBaoV2.TYPE_SHARE_YIJI,
                            MoneyBigDecimalUtil.mul(hongBao.getMoney(), firstLevelRate.divide(new BigDecimal(100))));
 
                    addInviteHongBao(firstHongbao, hongBao.getUserInfo().getNickName(), notificationMap, commonOrder);
 
                    // 二级分享赚
                    boss = threeSaleSerivce.getBoss(boss.getId());
                    if (boss != null) {
                        BigDecimal secondLevelRate = hongBaoManageService.getRate(
                                new OrderHongBaoRateParams(2, type, false, vip, commonOrder.getThirdCreateTime()));
                        if (secondLevelRate.compareTo(new BigDecimal(0)) <= 0)// 返利比例为0就不统计
                            return;
                        HongBaoV2 secondChild = createInviteHongBao(boss.getId(), hongBao, commonOrder,
                                HongBaoV2.TYPE_SHARE_ERJI, MoneyBigDecimalUtil.mul(hongBao.getMoney(),
                                        secondLevelRate.divide(new BigDecimal(100))));
                        addInviteHongBao(secondChild, null, notificationMap, commonOrder);
                    }
                }
            }
 
            // 修改统计数据
            Long goodsId = commonOrder.getCommonOrderGoods().getId();
            // 查询商品
            CommonOrderGoods goods = commonOrderGoodsMapper.selectByPrimaryKey(goodsId);
 
            HongBao hb = new HongBao();
            if (goods != null)
                hb.setAuctionId(Long.parseLong(goods.getGoodsId()));
            hb.setUserInfo(hongBao.getUserInfo());
            hb.setMoney(hongBao.getMoney());
 
            // TODO 更新分享记录数据
            // try {
            // userShareGoodsGroupService.updateOrderRecord(hb,
            // commonOrder.getSourceType());
            // } catch (UserShareGoodsRecordException e) {
            // try {
            // LogHelper.errorDetailInfo(e);
            // } catch (Exception e1) {
            // e1.printStackTrace();
            // }
            // }
        } else
            throw new HongBaoException(2, "type错误");
    }
 
    /**
     * 添加邀请赚红包
     * 
     * @param child
     * @param notificationMap
     * @param commonOrder
     */
    private void addInviteHongBao(HongBaoV2 child, String parentHongBaoUserName,
            Map<Integer, HongBaoOrder> notificationMap, CommonOrder commonOrder) {
        if (child != null) {
            hongBaoV2Mapper.insertSelective(child);
            // 用户通知
            if (notificationMap.get(child.getType()) == null) {
                HongBaoV2 tempHongBao = new HongBaoV2(child.getId());
                tempHongBao.setUserInfo(child.getUserInfo());
                tempHongBao.setMoney(child.getMoney());
                if (child.getType() == HongBaoV2.TYPE_SHARE_YIJI)
                    tempHongBao.setBeizhu(parentHongBaoUserName);
 
                CommonOrder tempCommonOrder = new CommonOrder(commonOrder.getId());
                tempCommonOrder.setPayment(commonOrder.getPayment());
                notificationMap.put(child.getType(), new HongBaoOrder(tempCommonOrder, tempHongBao));
            } else {
                // 增加付款金额与资金
                HongBaoOrder tempHongBaoOrder = notificationMap.get(child.getType());
                tempHongBaoOrder.getCommonOrder()
                        .setPayment(tempHongBaoOrder.getCommonOrder().getPayment().add(commonOrder.getPayment()));
                tempHongBaoOrder.getHongBaoV2()
                        .setMoney(tempHongBaoOrder.getHongBaoV2().getMoney().add(child.getMoney()));
                notificationMap.put(child.getType(), tempHongBaoOrder);
            }
        }
    }
 
    /**
     * 创建邀请红包
     * 
     * @param uid
     * @param parent
     * @param commonOrder
     * @param hongBaoType
     * @param money
     * @return
     */
    private HongBaoV2 createInviteHongBao(Long uid, HongBaoV2 parent, CommonOrder commonOrder, int hongBaoType,
            BigDecimal money) {
        if (parent == null)
            return null;
        if (parent.getState() == HongBaoV2.STATE_SHIXIAO)
            return null;
        UserInfo user = userInfoService.selectAvailableByPrimaryKey(uid);
        if (user == null)
            return null;
        boolean isVIP = userVIPInfoService.isVIP(uid);
 
        HongBaoV2 child = new HongBaoV2();
        child.setParent(parent);
        child.setType(hongBaoType);
        child.setMoney(money);
 
        if (commonOrder.getState() == CommonOrder.STATE_FK) {
            child.setState(HongBaoV2.STATE_BUKELINGQU);
        } else if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_WQ) {
            child.setState(HongBaoV2.STATE_KELINGQU);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(commonOrder.getSettleTime());
            calendar.add(Calendar.MONTH, 1);
            child.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25", "yyyy-M-dd")));
        }
 
        child.setUserInfo(user);
        child.setUrank(user.getRank());
        child.setVersion(2);
        child.setCreateTime(new Date());
        child.setOrderType(commonOrder.getSourceType());
        if (child.getMoney() == null)
            return null;
        if (child.getMoney().compareTo(new BigDecimal(0)) <= 0 && !isVIP)
            return null;
        return child;
    }
 
    /**
     * 
     * @param commonOrder
     *            - 订单信息
     * @param fanliRate
     *            -返利比例
     * @param mianDanMoney
     *            免单金额
     * @param isVIP-是否为VIP订单
     * @return
     * @throws HongBaoException
     * @throws UserAccountException
     */
    private HongBaoV2 createFanLiHongBao(CommonOrder commonOrder, BigDecimal fanliRate, BigDecimal mianDanMoney,
            boolean isVIP) throws HongBaoException, UserAccountException {
        HongBaoV2 hongBao = new HongBaoV2();
        hongBao.setUserInfo(commonOrder.getUserInfo());
        hongBao.setCreateTime(new Date());
        hongBao.setType(HongBaoV2.TYPE_ZIGOU);
        hongBao.setVersion(2);
        if (commonOrder.getState() == CommonOrder.STATE_FK) {
            hongBao.setState(HongBaoV2.STATE_BUKELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(), fanliRate.divide(new BigDecimal(100))));
        } else if (commonOrder.getState() == CommonOrder.STATE_JS || CommonOrder.STATE_WQ == commonOrder.getState()) {
            hongBao.setState(HongBaoV2.STATE_KELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), fanliRate.divide(new BigDecimal(100))));
            if (commonOrder.getSourceType() == Constant.SOURCE_TYPE_PDD)// 拼多多15天半到账
                hongBao.setPreGetTime(new Date(
                        commonOrder.getSettleTime().getTime() + 1000 * 60 * 60 * 24 * 15L + 1000 * 60 * 60 * 12L));
            else
                hongBao.setPreGetTime(new Date(commonOrder.getSettleTime().getTime() + 1000 * 60 * 60 * 24 * 15L));
        } else if (commonOrder.getState() == CommonOrder.STATE_SX) {
            hongBao.setState(HongBaoV2.STATE_SHIXIAO);
            hongBao.setMoney(new BigDecimal(0));
        } else {
            throw new HongBaoException(3, "维权订单不能创建红包");
        }
 
        if (mianDanMoney != null)
            hongBao.setMoney(mianDanMoney);
 
        UserInfo user = userInfoService.getUserById(commonOrder.getUserInfo().getId());
        if (user == null)
            throw new UserAccountException(1001, "用户不存在/被封禁");
        if (isVIP) {
            hongBao.setUrank(100);// VIP的等级设置为100
        } else {
            hongBao.setUrank(user.getRank());
        }
        hongBao.setOrderType(commonOrder.getSourceType());
        return hongBao;
    }
 
    private HongBaoV2 createFanLiUpdateHongBao(CommonOrder commonOrder, BigDecimal fanliRate, Long hongBaoId,
            boolean mianDan) throws HongBaoException, UserAccountException {
        HongBaoV2 hongBao = new HongBaoV2(hongBaoId);
        hongBao.setUpdateTime(new Date());
        // 更改状态与资金
        if (commonOrder.getState() == CommonOrder.STATE_FK) {
            hongBao.setState(HongBaoV2.STATE_BUKELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(), fanliRate.divide(new BigDecimal(100))));
            if (mianDan)
                hongBao.setMoney(commonOrder.getPayment());
        } else if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_WQ) {
            hongBao.setState(HongBaoV2.STATE_KELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), fanliRate.divide(new BigDecimal(100))));
            if (commonOrder.getSourceType() == Constant.SOURCE_TYPE_PDD)// 拼多多15天过1个小时到账
                hongBao.setPreGetTime(new Date(
                        commonOrder.getSettleTime().getTime() + 1000 * 60 * 60 * 24 * 15L + 1000 * 60 * 60 * 1L));
            else
                hongBao.setPreGetTime(new Date(commonOrder.getSettleTime().getTime() + 1000 * 60 * 60 * 24 * 15L));
            if (mianDan)
                hongBao.setMoney(commonOrder.getSettlement().compareTo(commonOrder.getPayment()) <= 0
                        ? commonOrder.getSettlement() : commonOrder.getPayment());// 返利结算与付款较小的金额
        } else if (commonOrder.getState() == CommonOrder.STATE_SX) {
            hongBao.setState(HongBaoV2.STATE_SHIXIAO);
            hongBao.setMoney(new BigDecimal(0));
        }
        return hongBao;
    }
 
    /**
     * 分享赚更新
     * 
     * @param commonOrder
     * @param fanliRate
     * @param hongBaoId
     * @param mianDan
     * @return
     * @throws HongBaoException
     * @throws UserAccountException
     */
    private HongBaoV2 createShareUpdateHongBao(CommonOrder commonOrder, BigDecimal fanliRate, Long hongBaoId)
            throws HongBaoException, UserAccountException {
        HongBaoV2 hongBao = new HongBaoV2(hongBaoId);
        hongBao.setUpdateTime(new Date());
        // 更改状态与资金
        if (commonOrder.getState() == CommonOrder.STATE_FK) {
            hongBao.setState(HongBaoV2.STATE_BUKELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(), fanliRate.divide(new BigDecimal(100))));
        } else if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_WQ) {
            hongBao.setState(HongBaoV2.STATE_KELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), fanliRate.divide(new BigDecimal(100))));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(commonOrder.getSettleTime());
            calendar.add(Calendar.MONTH, 1);
            hongBao.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25", "yyyy-M-dd")));
        } else if (commonOrder.getState() == CommonOrder.STATE_SX) {
            hongBao.setState(HongBaoV2.STATE_SHIXIAO);
            hongBao.setMoney(new BigDecimal(0));
        }
        return hongBao;
    }
 
    private HongBaoV2 createInviteUpdateHongBao(HongBaoV2 oldChild, int mainHongBaoState, BigDecimal money,
            CommonOrder commonOrder) {
        HongBaoV2 childUpdate = new HongBaoV2(oldChild.getId());
        childUpdate.setState(mainHongBaoState);
        childUpdate.setUpdateTime(new Date());
        childUpdate.setMoney(money);
        // 以实际收入为准计算预估收益
        if (mainHongBaoState == HongBaoV2.STATE_KELINGQU) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(commonOrder.getSettleTime());
            calendar.add(Calendar.MONTH, 1);
            childUpdate.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25", "yyyy-M-dd")));
        }
        return childUpdate;
    }
 
    private void addFanLiOrShareHongBao(HongBaoV2 hongBao, CommonOrder commonOrder,
            Map<Integer, HongBaoOrder> notificationMap) {
        hongBaoV2Mapper.insertSelective(hongBao);
        // 添加红包与订单的映射
        HongBaoOrder hongBaoOrder = new HongBaoOrder();
        hongBaoOrder.setCommonOrder(commonOrder);
        hongBaoOrder.setCreateTime(new Date());
        hongBaoOrder.setHongBaoV2(hongBao);
        hongBaoOrderMapper.insertSelective(hongBaoOrder);
        // 加入通知
        if (notificationMap.get(hongBao.getType()) == null) {
            HongBaoV2 tempHongBao = new HongBaoV2(hongBao.getId());
            tempHongBao.setUserInfo(hongBao.getUserInfo());
            tempHongBao.setMoney(hongBao.getMoney());
            CommonOrder tempCommonOrder = new CommonOrder(commonOrder.getId());
            tempCommonOrder.setPayment(commonOrder.getPayment());
            notificationMap.put(hongBao.getType(), new HongBaoOrder(tempCommonOrder, tempHongBao));
        } else {
            // 增加付款金额与资金
            HongBaoOrder tempHongBaoOrder = notificationMap.get(hongBao.getType());
            tempHongBaoOrder.getCommonOrder()
                    .setPayment(tempHongBaoOrder.getCommonOrder().getPayment().add(commonOrder.getPayment()));
            tempHongBaoOrder.getHongBaoV2()
                    .setMoney(tempHongBaoOrder.getHongBaoV2().getMoney().add(hongBao.getMoney()));
            notificationMap.put(hongBao.getType(), tempHongBaoOrder);
        }
    }
 
    /**
     * 创建分享赚红包
     * 
     * @param commonOrder
     * @param shareRate
     * @return
     * @throws HongBaoException
     * @throws UserAccountException
     */
    private HongBaoV2 createShareHongBao(CommonOrder commonOrder, BigDecimal shareRate, boolean isVip)
            throws HongBaoException, UserAccountException {
        HongBaoV2 hongBao = new HongBaoV2();
        hongBao.setCreateTime(new Date());
        hongBao.setType(HongBaoV2.TYPE_SHARE_GOODS);
        hongBao.setVersion(2);
        if (commonOrder.getState() == CommonOrder.STATE_FK) {
            hongBao.setState(HongBaoV2.STATE_BUKELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(), shareRate.divide(new BigDecimal(100))));
        } else if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_WQ) {
            hongBao.setState(HongBaoV2.STATE_KELINGQU);
            hongBao.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), shareRate.divide(new BigDecimal(100))));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(commonOrder.getSettleTime());
            calendar.add(Calendar.MONTH, 1);
            hongBao.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25", "yyyy-M-dd")));
        }
        UserInfo user = userInfoService.getUserById(commonOrder.getUserInfo().getId());
        if (user == null)
            throw new UserAccountException(1001, "用户不存在/被封禁");
        if (isVip)
            hongBao.setUrank(100);
        else
            hongBao.setUrank(user.getRank());
        hongBao.setUserInfo(user);
        hongBao.setOrderType(commonOrder.getSourceType());
        return hongBao;
    }
 
}