admin
2018-12-10 35ab4226899cba623b38441250920b3773325518
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
package com.yeshi.fanli.service.impl.hongbao;
 
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.ibatis.annotations.Param;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import com.yeshi.fanli.dao.hongbao.HongBaoDao;
import com.yeshi.fanli.dao.mybatis.AccountDetailsMapper;
import com.yeshi.fanli.dao.mybatis.AccountMessageMapper;
import com.yeshi.fanli.dao.mybatis.ConfigMapper;
import com.yeshi.fanli.dao.mybatis.HongBaoManageMapper;
import com.yeshi.fanli.dao.mybatis.MoneyRecordMapper;
import com.yeshi.fanli.dao.mybatis.ThreeSaleGiftMapper;
import com.yeshi.fanli.dao.mybatis.ThreeSaleMapper;
import com.yeshi.fanli.dao.mybatis.UserInfoMapper;
import com.yeshi.fanli.dao.mybatis.hongbao.HongBaoMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderItemMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderMapper;
import com.yeshi.fanli.entity.admin.OrderAdmin;
import com.yeshi.fanli.entity.bus.user.AccountDetails;
import com.yeshi.fanli.entity.bus.user.AccountMessage;
import com.yeshi.fanli.entity.bus.user.HongBao;
import com.yeshi.fanli.entity.bus.user.HongBaoExtra;
import com.yeshi.fanli.entity.bus.user.HongBaoManage;
import com.yeshi.fanli.entity.bus.user.MoneyRecord;
import com.yeshi.fanli.entity.bus.user.Order;
import com.yeshi.fanli.entity.bus.user.OrderItem;
import com.yeshi.fanli.entity.bus.user.ThreeSaleGift;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.common.Config;
import com.yeshi.fanli.entity.taobao.OrderVital;
import com.yeshi.fanli.entity.taobao.TaoBaoOrder;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.config.SystemConfigService;
import com.yeshi.fanli.service.inter.config.SystemService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoManageService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoService;
import com.yeshi.fanli.service.inter.hongbao.ThreeSaleGiftService;
import com.yeshi.fanli.service.inter.hongbao.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.order.OrderItemServcie;
import com.yeshi.fanli.service.inter.order.OrderService;
import com.yeshi.fanli.service.inter.push.PushService;
import com.yeshi.fanli.service.inter.user.AccountDetailsService;
import com.yeshi.fanli.service.inter.user.AccountMessageService;
import com.yeshi.fanli.service.inter.user.MoneyRecordService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserNotificationService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.GsonUtil;
import com.yeshi.fanli.util.HongBaoUtil;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TimeUtil;
import com.yeshi.fanli.util.Utils;
import com.yeshi.fanli.util.factory.AccountDetailsFactory;
import com.yeshi.fanli.util.factory.AccountMessageFactory;
import com.yeshi.fanli.util.factory.HongBaoFactory;
import com.yeshi.fanli.util.push.XiaoMiPushUtil;
import com.yeshi.fanli.util.taobao.TaoBaoOrderUtil;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
 
import net.sf.json.JSONObject;
 
@Service
public class HongBaoServiceImpl implements HongBaoService {
 
    @Resource
    private HongBaoDao hongBaoDao;
 
    @Resource
    private HongBaoService hongBaoService;
 
    @Resource
    private MoneyRecordService moneyRecordService;
 
    @Resource
    private UserInfoService userInfoService;
 
    @Resource
    private HongBaoManageService hongBaoManageService;
 
    @Resource
    private ConfigService configService;
 
    @Resource
    private SystemConfigService systemConfigService;
 
    @Resource
    private SystemService systemService;
 
    @Resource
    private OrderService orderService;
 
    @Resource
    private ThreeSaleSerivce threeSaleSerivce;
 
    @Resource
    private OrderItemServcie orderItemServcie;
 
    @Resource
    private ThreeSaleGiftService threeSaleGiftService;
 
    @Resource
    private AccountDetailsService accountDetailsService;
 
    @Resource
    private AccountMessageService accountMessageService;
 
    @Resource
    private HongBaoMapper hongBaoMapper;
 
    @Resource
    private OrderMapper orderMapper;
 
    @Resource
    private HongBaoManageMapper hongBaoManageMapper;
 
    @Resource
    private ThreeSaleMapper threeSaleMapper;
 
    @Resource
    private OrderItemMapper orderItemMapper;
 
    @Resource
    private ThreeSaleGiftMapper threeSaleGiftMapper;
 
    @Resource
    private OrderItemServcie orderItemService;
 
    @Resource
    private AccountDetailsMapper accountDetailsMapper;
 
    @Resource
    private AccountMessageMapper accountMessageMapper;
 
    @Resource
    private UserInfoMapper userInfoMapper;
 
    @Resource
    private ConfigMapper configMapper;
 
    @Resource
    private MoneyRecordMapper moneyRecordMapper;
 
    @Resource
    private UserNotificationService userNotificationService;
 
    private static final String NEW_USER_HONGBAO = "new_user_hongbao";
 
    public List<HongBaoExtra> getHongBao(long uid) {
        List<HongBao> list = hongBaoDao.list("from HongBao hb where hb.userInfo.id=? and hb.money > 0",
                new Serializable[] { uid });
        List<HongBaoExtra> hongBaoExtraList = new ArrayList<HongBaoExtra>();
        HongBaoExtra hbx = null;
        for (HongBao hongBao : list) {
            long sub = hongBao.getPreGettime() - System.currentTimeMillis();
            if (hongBao.getState() == Constant.HB_NOTIME && sub <= 0) {
                hongBaoService.updateStateGet(hongBao);
            }
            hbx = HongBaoUtil.convert(hongBao);
 
            hongBaoExtraList.add(hbx);
        }
 
        return hongBaoExtraList;
    }
 
    public HongBao getHongBaoById(long hid) {
        HongBao hongBao = hongBaoDao.find(HongBao.class, hid);
        return hongBao;
    }
 
    public List<HongBao> getHongBaoByUidAndState(long uid, int state) {
 
        return hongBaoDao.list("from HongBao hb where hb.userInfo.id=? and hb.state=?",
                new Serializable[] { uid, state });
 
    }
 
    public List<HongBao> getHongBaoList(int index, String state) {
        hongBaoDao.excute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                try {
                    session.getTransaction().begin();
                    Query query = session.createQuery(
                            "update HongBao hb set hb.state = 2 where hb.state = 1 and hb.preGettime <= ? ");
                    query.setParameter(0, new Date().getTime());
                    query.executeUpdate();
                    session.getTransaction().commit();
                } catch (Exception e) {
                    session.getTransaction().rollback();
                    e.printStackTrace();
                }
                return null;
            }
        });
        int start = index * Constant.PAGE_SIZE;
        if ("0".equals(state)) {
            return hongBaoDao.list("from HongBao h order by h.createtime desc", start, Constant.PAGE_SIZE,
                    new Serializable[] {});
        }
        return hongBaoDao.list("from HongBao h where h.state = ? order by h.createtime desc", start, Constant.PAGE_SIZE,
                new Serializable[] { Integer.valueOf(state) });
    }
 
    public int getCount(String state) {
        if ("0".equals(state)) {
            return ((Long) hongBaoDao.getCount("select count(*) from HongBao")).intValue();
        }
        return ((Long) hongBaoDao.getCount("select count(*) from HongBao h where h.state = ? ",
                new Serializable[] { Integer.valueOf(state) })).intValue();
    }
 
    @Transactional
    public Boolean success(OrderVital taobaorder) {
        String auctionId = taobaorder.getAuctionId() + "";
        String orderid = taobaorder.getOrderId();
        BigDecimal money = taobaorder.getMoney();
        // BigDecimal yongjin = taobaorder.getYongjin();
        // 查询出淘宝订单
        Order findOrder = orderService.getOrder(orderid, Constant.TAOBAO);
        if (findOrder == null) {
            return false;
        }
        findOrder.setMoney(money);
        // 修改订单金额
        orderService.update(findOrder);
 
        // HongBao hongBao = hongBaoService.getUnOPenHongBao(findOrder.getId());
        // if (hongBao == null) {
        // return false;
        // }
        // String rate = hongBaoManageService.get("hongbao_goods_proportion");
 
        // BigDecimal hb = BigDecimalUtil.mul(new
        // BigDecimal(rate).divide(BigDecimal.valueOf(100)), yongjin);
        // 剩余金额
        // double surplus = BigDecimalUtil.sub(yongjin, hb);
        // 修改买家的红包金额
        // hongBaoService.updateHongBaoMoney(findOrder, auctionId,
        // taobaorder.getHb(), hongBao);
        // 修改分销红包金额
        // hongBaoService.updateSaleHongBao(hongBao.getId(),
        // taobaorder.getHb());
 
        return true;
    }
 
    // public HongBao getHongBaoByOid(final long oid) {
    // return (HongBao) hongBaoDao.excute(new HibernateCallback<HongBao>() {
    //
    // public HongBao doInHibernate(Session session)
    // throws HibernateException {
    // Query query = session
    // .createQuery("from HongBao hb where hb.orderId = ? ");
    // query.setParameter(0, String.valueOf(oid));
    // List<HongBao> list = query.list();
    // if (list.size() > 0) {
    // return list.get(0);
    // }
    // return null;
    // }
    // });
    // }
 
    public BigDecimal getTotalHongBaoByUid(final long id) {
 
        return (BigDecimal) hongBaoDao.excute(new HibernateCallback<BigDecimal>() {
 
            public BigDecimal doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(
                        "select IFNULL(sum(h.money),0) from yeshi_ec_hongbao h where h.uid = ? and state=3 ");
                query.setParameter(0, id);
                List list = query.list();
                if (list.size() > 0) {
                    return new BigDecimal(list.get(0) + "");
                }
                return BigDecimal.valueOf(0);
            }
        });
 
    }
 
    public BigDecimal getMyTotalHongBaoByUid(final long id) {
 
        return (BigDecimal) hongBaoDao.excute(new HibernateCallback<BigDecimal>() {
 
            public BigDecimal doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(
                        "select IFNULL(sum(h.money),0) from yeshi_ec_hongbao h where h.uid = ? and type = 1 and state=3 ");
                query.setParameter(0, id);
                List list = query.list();
                if (list.size() > 0) {
                    return new BigDecimal(list.get(0) + "");
                }
                return BigDecimal.valueOf(0);
            }
        });
 
    }
 
    /**
     * 只是包含用户的未到账返利
     */
    public BigDecimal getUnOpenHongBaoByUid(final long id) {
        return (BigDecimal) hongBaoDao.excute(new HibernateCallback<BigDecimal>() {
 
            public BigDecimal doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(String.format(
                        "select IFNULL(sum(h.money),0) from yeshi_ec_hongbao h where h.uid = ? and h.pid is null and (state=1 or state=2) and (type!=%s and type!=%s and type !=%s)",
                        HongBao.TYPE_ERJI + "", HongBao.TYPE_YIJI + "", HongBao.TYPE_SHARE_GOODS + ""));
                query.setParameter(0, id);
                List list = query.list();
                if (list.size() > 0) {
                    return new BigDecimal(list.get(0) + "");
                }
                return BigDecimal.valueOf(0);
            }
        });
    }
 
    /**
     * 
     * @param form
     *            用户(要有创建时间)
     * @param type
     *            1.注册 2.下首单
     */
    public void setNewUserHongBao(UserInfo form, int type) {
        if (form == null) {
            return;
        }
        Config config = configService.getConfig(NEW_USER_HONGBAO);
        if ("是".equals(config.getValue())) {
            String beginTime = config.getCreatetime();
            if ((Long.parseLong(beginTime) - form.getCreatetime() > 0)) { // 开启后的新注册用户才享受
                return;
            }
            String isorder = configService.get("new_user_isorder");
            if ("是".equals(isorder)) { // 判断是否首单享受新人红包 是:首单才享受 否:登陆即送
                if (2 == type) {
                    createNewUserHongBao(form);
                }
            } else {
                if (1 == type) {
                    createNewUserHongBao(form);
                }
            }
        }
    }
 
    public void setNewUserHongBaoMyBatis(UserInfo form, int type) {
        if (form == null) {
            return;
        }
        Config config = configMapper.selectByKey(NEW_USER_HONGBAO);
        if ("是".equals(config.getValue())) {
            String beginTime = config.getCreatetime();
            if ((Long.parseLong(beginTime) - form.getCreatetime() > 0)) { // 开启后的新注册用户才享受
                return;
            }
            String isorder = configMapper.selectByKey("new_user_isorder").getValue();
            if ("是".equals(isorder)) { // 判断是否首单享受新人红包 是:首单才享受 否:登陆即送
                if (2 == type) {
                    createNewUserHongBaoMyBatis(form);
                }
            } else {
                if (1 == type) {
                    createNewUserHongBaoMyBatis(form);
                }
            }
        }
    }
 
    /**
     * 
     * 方法说明: 新人红包
     * 
     * @author mawurui createTime 2018年5月18日 下午3:29:01
     * @param form
     */
    private void createNewUserHongBao(UserInfo form) {
        String money = hongBaoManageService.get("hongbao_new_user_money");
        JSONObject json = new JSONObject();
        json.put("picture", getLogoUrl());
        HongBao hongBao = HongBaoFactory.createHongBao(new BigDecimal(money), json.toString(), null, null, form,
                Constant.HB_NEWUSER);
        hongBao.setGetTime(System.currentTimeMillis());
        hongBao.setState(Constant.HB_GOT);
        hongBaoDao.save(hongBao);
        MoneyRecord moneyRecord = new MoneyRecord(form, hongBao, new BigDecimal(money), "新人红包", "",
                System.currentTimeMillis(), 1);
        moneyRecordService.addMoneyRecord(moneyRecord);
        AccountDetails ac = AccountDetailsFactory.create("+" + money, AccountDetailsFactory.XINREN, null, null, form);
        AccountMessage am = AccountMessageFactory.create(form, null, new BigDecimal(money),
                AccountMessageFactory.NEWUSER);
        accountDetailsService.save(ac);
        accountMessageService.save(am);
        userInfoService.addMoney(form, new BigDecimal(money));
        com.yeshi.fanli.entity.system.System system = form.getSystem();
        if (system != null) {
            userNotificationService.newerHongBao(form.getId(), new BigDecimal(money));
        }
    }
 
    private void createNewUserHongBaoMyBatis(UserInfo form) {
        HongBaoManage hongBaoManager = hongBaoManageMapper.selectByKey("hongbao_new_user_money");
        String money = hongBaoManager.getValue();
 
        JSONObject json = new JSONObject();
        json.put("picture", getLogoUrl());
        HongBao hongBao = HongBaoFactory.createHongBao(new BigDecimal(money), json.toString(), null, null, form,
                Constant.HB_NEWUSER);
        hongBao.setGetTime(System.currentTimeMillis());
        hongBao.setState(Constant.HB_GOT);
        hongBaoMapper.insertSelective(hongBao);
 
        MoneyRecord moneyRecord = new MoneyRecord(form, hongBao, new BigDecimal(money), "新人红包", "",
                System.currentTimeMillis(), 1);
        moneyRecordMapper.insertSelective(moneyRecord);
 
        AccountDetails ac = AccountDetailsFactory.create("+" + money, AccountDetailsFactory.XINREN, null, null, form);
        accountDetailsMapper.insertSelective(ac);
 
        userInfoMapper.addHongBaoByUid(form.getId(), new BigDecimal(money));
        userNotificationService.newerHongBao(form.getId(), new BigDecimal(money));
    }
 
    private String getLogoUrl() {
        ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = servletContainer.getRequest();
        String packages = request.getParameter("packages");
        String platform = request.getParameter("platform");
        com.yeshi.fanli.entity.system.System system = systemService.getSystem(platform, packages);
        return systemConfigService.get("logo", system);
    }
 
    @SuppressWarnings("unchecked")
    public List<OrderAdmin> getOrderAdminList(int pageIndex, String key) {
 
        return (List<OrderAdmin>) hongBaoDao.excute(new HibernateCallback<List<OrderAdmin>>() {
 
            public List<OrderAdmin> doInHibernate(Session session) throws HibernateException {
                boolean IsNum = Utils.isNum(key);
                String sql = "SELECT o.*,shb FROM yeshi_ec_order o left join yeshi_ec_user u on u.id=o.uid LEFT JOIN (SELECT hb.oid AS id,SUM(hb.money) AS shb FROM yeshi_ec_hongbao hb GROUP BY hb.oid) a ON a.id=o.id";
                if (IsNum) {
                    if (key.trim().length() < 18) {
                        long uid = Long.parseLong(key);
                        sql += " where o.uid=" + uid + " order by o.`third_createtime` desc";
                    } else {
                        sql += " where o.orderid like '%" + key + "%' order by o.`third_createtime` desc";
                    }
 
                } else {
                    sql += " where u.nick_name like '%" + key + "%' order by o.`third_createtime` desc";
                }
                SQLQuery query = session.createSQLQuery(sql);
                query.addEntity(Order.class).addScalar("shb", StandardBasicTypes.BIG_DECIMAL)
                        .setResultTransformer(Transformers.aliasToBean(OrderAdmin.class));
                query.setFirstResult((pageIndex - 1) * Constant.PAGE_SIZE);
                query.setMaxResults(Constant.PAGE_SIZE);
                List list = query.list();
                return list;
            }
        });
    }
 
    public List<HongBao> getHongBaoList(int pageIndex, long uid) {
        List<HongBao> list = hongBaoDao.list("from HongBao hb where hb.userInfo.id = ? order by hb.createtime desc",
                (pageIndex - 1) * Constant.PAGE_SIZE, Constant.PAGE_SIZE, new Serializable[] { uid });
        // for (HongBao hongBao : list) {
        // String orderId = hongBao.getOrderId();
        // if (!StringUtil.isNullOrEmpty(orderId)) {
        // Order o = orderService.find(Long.parseLong(orderId));
        // hongBao.setOrder(o);
        // }
        // }
        return list;
    }
 
    public int getCount(long uid) {
        return (int) hongBaoDao.getCount("select count(*) from HongBao hb where hb.userInfo.id = ? ",
                new Serializable[] { uid });
    }
 
    public BigDecimal getCanOpenHongBaoByUid(final long id) {
        return (BigDecimal) hongBaoDao.excute(new HibernateCallback<BigDecimal>() {
 
            public BigDecimal doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(
                        "select IFNULL(sum(h.money),0) from yeshi_ec_hongbao h where h.uid = ? and state=2 ");
                query.setParameter(0, id);
                List list = query.list();
                if (list.size() > 0) {
                    return new BigDecimal(list.get(0) + "");
                }
                return BigDecimal.valueOf(0);
            }
        });
    }
 
    public HongBao getUnOPenHongBao(long orderid) {
        List<HongBao> list = hongBaoDao.list("from HongBao hb where hb.order.id=? and (hb.state=1 or hb.state=2)",
                new Serializable[] { orderid + "" });
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
 
    /**
     * 修改红包金额
     */
    public void updateHongBaoMoney(Order order, String auctionId, BigDecimal hb, HongBao hongBao) {
        List<String> tbImg = TaoBaoUtil.getTbImg(auctionId);
        JSONObject param = new JSONObject();
        if (tbImg.size() > 0) {
            param.put("picture", tbImg.get(0));
        }
        int updateNum = hongBaoDao.update(
                "update HongBao hb set hb.money=? , hb.param=? where hb.order.id = ? and (hb.state=1 or hb.state=2)",
                new Serializable[] { hb, param.toString(), order.getId() + "" });
        BigDecimal oldMoney = hongBao.getMoney();
        if (oldMoney.equals(BigDecimal.valueOf(0)) && updateNum > 0) {
            UserInfo userInfo = order.getUserInfo();
            LogHelper.userInfo("用户[" + GsonUtil.toJson(userInfo) + "],获得红包金额:[" + hb + "]");
            com.yeshi.fanli.entity.system.System system = userInfo.getSystem();
            if (system != null) {
                // XingePushUtil.pushByHongBao(userInfo.getId(), system);
                XiaoMiPushUtil.pushByHongBao(userInfo.getId().toString(), system);
            }
        } else if (!oldMoney.equals(BigDecimal.valueOf(0)) && updateNum > 0) {
            LogHelper.userInfo("用户[" + GsonUtil.toJson(order.getUserInfo()) + "],红包金额发生变化:[" + hb + "]");
        }
    }
 
    @Transactional
    public void updateSaleHongBao(long id, BigDecimal surplus) {
        // 查询到所有分销红包
        List<HongBao> salehbList = hongBaoService.findSaleHongBaoList(id);
        Map<String, String> map = hongBaoManageService.convertMap();
        for (HongBao hongBao : salehbList) {
            UserInfo userInfo = hongBao.getUserInfo();
            int rank = hongBao.getUrank();
            // 分销分成比率key命名为:sale_(红包类型(1级分销为6,2级分销为7))_(rank(暂时分为4种,0是普通(也就是没有分成),1铜管,2银冠,3金冠)
            String rate = map.get("sale_" + hongBao.getType() + "_" + rank);
            // 等于空就不用修改了,直接continue
            if (StringUtil.isNullOrEmpty(rate) || "0".equals(rate)) {
                continue;
            }
            BigDecimal hb = MoneyBigDecimalUtil.mul(surplus, new BigDecimal(rate).divide(BigDecimal.valueOf(100)));
            hongBaoDao.update("update HongBao hb set hb.money=? where hb.id = ? ",
                    new Serializable[] { hb, hongBao.getId() });
            LogHelper.userInfo("用户[" + GsonUtil.toJson(userInfo) + "],获得分销红包金额:[" + hb + "]");
        }
    }
 
    public List<HongBao> findSaleHongBaoList(long id) {
        return hongBaoDao.list("from HongBao hb where hb.parent.id = ?", new Serializable[] { id });
    }
 
    @Transactional
    public void save(HongBao hongBao) {
        hongBaoDao.save(hongBao);
    }
 
    public double findThreeSaleMoney(final long id) {
        return (Double) hongBaoDao.excute(new HibernateCallback<Double>() {
 
            public Double doInHibernate(Session session) throws HibernateException {
                SQLQuery query = session.createSQLQuery(
                        "SELECT IFNULL(SUM(money),0) FROM `yeshi_ec_hongbao` WHERE uid=? AND (`type` = 6 OR `type` = 7) and state = 3");
                query.setParameter(0, id);
                return Double.parseDouble(query.uniqueResult() + "");
            }
        });
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HongBaoExtra open(long hid, String ip) {
        return (HongBaoExtra) hongBaoDao.excute(new HibernateCallback<HongBaoExtra>() {
            @Override
            public HongBaoExtra doInHibernate(Session session) throws HibernateException {
                HongBao oldHongBao = hongBaoDao.find(HongBao.class, hid);
                if (oldHongBao == null) {
                    return null;
                }
                OrderItem orderItem = null;
                ThreeSaleGift tsg = null;
                int type = oldHongBao.getType();
                if (oldHongBao.getOrder() != null) {
                    orderItem = orderItemServcie.conver(oldHongBao);
                    if (orderItem == null) {
                        return null;
                    }
                } else if (type == Constant.ONESALE || type == Constant.TWOSALE) {
                    HongBao parent = oldHongBao.getParent();
                    OrderItem parentOrderItem = orderItemServcie.conver(parent);
                    tsg = threeSaleGiftService.conver(oldHongBao, parentOrderItem);
                    if (tsg == null) {
                        return null;
                    }
                }
 
                long currentTimeMillis = System.currentTimeMillis();
                Query query = session.createQuery(
                        "update HongBao hb set hb.state = ?,hb.getIp=?,hb.getTime=? where hb.id = ? and hb.state = ?");
                query.setParameter(0, Constant.HB_GOT);
                query.setParameter(1, ip);
                query.setParameter(2, currentTimeMillis);
                query.setParameter(3, hid);
                query.setParameter(4, Constant.HB_GET);
                int update = query.executeUpdate();
                if (update == 1) {
                    if (orderItem != null) {
                        orderItem.setState(3);
                        orderItem.setFanTime(currentTimeMillis);
                        orderItemServcie.update(orderItem);
                    }
                    if (tsg != null) {
                        tsg.setState(3);
                        tsg.setFanTime(currentTimeMillis);
                        threeSaleGiftService.update(tsg);
                    }
                    HongBao find = hongBaoDao.find(HongBao.class, hid);
                    userInfoService.addMoney(find.getUserInfo(), find.getMoney());
                    HongBaoExtra hongBaoExtra = HongBaoUtil.convert(find);
                    hongBaoExtra.setoState(true);
                    MoneyRecord moneyRecord = new MoneyRecord(find.getUserInfo(), find, find.getMoney(),
                            hongBaoExtra.getTitle(), "", currentTimeMillis, 1);
                    moneyRecordService.addMoneyRecord(moneyRecord);
                    AccountDetails ad = AccountDetailsFactory.create(find, orderItem);
                    AccountMessage am = AccountMessageFactory.create(find);
                    accountDetailsService.save(ad);
                    accountMessageService.save(am);
                    return hongBaoExtra;
                }
                return null;
            }
        });
    }
 
    @Override
    public void updateStateGet(HongBao hongBao) {
        hongBaoDao.excute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                long currentTimeMillis = System.currentTimeMillis();
                Query query = session.createQuery(
                        "update HongBao hb set hb.state = ? where hb.id = ? and hb.state = ? and hb.preGettime <= ? ");
                query.setParameter(0, Constant.HB_GET);
                query.setParameter(1, hongBao.getId());
                query.setParameter(2, Constant.HB_NOTIME);
                query.setParameter(3, currentTimeMillis);
 
                query.executeUpdate();
                return null;
            }
        });
    }
 
    @Transactional
    public void relevantInvalid(long hid) {
        hongBaoDao.excute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                // and version=1
                Query query = session
                        .createSQLQuery("update yeshi_ec_hongbao set state=? where (id=? or `pid`=?) and state != 3 ");
                query.setParameter(0, Constant.HB_DISABLE);
                query.setParameter(1, hid);
                query.setParameter(2, hid);
                query.executeUpdate();
                return null;
            }
        });
    }
 
    @Transactional
    public void relevantInvalidVersion2(long hid) {
        List<HongBao> hbList = hongBaoMapper.selectByIdOrPid(hid);
        if (hbList != null)
            for (HongBao hb : hbList) {
                HongBao updateHongBao = new HongBao();
                updateHongBao.setId(hb.getId());
 
                if (hb.getState() == HongBao.STATE_SHIXIAO)
                    continue;
                // 已经领取过的红包要退款
                if (hb.getState() == HongBao.STATE_YILINGQU) {
                    // 判断该用户的账户余额是否够扣款
                    UserInfo user = userInfoMapper.selectByPrimaryKeyForUpdate(hb.getUserInfo().getId());
                    if (user != null) {
                        userInfoMapper.subHongBaoByUid(user.getId(), hb.getMoney());
                        // 添加账目明细
                        if (hb.getOrderItemId() != null) {
                            AccountDetails accountDetails = AccountDetailsFactory.create("-" + hb.getMoney(),
                                    AccountDetailsFactory.TUIKUAN, new OrderItem(hb.getOrderItemId()), null,
                                    hb.getUserInfo());
                            accountDetailsMapper.insertSelective(accountDetails);
                        }
 
                        // 添加账户消息
                        AccountMessage accountMessage = AccountMessageFactory.create(hb.getUserInfo(),
                                hb.getOrder().getOrderId(), hb.getMoney(), AccountMessageFactory.SERVICE);
                        accountMessageMapper.insertSelective(accountMessage);
                    }
                }
                // 更改红包状态
                updateHongBao.setState(HongBao.STATE_SHIXIAO);
                hongBaoMapper.updateByPrimaryKeySelective(updateHongBao);
            }
    }
 
    @Override
    public List<HongBao> getHongBaoListAll(long uid) {
        List<HongBao> list = hongBaoDao.list("from HongBao hb where hb.userInfo.id = ? ", new Serializable[] { uid });
        // for (HongBao hongBao : list) {
        // String orderId = hongBao.getOrderId();
        // if (!StringUtil.isNullOrEmpty(orderId)) {
        // Order o = orderService.find(Long.parseLong(orderId));
        // hongBao.setOrder(o);
        // }
        // }
        return list;
    }
 
    @Override
    public List<HongBao> findThreeSaleHongBao(long id) {
 
        List<HongBao> list = hongBaoDao.list(
                "from HongBao hb where hb.userInfo.id = ? and (type = 6 OR type = 7) and state = 3 ",
                new Serializable[] { id });
        // for (HongBao hongBao : list) {
        // String orderId = hongBao.getParent().getOrderId();
        // if (!StringUtil.isNullOrEmpty(orderId)) {
        // Order o = orderService.find(Long.parseLong(orderId));
        // hongBao.setOrder(o);
        // }
        // }
        return list;
    }
 
    @Override
    public List<HongBao> findHongBaoByOrderList(long oid) {
        return hongBaoMapper.selectByOid(oid);
    }
 
    @Override
    public List<HongBao> findChildHongBaoList(long id) {
        return hongBaoDao.list("from HongBao hb where hb.parent.id = ?", new Serializable[] { id });
    }
 
    @Override
    public void update(HongBao hb) {
        hongBaoDao.update(hb);
    }
 
    /**
     * 对老版本的红包进行返利
     */
    @Override
    @Transactional
    public void oldVersionFanLi() {
        List<HongBao> list = hongBaoDao
                .list("from HongBao hb where hb.version=1 and hb.preGettime<=" + System.currentTimeMillis());
        list.parallelStream().forEach(hb -> {
            hongBaoDao.excute(new HibernateCallback() {
                @Override
                public Object doInHibernate(Session session) throws HibernateException {
                    if (hb.getMoney().compareTo(new BigDecimal(0)) == 0) {
                        return null;
                    }
                    Query query = session.createQuery(
                            "update HongBao hb set hb.state=3 where hb.id=? and (hb.state=1 or hb.state=2)");
                    query.setParameter(0, hb.getId());
                    int i = query.executeUpdate();
                    if (i == 1) {
                        long currentTimeMillis = System.currentTimeMillis();
                        userInfoService.addMoney(hb.getUserInfo(), hb.getMoney());
                        if (hb.getOrder() != null) {
                            List<OrderItem> orderItemList = hb.getOrder().getOrderItemList();
                            if (orderItemList != null) {
                                orderItemList.parallelStream().forEach(oi -> {
                                    oi.setState(3);
                                    oi.setFanTime(currentTimeMillis);
                                    orderItemServcie.update(oi);
                                });
                            }
                        }
                        HongBaoExtra hongBaoExtra = HongBaoUtil.convert(hb);
                        MoneyRecord moneyRecord = new MoneyRecord(hb.getUserInfo(), hb, hb.getMoney(),
                                hongBaoExtra.getTitle(), "", currentTimeMillis, 1);
                        moneyRecordService.addMoneyRecord(moneyRecord);
                        AccountDetails ad = AccountDetailsFactory.create(hb, null);
                        AccountMessage am = AccountMessageFactory.create(hb);
                        accountDetailsService.save(ad);
                        accountMessageService.save(am);
                    }
                    return null;
                }
            });
        });
    }
 
    @Override
    public HongBao getHongBaoByOid(long oid) {
        List<HongBao> list = hongBaoDao.list("from HongBao hb where hb.order.id=? and hb.version=1", 0, 1,
                new Serializable[] { oid });
        if (list != null && list.size() > 0)
            return list.get(0);
        return null;
    }
 
    /**
     * 让红包失效
     * 
     * @param hongBao
     */
    @Transactional
    private void invalidHongBao(HongBao hongBao) {
        if (hongBao.getState() == HongBao.STATE_SHIXIAO)
            return;
        // 让主红包失效
        HongBao updateHongBao = new HongBao();
        updateHongBao.setId(hongBao.getId());
        updateHongBao.setState(HongBao.STATE_SHIXIAO);
        hongBaoMapper.updateByPrimaryKeySelective(updateHongBao);
        // 让子红包失效
        if (hongBao.getHasChild()) {
            List<HongBao> hongBaoList = hongBaoMapper.findChildHongBaoList(hongBao.getId());
            if (hongBaoList != null) {
                for (HongBao childHongBao : hongBaoList) {
                    HongBao updateChildHongBao = new HongBao();
                    updateChildHongBao.setId(childHongBao.getId());
                    updateChildHongBao.setState(HongBao.STATE_SHIXIAO);
                    hongBaoMapper.updateByPrimaryKeySelective(updateChildHongBao);
                }
            }
        }
 
        // 如果红包已经领取则减去用户资金
        if (hongBao.getState() == HongBao.STATE_YILINGQU) {
            // 未完待续
 
        }
    }
 
    @Transactional
    public void updateHongBao(HongBao hongBao, TaoBaoOrder taoBaoOrder) {
        BigDecimal proportion = hongBaoManageService.getFanLiRate();
        BigDecimal rate = proportion.divide(new BigDecimal(100));
        // 更新红包项
        HongBao updateHongBao = new HongBao();
        updateHongBao.setId(hongBao.getId());
        List<HongBao> childHongBaoList = null;
        if (hongBao.getHasChild())
            childHongBaoList = hongBaoMapper.findChildHongBaoList(hongBao.getId());
 
        if ("订单失效".equals(taoBaoOrder.getOrderState())) {// 订单失效,也使红包失效
            invalidHongBao(hongBao);
            return;
        } else if ("订单付款".equals(taoBaoOrder.getOrderState()) || "订单成功".equals(taoBaoOrder.getOrderState())) {//
            // 更新红包的信息
            BigDecimal estimate = taoBaoOrder.getEstimate();
            BigDecimal money = MoneyBigDecimalUtil.mul(estimate, rate);
            updateHongBao.setMoney(money);
            updateHongBao.setState(HongBao.STATE_BUKELINGQU);
            updateHongBao.setPreGettime(0L);
 
            if (childHongBaoList != null && childHongBaoList.size() > 0) {// 存在子红包
                childHongBaoList.parallelStream().forEach(hb -> {
                    HongBao updateChildHongBao = new HongBao();
                    updateChildHongBao.setId(hb.getId());
                    if (hb.getState() != HongBao.STATE_SHIXIAO && hb.getState() != HongBao.STATE_YILINGQU)
                        updateChildHongBao.setState(HongBao.STATE_BUKELINGQU);
                    // 更新子红包的状态和返利的金额
                    BigDecimal saleRate;
                    HongBaoManage hbm = hongBaoManageMapper.selectByKey("sale_" + hb.getType() + "_" + hb.getUrank());
                    if (hbm == null)
                        saleRate = new BigDecimal(0);
                    else
                        saleRate = new BigDecimal(hbm.getValue()).divide(new BigDecimal(100));
 
                    updateChildHongBao.setMoney(MoneyBigDecimalUtil.mul(money, saleRate));
                    // 更新子红包的信息
                    hongBaoMapper.updateByPrimaryKeySelective(updateChildHongBao);
                });
            }
        } else if ("订单结算".equals(taoBaoOrder.getOrderState())) {// 更新预估获取时间
            BigDecimal money = MoneyBigDecimalUtil.mul(taoBaoOrder.geteIncome(), rate);
            // 设置预计领取时间
            long settlementTime = TimeUtil.convertDateToTemp2(taoBaoOrder.getSettlementTime().trim());
            // 预计领取时间
            long preGetTime = settlementTime + 1000 * 60 * 60 * 24 * 15L;// 结算后15日领取
            updateHongBao.setPreGettime(preGetTime);
            // 更新结算时间
            updateHongBao.setBalanceTime(new Date(settlementTime));
            hongBaoMapper.updateByPrimaryKeySelective(updateHongBao);
            if (childHongBaoList != null && childHongBaoList.size() > 0)
                childHongBaoList.parallelStream().forEach(hb -> {
                    HongBao updateChildHongBao = new HongBao();
                    updateChildHongBao.setId(hb.getId());
                    if (hb.getState() != HongBao.STATE_SHIXIAO && hb.getState() != HongBao.STATE_YILINGQU)
                        updateChildHongBao.setState(HongBao.STATE_BUKELINGQU);
                    // 更新子红包的状态和返利的金额
                    BigDecimal saleRate;
                    HongBaoManage hbm = hongBaoManageMapper.selectByKey("sale_" + hb.getType() + "_" + hb.getUrank());
                    if (hbm == null)
                        saleRate = new BigDecimal(0);
                    else
                        saleRate = new BigDecimal(hbm.getValue()).divide(new BigDecimal(100));
 
                    updateChildHongBao.setMoney(MoneyBigDecimalUtil.mul(money, saleRate));
                    // 结算后的下个月25日返利
                    updateChildHongBao.setPreGettime(TaoBaoOrderUtil.computeInviteFanLiTime(settlementTime));
                    // 更新子红包的信息
                    hongBaoMapper.updateByPrimaryKeySelective(updateChildHongBao);
                });
 
            BigDecimal estimate = taoBaoOrder.geteIncome();
            updateHongBao.setPayMoney(taoBaoOrder.getSettlement());
            updateHongBao.setMoney(MoneyBigDecimalUtil.mul(estimate, rate));
        }
 
        hongBaoMapper.updateByPrimaryKeySelective(updateHongBao);
    }
 
    @Override
    public void connectHongBaoAndOrderItem() {
        List<String> orderList = hongBaoMapper.selectMultiHongBaoOrder();
        List<String> unavaiableList = new ArrayList<>();
        for (String orderId : orderList) {
            List<HongBao> list = hongBaoMapper.selectByOrderIdSortWithAucationIdAndPayMoney(orderId);
            List<OrderItem> orderItemList = orderItemMapper.selectByOrderIdSortWithAucationIdAndPayMoney(orderId);
            if (list.size() != orderItemList.size()) {
                unavaiableList.add(orderId);
            }
            System.out.println("-------------------------:" + orderId);
            for (int i = 0; i < list.size(); i++) {
                HongBao updateHongBao = new HongBao();
                updateHongBao.setId(list.get(i).getId());
                updateHongBao.setOrderItemId(orderItemList.get(i).getId());
                hongBaoMapper.updateByPrimaryKeySelective(updateHongBao);
                // System.out.println(list.get(i).getAuctionId() + "-" +
                // orderItemList.get(i).getAuctionId());
                // System.out.println(
                // list.get(i).getPayMoney().toString() + "-" +
                // orderItemList.get(i).getPayMoney().toString());
            }
        }
        System.out.println("总共的订单:" + orderList.size());
        for (String order : unavaiableList)
            System.out.println("订单:" + order);
    }
 
    @Transactional
    @Override
    public void addHongBao(Order order, TaoBaoOrder taoBaoOrder, Long orderItemId) {
        OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
        // 订单返利比例
        BigDecimal proportion = hongBaoManageService.getFanLiRate();
        BigDecimal baseRate = proportion.divide(new BigDecimal(100));
 
        // 创建红包
        JSONObject data = new JSONObject();
        HongBao hongBao = null;
        if (taoBaoOrder.getOrderState().equalsIgnoreCase("订单结算"))
            // 订单结算应该取结算金额与预估收入
            hongBao = HongBaoFactory.createHongBao(MoneyBigDecimalUtil.mul(baseRate, taoBaoOrder.geteIncome()),
                    data.toString(), order.getId(), null, order.getUserInfo(), 1, taoBaoOrder.getSettlement(),
                    taoBaoOrder.getAuctionId());
        else
            hongBao = HongBaoFactory.createHongBao(MoneyBigDecimalUtil.mul(baseRate, taoBaoOrder.getEstimate()),
                    data.toString(), order.getId(), null, order.getUserInfo(), 1, taoBaoOrder.getPayment(),
                    taoBaoOrder.getAuctionId());
 
        hongBao.setOrderId(taoBaoOrder.getOrderId());
        hongBao.setOrderItemId(orderItem.getId());
        hongBao.setPreGettime(0L);
        if (taoBaoOrder.getOrderState().equalsIgnoreCase("订单结算")
                && !StringUtil.isNullOrEmpty(taoBaoOrder.getSettlementTime()))
            hongBao.setBalanceTime(
                    new Date(TimeUtil.convertToTimeTemp(taoBaoOrder.getSettlementTime(), "yyyy-MM-dd HH:mm:ss")));
 
        UserInfo boss = threeSaleMapper.selectBoss(order.getUserInfo().getId());
 
        if (boss != null) {
            hongBao.setHasChild(true);
        }
 
        // 如果失效就判定已经失效
        if (taoBaoOrder.getOrderState().equalsIgnoreCase("订单失效"))
            hongBao.setState(HongBao.STATE_SHIXIAO);
 
        hongBaoMapper.insertSelective(hongBao);
        // 通知用户订单被统计
        if (!taoBaoOrder.getOrderState().equalsIgnoreCase("订单失效")) {
            try {
                userNotificationService.orderFanliStatisticed(hongBao.getUserInfo().getId(), order.getOrderId());
            } catch (Exception e) {
            }
        }
 
        // 提成订单不处理失效订单
        if (taoBaoOrder.getOrderState().equalsIgnoreCase("订单失效"))
            return;
        if (boss != null) {
            // 计算上级返利金额
            HongBaoManage hbm = hongBaoManageMapper
                    .selectByKey("sale_6_" + (boss.getRank() == null ? 0 : boss.getRank()));
            BigDecimal rate = null;
            if (hbm == null)
                rate = new BigDecimal(0);
            else
                rate = new BigDecimal(hbm.getValue()).divide(new BigDecimal(100));
            if (rate.compareTo(new BigDecimal(0)) > 0) {
                HongBao hongBao2 = null;
                if (taoBaoOrder.getOrderState().equalsIgnoreCase("订单结算")) {
                    // 订单结算应该取结算金额与预估收入
                    hongBao2 = HongBaoFactory.createHongBao(
                            MoneyBigDecimalUtil.mul(rate, MoneyBigDecimalUtil.mul(taoBaoOrder.geteIncome(), baseRate)),
                            null, hongBao, boss, Constant.ONESALE);
                } else {
                    hongBao2 = HongBaoFactory.createHongBao(
                            MoneyBigDecimalUtil.mul(rate, MoneyBigDecimalUtil.mul(taoBaoOrder.getEstimate(), baseRate)),
                            null, hongBao, boss, Constant.ONESALE);
                }
 
                HongBaoFactory.createHongBao(
                        MoneyBigDecimalUtil.mul(rate, MoneyBigDecimalUtil.mul(taoBaoOrder.getEstimate(), baseRate)),
                        null, hongBao, boss, Constant.ONESALE);
                // 设置订单号
                hongBao2.setOrderId(taoBaoOrder.getOrderId());
 
                hongBaoMapper.insertSelective(hongBao2);
 
                try {
                    // 通知提成订单被统计
                    userNotificationService.tiChengStatisticed(hongBao2.getUserInfo().getId(), hongBao2.getOrderId(),
                            hongBao2.getMoney());
                } catch (Exception e) {
                }
 
            }
 
            UserInfo boss2 = threeSaleMapper.selectBoss(boss.getId());
            // 计算上上级返利
            if (boss2 != null) {
                hbm = hongBaoManageMapper.selectByKey("sale_7_" + (boss.getRank() == null ? 0 : boss.getRank()));
                if (hbm == null)
                    rate = new BigDecimal(0);
                else
                    rate = new BigDecimal(hbm.getValue()).divide(new BigDecimal(100));
                if (rate.compareTo(new BigDecimal(0)) > 0) {
                    // 订单结算应该取结算金额与预估收入
                    HongBao hongBao3 = null;
                    if (taoBaoOrder.getOrderState().equalsIgnoreCase("订单结算"))
                        hongBao3 = HongBaoFactory.createHongBao(
                                MoneyBigDecimalUtil.mul(rate,
                                        MoneyBigDecimalUtil.mul(taoBaoOrder.geteIncome(), baseRate)),
                                null, hongBao, boss2, Constant.TWOSALE);
                    else
                        hongBao3 = HongBaoFactory.createHongBao(
                                MoneyBigDecimalUtil.mul(rate,
                                        MoneyBigDecimalUtil.mul(taoBaoOrder.getEstimate(), baseRate)),
                                null, hongBao, boss2, Constant.TWOSALE);
                    // 设置返利订单号
                    hongBao3.setOrderId(taoBaoOrder.getOrderId());
                    hongBaoMapper.insertSelective(hongBao3);
 
                    try {
                        // 通知提成订单被统计
                        userNotificationService.tiChengStatisticed(hongBao3.getUserInfo().getId(),
                                hongBao3.getOrderId(), hongBao3.getMoney());
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
 
    @Override
    public BigDecimal getTotalTiChengMoney(Long uid) {
 
        return hongBaoMapper.getTotalTiChengMoney(uid);
    }
 
    @Override
    public BigDecimal getUnGetTiChengMoney(Long uid) {
        return hongBaoMapper.getUnGetTiChengMoney(uid);
    }
 
    @Override
    public List<HongBao> getTiChengHongBaoList(Long uid, int page) {
        return hongBaoDao.list(
                "from HongBao hb where hb.userInfo.id=? and hb.version=2  and (hb.type=6 or hb.type=7 or hb.type=20 or hb.type=21 or hb.type=22)  order by hb.createtime desc",
                (page - 1) * Constant.PAGE_SIZE, Constant.PAGE_SIZE, new Serializable[] { uid });
    }
 
    @Override
    public long getTiChengHongBaoListCount(Long uid) {
        return hongBaoDao.getCount(
                "select count(*) from HongBao hb where hb.userInfo.id=? and hb.version=2  and (hb.type=6 or hb.type=7 or hb.type=20 or hb.type=21 or hb.type=22)",
                new Serializable[] { uid });
    }
 
    @Override
    public List<HongBao> selectOrderByUid(int pageIndex, int pageSize, Long uid, String startTime, String endTime) {
        return hongBaoMapper.selectOrderByUid((pageIndex - 1) * pageSize, pageSize, uid, startTime, endTime);
    }
 
    @Override
    public int countOrderByUid(Long uid, String startTime, String endTime) {
        return hongBaoMapper.countOrderByUid(uid, startTime, endTime);
    }
 
    @Override
    public double countProfitByUid(Long uid, String startTime, String endTime) {
        return hongBaoMapper.countProfitByUid(uid, startTime, endTime);
    }
 
    @Override
    public int getCountByUid(Long uid) {
        return hongBaoMapper.getCountByUid(uid);
    }
 
    @Override
    public int getCountCancelByUid(Long uid) {
        return hongBaoMapper.getCountCancelByUid(uid);
    }
 
    @Override
    public Long getCountByUidOrder(Long uid) {
        return hongBaoMapper.getCountByUidOrder(uid);
    }
 
    @Override
    public double countReceiveMoneysByUid(Long uid) {
        return hongBaoMapper.countReceiveMoneysByUid(uid);
    }
 
    @Override
    public List<HongBao> findChildHongBaoList(Long pid) {
        return hongBaoMapper.findChildHongBaoList(pid);
    }
 
    @Override
    public List<HongBao> queryByOrderIDAndPayMoney(Long oid, BigDecimal payMoney) {
        return hongBaoMapper.queryByOrderIDAndPayMoney(oid, payMoney);
    }
 
    @Override
    public List<HongBao> queryByOrderIDAndUid(Long oid, Long uid) {
        return hongBaoMapper.queryByOrderIDAndUid(oid, uid);
    }
 
    @Override
    public long countByUidSelf(Long uid, Integer isToday, Integer isMonth) {
        return hongBaoMapper.countByUidSelf(uid, isToday, isMonth);
    }
 
    @Override
    public double countForecastMoneysByUid(Long uid) {
        return hongBaoMapper.countForecastMoneysByUid(uid);
    }
 
    @Override
    public HongBao selectByPrimaryKey(Long id) {
        return hongBaoMapper.selectByPrimaryKey(id);
    }
 
    @Override
    public Long getLastOrderTime(Long uid) {
        return hongBaoMapper.getLastOrderTime(uid);
    }
 
    @Override
    public Double getMaxMoney(Integer typeArray[]) {
        return hongBaoMapper.getMaxMoney(typeArray);
    }
 
    @Override
    public List<HongBao> listShareAndInviteMoney(long start, int count, String date) {
        return hongBaoMapper.listShareAndInviteMoney(start, count, date);
    }
 
    @Override
    public int getTotalTiChengCount(Long uid) {
 
        return hongBaoMapper.getTotalTiChengCount(uid);
    }
 
}