admin
2019-07-16 013a3a80d8b91506307995e282337143c7b09783
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
package com.yeshi.fanli.service.impl.order;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
 
import javax.annotation.Resource;
 
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
import com.yeshi.fanli.dao.mybatis.HongBaoV2Mapper;
import com.yeshi.fanli.dao.mybatis.money.ExtractCheckCompensateMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderGoodsMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderTradeIdMapMapper;
import com.yeshi.fanli.dao.mybatis.order.HongBaoOrderMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderRepairHistoryMapper;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.goods.CommonGoods;
import com.yeshi.fanli.entity.money.ExtractCheckCompensate;
import com.yeshi.fanli.entity.money.UserMoneyDetail;
import com.yeshi.fanli.entity.order.CommonOrder;
import com.yeshi.fanli.entity.order.CommonOrderGoods;
import com.yeshi.fanli.entity.order.CommonOrderTradeIdMap;
import com.yeshi.fanli.entity.order.HongBaoOrder;
import com.yeshi.fanli.entity.order.OrderRepairHistory;
import com.yeshi.fanli.entity.order.ShareGoodsActivityOrder;
import com.yeshi.fanli.entity.push.PushInfo;
import com.yeshi.fanli.entity.push.PushInfo.PushTypeEnum;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.entity.taobao.TaoBaoOrder;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanOrder;
import com.yeshi.fanli.exception.HongBaoException;
import com.yeshi.fanli.exception.PushException;
import com.yeshi.fanli.exception.money.UserMoneyDetailException;
import com.yeshi.fanli.exception.push.PushInfoException;
import com.yeshi.fanli.exception.taobao.TaobaoGoodsDownException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.goods.CommonGoodsService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoManageService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoV2Service;
import com.yeshi.fanli.service.inter.msg.UserMoneyMsgNotificationService;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoOrderService;
import com.yeshi.fanli.service.inter.order.OrderRepairHistoryService;
import com.yeshi.fanli.service.inter.order.OrderRepairService;
import com.yeshi.fanli.service.inter.order.ShareGoodsActivityOrderService;
import com.yeshi.fanli.service.inter.push.PushInfoService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoOrderService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoWeiQuanOrderService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserMoneyService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TimeUtil;
import com.yeshi.fanli.util.factory.CommonOrderGoodsFactory;
import com.yeshi.fanli.util.factory.UserMoneyDetailFactory;
import com.yeshi.fanli.util.taobao.TaoBaoOrderUtil;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
 
import net.sf.json.JSONObject;
 
@Service
public class OrderRepairServiceImpl implements OrderRepairService {
 
    @Resource
    private OrderRepairHistoryMapper orderRepairHistoryMapper;
 
    @Resource
    private TaoBaoOrderService taoBaoOrderService;
 
    @Resource
    private CommonOrderService commonOrderService;
 
    @Resource
    private HongBaoOrderService hongBaoOrderService;
 
    @Resource
    private HongBaoV2Service hongBaoV2Service;
 
    @Resource
    private CommonOrderGoodsMapper commonOrderGoodsMapper;
 
    @Resource
    private CommonGoodsService commonGoodsService;
 
    @Resource
    private HongBaoManageService hongBaoManageService;
 
    @Resource
    private UserSystemCouponRecordService userSystemCouponRecordService;
 
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
 
    @Resource
    private UserSystemCouponService userSystemCouponService;
 
    @Resource
    private ShareGoodsActivityOrderService shareGoodsActivityOrderService;
 
    @Resource
    private CommonOrderMapper commonOrderMapper;
 
    @Resource
    private CommonOrderTradeIdMapMapper commonOrderTradeIdMapMapper;
 
    @Resource
    private UserInfoService userInfoService;
 
    @Resource
    private HongBaoOrderMapper hongBaoOrderMapper;
 
    @Resource
    private OrderRepairHistoryService orderRepairHistoryService;
 
    @Resource
    private DataSourceTransactionManager dataSourceTransactionManager;
 
    @Resource
    private TaoBaoWeiQuanOrderService taoBaoWeiQuanOrderService;
 
    @Resource
    private UserMoneyService userMoneyService;
 
    @Resource
    private PushInfoService pushInfoService;
 
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
 
    @Resource
    private ExtractCheckCompensateMapper extractCheckCompensateMapper;
 
    @Transactional
    @Override
    public void repairOrder(String orderId) throws Exception {
        // 比较CommonOrder与TaoBaoOrder的预估收益
        List<TaoBaoOrder> orderList = taoBaoOrderService.getTaoBaoOrderByOrderId(orderId);
        // 统计
        BigDecimal sumMoney = new BigDecimal("0");
        for (TaoBaoOrder order : orderList) {
            // if (order.getOrderState().equalsIgnoreCase("订单付款") ||
            // order.getOrderState().equalsIgnoreCase("订单成功"))
            // return;
            if (order.getSubsidy() == null)
                order.setSubsidy(new BigDecimal(0));
            if (order.geteIncome() == null)
                order.seteIncome(new BigDecimal(0));
 
            BigDecimal money = order.geteIncome().add(order.getSubsidy());
            sumMoney = sumMoney.add(money);
        }
 
        List<CommonOrder> commonOrderList = commonOrderService.listBySourceTypeAndOrderId(Constant.SOURCE_TYPE_TAOBAO,
                orderId);
        BigDecimal commonSumMoney = new BigDecimal("0");
        for (CommonOrder commonOrder : commonOrderList) {
            commonSumMoney = commonSumMoney.add(commonOrder.geteIncome());
        }
 
        // 不处理维权过的订单
        List<TaoBaoWeiQuanOrder> weiQuanOrderList = taoBaoWeiQuanOrderService.getWeiQuanSuccessOrders(orderId);
        if (weiQuanOrderList != null && weiQuanOrderList.size() > 0)
            return;
 
        processLessFanOrder(orderId);
 
        // if (sumMoney.compareTo(commonSumMoney) > 0) {
        // // 少返了
        //
        // } else {
        //
        // }
 
    }
 
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private void processLessFanOrder(String orderId) throws Exception {
 
        List<CommonOrder> commonOrderList = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                orderId);
        // 确定是自购还是分享赚
        if (commonOrderList.size() <= 0)
            return;
        HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrderList.get(0).getId());
        // 统计原来的上下级关系及返利的资金
        Map<Long, BigDecimal> oldMoney = new HashMap<>();
        Long firstUid = null;
        Long secondUid = null;
        Long mainUid = null;
        // 统计返利的资金
        for (CommonOrder co : commonOrderList) {
            HongBaoOrder tempHongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(co.getId());
            if (tempHongBaoOrder == null || tempHongBaoOrder.getHongBaoV2() == null)
                continue;
            hongBaoOrder = tempHongBaoOrder;
 
            mainUid = hongBaoOrder.getHongBaoV2().getUserInfo().getId();
            if (oldMoney.get(mainUid) == null)
                oldMoney.put(mainUid, new BigDecimal(0));
            if (hongBaoOrder.getHongBaoV2().getState() == HongBaoV2.STATE_YILINGQU)
                oldMoney.put(mainUid, oldMoney.get(mainUid).add(hongBaoOrder.getHongBaoV2().getMoney()));
            // 查询是否有下级
            List<HongBaoV2> childrenList = hongBaoV2Mapper.listChildrenById(hongBaoOrder.getHongBaoV2().getId());
            for (HongBaoV2 child : childrenList) {
                if (child.getType() == HongBaoV2.TYPE_YIJI || child.getType() == HongBaoV2.TYPE_SHARE_YIJI) {
                    firstUid = child.getUserInfo().getId();
                    if (oldMoney.get(firstUid) == null)
                        oldMoney.put(firstUid, new BigDecimal(0));
                    if (child.getState() == HongBaoV2.STATE_YILINGQU)
                        oldMoney.put(firstUid, oldMoney.get(firstUid).add(child.getMoney()));
 
                } else if (child.getType() == HongBaoV2.TYPE_ERJI || child.getType() == HongBaoV2.TYPE_SHARE_ERJI) {
                    secondUid = child.getUserInfo().getId();
                    if (oldMoney.get(secondUid) == null)
                        oldMoney.put(secondUid, new BigDecimal(0));
                    if (child.getState() == HongBaoV2.STATE_YILINGQU)
                        oldMoney.put(firstUid, oldMoney.get(secondUid).add(child.getMoney()));
                }
            }
        }
 
        // FileWriter fw = null;
        // try {
        // // 如果文件存在,则追加内容;如果文件不存在,则创建文件
        // File f = new File("D:\\three_sale.txt");
        // fw = new FileWriter(f, true);
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        // PrintWriter pw = new PrintWriter(fw);
        // pw.println(orderId+"#"+firstUid+"-"+oldMoney.get(firstUid)+"#"+secondUid+"-"+(secondUid!=null?
        // oldMoney.get(secondUid):""));
        // pw.flush();
        // try {
        // fw.flush();
        // pw.close();
        // fw.close();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        //
        // if (1 > 0)
        // return;
 
        List<TaoBaoOrder> taoBaoOrderList = taoBaoOrderService.getTaoBaoOrderByOrderId(orderId);
 
        // 根据交易ID查询
        // 先删除所有信息
        List<CommonOrder> commonOrderOldList = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                orderId);
        if (commonOrderOldList != null)
            for (CommonOrder co : commonOrderOldList) {
                deleteByCommonOrderId(co.getId());
            }
 
        // 然后再增加
 
        int invalidCount = 0;
        for (TaoBaoOrder tb : taoBaoOrderList) {
            if ("订单失效".equalsIgnoreCase(tb.getOrderState())) {
                invalidCount++;
            }
        }
 
        // 获取整体订单的状态
        int wholeOrderState = 0;
        if (taoBaoOrderList.size() == invalidCount)
            wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
        else if (invalidCount == 0)
            wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
        else
            wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
 
        for (TaoBaoOrder taoBaoOrder : taoBaoOrderList) {
            CommonOrder commonOrder = TaoBaoOrderUtil.convert(taoBaoOrder);
            commonOrder.setStateWholeOrder(wholeOrderState);
            commonOrder.setCommonOrderGoods(getCommonOrderGoods(taoBaoOrder.getAuctionId()));
            commonOrder.setUserInfo(new UserInfo(mainUid));
            addOrder(commonOrder, hongBaoOrder.getHongBaoV2().getType(), firstUid, secondUid);
            // } else {// 删除旧的,添加新的
            // Long commonOrderId = oldCommonOrder.getId();
            // List<CommonOrder> list =
            // commonOrderService.listBySourceTypeAndTradeId(Constant.SOURCE_TYPE_TAOBAO,
            // tradeId);
            // if (list.size() > 1)// 删除多余的tradeId
            // {
            // for (CommonOrder co : list) {
            // if (co.getId().longValue() != commonOrderId)
            // deleteByCommonOrderId(co.getId());
            // }
            // }
            // // 修改原来的信息
            // updateOrderInfo(taoBaoOrder, commonOrderId);
            // }
        }
 
        // 统计修改后的资金
        List<CommonOrder> newCommonOrderList = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                orderId);
        Map<Long, BigDecimal> newMap = new HashMap<>();
        if (newCommonOrderList != null)
            for (CommonOrder co : newCommonOrderList) {
                HongBaoOrder newHongBaoOrder = hongBaoOrderService.selectDetailByCommonOrderId(co.getId());
                if (newHongBaoOrder == null)
                    continue;
                HongBaoV2 hongBao = newHongBaoOrder.getHongBaoV2();
                if (hongBao.getState() == HongBaoV2.STATE_YILINGQU) {
                    Long uid = hongBao.getUserInfo().getId();
                    if (newMap.get(uid) == null)
                        newMap.put(uid, new BigDecimal(0));
                    newMap.put(uid, newMap.get(uid).add(hongBao.getMoney()));
                } else {
                    Long uid = hongBao.getUserInfo().getId();
                    if (newMap.get(uid) == null)
                        newMap.put(uid, new BigDecimal(0));
                }
                List<HongBaoV2> children = hongBaoV2Service.listChildrenById(hongBao.getId());
                if (children != null)
                    for (HongBaoV2 child : children) {
                        if (newMap.get(child.getUserInfo().getId()) == null)
                            newMap.put(child.getUserInfo().getId(), new BigDecimal(0));
                        if (child.getState() == HongBaoV2.STATE_YILINGQU)
                            newMap.put(child.getUserInfo().getId(),
                                    newMap.get(child.getUserInfo().getId()).add(child.getMoney()));
                    }
            }
 
        for (Iterator<Long> its = newMap.keySet().iterator(); its.hasNext();) {
            Long uid = its.next();
            BigDecimal beforeGetMoney = oldMoney.get(uid);
            BigDecimal afterGetMoney = newMap.get(uid);
            OrderRepairHistory history = new OrderRepairHistory();
            history.setAfterGetMoney(afterGetMoney);
            history.setBeforeGetMoney(beforeGetMoney);
            history.setOrderId(orderId);
            history.setUid(uid);
            orderRepairHistoryService.addOrderRepairHistory(history);
        }
 
    }
 
    private CommonOrderGoods getCommonOrderGoods(Long auctionId) {
        List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(auctionId + "",
                Constant.SOURCE_TYPE_TAOBAO);
        CommonOrderGoods cog = null;
        if (commonGoodsList.size() <= 0)// 不存在就插入商品
        {
            TaoBaoGoodsBrief taoBaoGoods = null;
            try {
                taoBaoGoods = TaoKeApiUtil.getSimpleGoodsInfo(auctionId);
            } catch (TaobaoGoodsDownException e) {
                e.printStackTrace();
                LogHelper.errorDetailInfo(e, "AUCTIONID:" + auctionId, "");
                try {
                    taoBaoGoods = TaoBaoUtil.getSimpleGoodsBrief(auctionId);
                } catch (Exception e1) {
                    CommonGoods commonGoods = commonGoodsService.getCommonGoodsByGoodsIdAndGoodsType(auctionId,
                            Constant.SOURCE_TYPE_TAOBAO);
                    if (commonGoods != null)
                        taoBaoGoods = TaoBaoUtil.convert(commonGoods);
                }
            }
            if (taoBaoGoods != null) {
                cog = CommonOrderGoodsFactory.create(taoBaoGoods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
 
            return cog;
        } else
            return commonGoodsList.get(0);
 
    }
 
    // 修改订单信息
    @Transactional
    private void updateOrderInfo(TaoBaoOrder taoBaoOrder, Long commonOrderId) throws Exception {
        HongBaoOrder hongBaoOrder = hongBaoOrderService.selectDetailByCommonOrderId(commonOrderId);
        CommonOrder newCommonOrder = TaoBaoOrderUtil.convert(taoBaoOrder);
        List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper
                .listByGoodsIdAndGoodsType(taoBaoOrder.getAuctionId() + "", newCommonOrder.getSourceType());
        CommonOrderGoods cog = null;
        if (commonGoodsList.size() <= 0)// 不存在就插入商品
        {
            TaoBaoGoodsBrief taoBaoGoods = null;
            try {
                taoBaoGoods = TaoKeApiUtil.getSimpleGoodsInfo(taoBaoOrder.getAuctionId());
            } catch (TaobaoGoodsDownException e) {
                e.printStackTrace();
                LogHelper.errorDetailInfo(e, "AUCTIONID:" + taoBaoOrder.getAuctionId(), "");
                try {
                    taoBaoGoods = TaoBaoUtil.getSimpleGoodsBrief(taoBaoOrder.getAuctionId());
                } catch (Exception e1) {
                    CommonGoods commonGoods = commonGoodsService.getCommonGoodsByGoodsIdAndGoodsType(
                            taoBaoOrder.getAuctionId(), Constant.SOURCE_TYPE_TAOBAO);
                    if (commonGoods != null)
                        taoBaoGoods = TaoBaoUtil.convert(commonGoods);
                }
            }
            if (taoBaoGoods != null) {
                cog = CommonOrderGoodsFactory.create(taoBaoGoods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
        }
 
        newCommonOrder.setCommonOrderGoods(cog);
        newCommonOrder.setId(commonOrderId);
        newCommonOrder.setCreateTime(null);
        newCommonOrder.setUpdateTime(new Date());
        commonOrderService.updateByPrimaryKeySelective(newCommonOrder);
        // 更新主红包信息
        CommonOrder commonOrder = commonOrderService.selectByPrimaryKey(newCommonOrder.getId());
 
        if (hongBaoOrder.getHongBaoV2().getType() == HongBaoV2.TYPE_ZIGOU) {
            BigDecimal fanliRate = hongBaoManageService.getFanLiRate(commonOrder.getCreateTime().getTime());
            // 免单处理
            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.getOrderNo());
                }
            }
 
            HongBaoV2 hongBao = new HongBaoV2(hongBaoOrder.getHongBaoV2().getId());
            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) {
                if (hongBaoOrder.getHongBaoV2().getPreGetTime().getTime() < System.currentTimeMillis())
                    hongBao.setState(HongBaoV2.STATE_YILINGQU);
                hongBao.setMoney(
                        MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), fanliRate.divide(new BigDecimal(100))));
                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));
                if (mianDan) {
                    try {
                        userSystemCouponService.updateStateByDrawback(commonOrder.getOrderNo());
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new HongBaoException(12, "免单券退款出错");
                    }
                }
            }
            hongBaoV2Mapper.updateByPrimaryKeySelective(hongBao);
 
            // 更新子红包信息
            // 获取子红包
            List<HongBaoV2> children = hongBaoV2Mapper.listChildrenById(hongBao.getId());
            if (children != null && children.size() > 0)
                for (HongBaoV2 child : children) {
                    HongBaoV2 childUpdate = new HongBaoV2(child.getId());
                    childUpdate.setState(hongBao.getState());
                    childUpdate.setUpdateTime(new Date());
                    BigDecimal rate = null;
                    if (child.getType() == HongBaoV2.TYPE_YIJI) {// 一级分享赚
                        rate = hongBaoManageService.getFirstInviteRate(child.getUrank(),
                                commonOrder.getCreateTime().getTime());
                    } else if (child.getType() == HongBaoV2.TYPE_ERJI) {// 二级分享赚
                        rate = hongBaoManageService.getSecondInviteRate(child.getUrank(),
                                commonOrder.getCreateTime().getTime());
                    }
 
                    // 以实际收入为准计算预估收益
                    if (hongBao.getState() == HongBaoV2.STATE_YILINGQU) {
                        childUpdate.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), rate.divide(new BigDecimal(100))));
                        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")));
 
                        if (child.getPreGetTime().getTime() < System.currentTimeMillis()) {
                            childUpdate.setState(HongBaoV2.STATE_YILINGQU);
                            childUpdate.setGetTime(child.getGetTime());
                        }
 
                    } else if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU) {
                        childUpdate.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), rate.divide(new BigDecimal(100))));
                    }
                    hongBaoV2Mapper.updateByPrimaryKeySelective(childUpdate);
                }
        } else if (hongBaoOrder.getHongBaoV2().getType() == HongBaoV2.TYPE_SHARE_GOODS) {
 
            BigDecimal fanliRate = hongBaoManageService.getShareRate(commonOrder.getCreateTime().getTime());
            List<ShareGoodsActivityOrder> list = shareGoodsActivityOrderService
                    .listByOrderIdAndUid(commonOrder.getUserInfo().getId(), commonOrder.getOrderNo());
            if (list != null && list.size() > 0) {
                fanliRate = list.get(0).getShareRate();
            }
 
            HongBaoV2 hongBao = new HongBaoV2(hongBaoOrder.getHongBaoV2().getId());
            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) {
                hongBao.setState(HongBaoV2.STATE_YILINGQU);
                hongBao.setMoney(
                        MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), fanliRate.divide(new BigDecimal(100))));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(commonOrder.getSettleTime());
                calendar.add(Calendar.MONTH, 1);
                if (hongBaoOrder.getHongBaoV2().getGetTime() == null) {
                    hongBao.setGetTime(hongBaoOrder.getHongBaoV2().getPreGetTime());
                }
 
            } else if (commonOrder.getState() == CommonOrder.STATE_SX) {
                hongBao.setState(HongBaoV2.STATE_SHIXIAO);
                hongBao.setMoney(new BigDecimal(0));
            }
            hongBaoV2Mapper.updateByPrimaryKeySelective(hongBao);
 
            // 获取子红包
            List<HongBaoV2> children = hongBaoV2Mapper.listChildrenById(hongBao.getId());
            if (children != null)
                for (HongBaoV2 child : children) {
                    HongBaoV2 childUpdate = new HongBaoV2(child.getId());
                    // 统一设置状态
                    childUpdate.setState(hongBao.getState());
                    childUpdate.setUpdateTime(new Date());
                    BigDecimal rate = null;
                    if (child.getType() == HongBaoV2.TYPE_SHARE_YIJI) {// 一级分享赚
                        rate = hongBaoManageService.getFirstShareRate(1, commonOrder.getCreateTime().getTime());
                    } else if (child.getType() == HongBaoV2.TYPE_SHARE_ERJI) {// 二级分享赚
                        rate = hongBaoManageService.getSecondShareRate(1, commonOrder.getCreateTime().getTime());
                    }
 
                    // 以实际收入为准计算预估收益
                    if (CommonOrder.STATE_JS == commonOrder.getState()) {
                        childUpdate.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), rate.divide(new BigDecimal(100))));
                        if (commonOrder.getThirdCreateTime().getTime() > TimeUtil.convertToTimeTemp("2019-04-16",
                                "yyyy-MM-dd"))
                            childUpdate.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(),
                                    rate.divide(new BigDecimal(100))));
 
                        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")));
                        if (child.getGetTime() == null) {
                            childUpdate.setGetTime(child.getPreGetTime());
                        }
 
                    } else if (CommonOrder.STATE_FK == commonOrder.getState()) {
                        if (commonOrder.getThirdCreateTime().getTime() > TimeUtil.convertToTimeTemp("2019-04-16",
                                "yyyy-MM-dd"))
                            childUpdate.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(),
                                    rate.divide(new BigDecimal(100))));
                        else
                            childUpdate.setMoney(
                                    MoneyBigDecimalUtil.mul(hongBao.getMoney(), rate.divide(new BigDecimal(100))));
                    }
                    hongBaoV2Mapper.updateByPrimaryKeySelective(childUpdate);
                }
        }
    }
 
    @Transactional
    public void addOrder(CommonOrder commonOrder, int type, Long firstUid, Long secondUid) throws Exception {
        // 增加commonOrder
        commonOrder.setCreateTime(commonOrder.getThirdCreateTime());
        // 不存在就插入,存在就不管
        CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
 
        // 之前不存在于数据库
        if (commonOrder.getCommonOrderGoods().getId() == null) {
            List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper
                    .listByGoodsIdAndGoodsType(goods.getGoodsId(), goods.getGoodsType());
 
            if (commonGoodsList == null || commonGoodsList.size() < 1) {// 不存在
                commonOrderGoodsMapper.insertSelective(goods);
            } else {// 存在
                goods = commonGoodsList.get(0);
            }
            if (goods.getId() == null)
                return;
            commonOrder.setCommonOrderGoods(goods);
        }
 
        CommonOrder oldCommonOrder = commonOrderMapper.selectBySourceTypeAndTradeId(commonOrder.getSourceType(),
                commonOrder.getTradeId());
        if (oldCommonOrder == null)// 新增
        {
            commonOrder.setUpdateTime(new Date());
            commonOrderMapper.insertSelective(commonOrder);
            try {
                // 插入映射,保证交易ID的完整性
                commonOrderTradeIdMapMapper.insertSelective(new CommonOrderTradeIdMap(commonOrder.getId(),
                        commonOrder.getTradeId(), new Date(), commonOrder.getSourceType()));
            } catch (Exception e) {
 
            }
        }
 
        // 添加红包
        if (type == HongBaoV2.TYPE_ZIGOU) {// 获取自购的返利比例
            BigDecimal fanliRate = hongBaoManageService.getFanLiRate(commonOrder.getCreateTime().getTime());
            // 查询是否有免单计划
            BigDecimal mianDanMoney = null;
            if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_FK) {
                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();
 
                    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) {// 设置免单券失效
                try {
                    userSystemCouponService.updateStateByDrawback(commonOrder.getOrderNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
 
            HongBaoV2 hongBao = new HongBaoV2();
            hongBao.setBeizhu("2019年7月批量修改");
            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) {
                hongBao.setState(HongBaoV2.STATE_KELINGQU);
                hongBao.setMoney(
                        MoneyBigDecimalUtil.mul(commonOrder.geteIncome(), fanliRate.divide(new BigDecimal(100))));
                hongBao.setPreGetTime(new Date(commonOrder.getSettleTime().getTime() + 1000 * 60 * 60 * 24 * 15L));
 
                if (hongBao.getPreGetTime().getTime() < System.currentTimeMillis()) {
                    hongBao.setState(HongBaoV2.STATE_YILINGQU);
                    hongBao.setGetTime(hongBao.getPreGetTime());
                }
            } 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.getUserByIdWithMybatis(commonOrder.getUserInfo().getId());
            hongBao.setUrank(user.getRank());
            hongBaoV2Mapper.insertSelective(hongBao);
            // 添加红包与订单的映射
            HongBaoOrder hongBaoOrder = new HongBaoOrder();
            hongBaoOrder.setCommonOrder(commonOrder);
            hongBaoOrder.setCreateTime(new Date());
            hongBaoOrder.setHongBaoV2(hongBao);
            hongBaoOrderMapper.insertSelective(hongBaoOrder);
 
            UserInfo boss = null;
            if (firstUid != null)
                boss = userInfoService.selectByPKey(firstUid);
 
            if (boss != null && hongBao.getState() != HongBaoV2.STATE_SHIXIAO && mianDanMoney == null) {// 1级BOSS存在且红包未失效,免单不支持多级分销
 
                // 插入一级子红包
                BigDecimal firstRate = hongBaoManageService
                        .getFirstInviteRate(boss.getRank() == null ? 0 : boss.getRank());
                if (firstRate.compareTo(new BigDecimal(0)) <= 0)
                    return;
                HongBaoV2 firstHongbao = new HongBaoV2();
                firstHongbao.setBeizhu("2019年7月批量修改");
                firstHongbao.setUserInfo(boss);
                firstHongbao.setUrank(boss.getRank());
                firstHongbao.setParent(hongBao);
                firstHongbao.setCreateTime(new Date());
                firstHongbao.setType(HongBaoV2.TYPE_YIJI);
                firstHongbao.setVersion(2);
                firstHongbao.setState(hongBao.getState());
 
                if (hongBao.getState() == HongBaoV2.STATE_KELINGQU) {// ||
                                                                        // hongBao.getState()
                                                                        // ==
                                                                        // HongBaoV2.STATE_YILINGQU
                    firstHongbao.setMoney(
                            MoneyBigDecimalUtil.mul(hongBao.getMoney(), firstRate.divide(new BigDecimal(100))));
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(commonOrder.getSettleTime());
                    calendar.add(Calendar.MONTH, 1);
                    firstHongbao.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                            calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25",
                            "yyyy-M-dd")));
                    if (firstHongbao.getPreGetTime().getTime() < System.currentTimeMillis()) {
                        firstHongbao.setGetTime(firstHongbao.getPreGetTime());
                        firstHongbao.setState(HongBaoV2.STATE_YILINGQU);
                    }
                } else if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU) {
                    firstHongbao.setMoney(
                            MoneyBigDecimalUtil.mul(hongBao.getMoney(), firstRate.divide(new BigDecimal(100))));
                }
                // 返利为0的不通知
                if (firstHongbao.getMoney() == null || firstHongbao.getMoney().compareTo(new BigDecimal(0)) <= 0)
                    return;
 
                hongBaoV2Mapper.insertSelective(firstHongbao);
 
                // 插入二级子红包
                if (secondUid == null)
                    boss = null;
                else
                    boss = userInfoService.selectByPKey(secondUid);
 
                if (boss != null) {// 二级BOSS存在
                    BigDecimal secondRate = hongBaoManageService
                            .getSecondInviteRate(boss.getRank() == null ? 0 : boss.getRank());
                    if (secondRate.compareTo(new BigDecimal(0)) <= 0)
                        return;
                    HongBaoV2 secondHongbao = new HongBaoV2();
                    secondHongbao.setBeizhu("2019年7月批量修改");
                    secondHongbao.setUserInfo(boss);
                    secondHongbao.setUrank(boss.getRank());
                    secondHongbao.setParent(hongBao);
                    secondHongbao.setCreateTime(new Date());
                    secondHongbao.setType(HongBaoV2.TYPE_ERJI);
                    secondHongbao.setVersion(2);
                    secondHongbao.setState(hongBao.getState());
                    if (hongBao.getState() == HongBaoV2.STATE_KELINGQU) {// ||
                                                                            // hongBao.getState()
                                                                            // ==
                                                                            // HongBaoV2.STATE_YILINGQU
                        secondHongbao.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), secondRate.divide(new BigDecimal(100))));
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(commonOrder.getSettleTime());
                        calendar.add(Calendar.MONTH, 1);
                        secondHongbao.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                                calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25",
                                "yyyy-M-dd")));
                        if (secondHongbao.getPreGetTime().getTime() < System.currentTimeMillis()) {
                            secondHongbao.setGetTime(secondHongbao.getPreGetTime());
                            secondHongbao.setState(HongBaoV2.STATE_YILINGQU);
                        }
 
                    } else if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU) {
                        secondHongbao.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), secondRate.divide(new BigDecimal(100))));
                    }
 
                    // 返利为0的不统计
                    if (secondHongbao.getMoney() == null || secondHongbao.getMoney().compareTo(new BigDecimal(0)) <= 0)
                        return;
                    hongBaoV2Mapper.insertSelective(secondHongbao);
                }
 
            }
 
        } else if (type == HongBaoV2.TYPE_SHARE_GOODS) {
            // 分享赚不加入失效的订单
            if (commonOrder.getState() == CommonOrder.STATE_SX || commonOrder.getState() == CommonOrder.STATE_WQ)
                return;
            // 分享赚
            BigDecimal shareRate = hongBaoManageService.getShareRate(commonOrder.getCreateTime().getTime());
 
            HongBaoV2 hongBao = new HongBaoV2();
            hongBao.setBeizhu("2019年7月批量修改");
            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) {
                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")));
                if (hongBao.getPreGetTime().getTime() < System.currentTimeMillis()) {
                    hongBao.setGetTime(hongBao.getPreGetTime());
                    hongBao.setState(HongBaoV2.STATE_YILINGQU);
                }
            }
            UserInfo user = userInfoService.getUserByIdWithMybatis(commonOrder.getUserInfo().getId());
            hongBao.setUrank(user.getRank());
            hongBao.setUserInfo(user);
            hongBaoV2Mapper.insertSelective(hongBao);
            // 插入红包与订单映射
            HongBaoOrder hongBaoOrder = new HongBaoOrder();
            hongBaoOrder.setCommonOrder(commonOrder);
            hongBaoOrder.setCreateTime(new Date());
            hongBaoOrder.setHongBaoV2(hongBao);
            hongBaoOrderMapper.insertSelective(hongBaoOrder);
 
            // 4月17日后才有一级分享赚
            if (commonOrder.getThirdCreateTime().getTime() > TimeUtil.convertToTimeTemp("2019-04-17", "yyyy-MM-dd")) {
                UserInfo boss = null;
                if (firstUid != null)
                    boss = userInfoService.selectByPKey(firstUid);
                if (boss != null) {
                    BigDecimal firstLevelRate = hongBaoManageService.getFirstShareRate(1,
                            commonOrder.getThirdCreateTime().getTime());
                    HongBaoV2 child = new HongBaoV2();
                    child.setBeizhu("2019年7月批量修改");
                    child.setParent(hongBao);
                    child.setType(HongBaoV2.TYPE_SHARE_YIJI);
                    if (commonOrder.getState() == CommonOrder.STATE_FK) {
                        child.setState(HongBaoV2.STATE_BUKELINGQU);
                        child.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(),
                                firstLevelRate.divide(new BigDecimal(100))));
                    } else if (commonOrder.getState() == CommonOrder.STATE_JS) {
                        child.setState(HongBaoV2.STATE_KELINGQU);
                        child.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(),
                                firstLevelRate.divide(new BigDecimal(100))));
                        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")));
 
                        if (child.getPreGetTime().getTime() < System.currentTimeMillis()) {
                            child.setGetTime(child.getPreGetTime());
                            child.setState(HongBaoV2.STATE_YILINGQU);
                        }
 
                    }
                    child.setUserInfo(boss);
                    child.setUrank(boss.getRank());
                    child.setVersion(2);
                    child.setCreateTime(new Date());
                    hongBaoV2Mapper.insertSelective(child);
                }
            }
 
        } else
            throw new HongBaoException(2, "type错误");
 
        // 添加
 
    }
 
    @Transactional(propagation = Propagation.REQUIRED)
    private void deleteByCommonOrderId(Long commonOrderId) {
        commonOrderMapper.deleteByPrimaryKey(commonOrderId);
        HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrderId);
        if (hongBaoOrder == null || hongBaoOrder.getHongBaoV2() == null)
            return;
        List<HongBaoV2> children = hongBaoV2Mapper.listChildrenById(hongBaoOrder.getHongBaoV2().getId());
        if (children != null)
            for (HongBaoV2 hongBao : children) {
                hongBaoV2Mapper.deleteByPrimaryKey(hongBao.getId());
            }
        hongBaoV2Mapper.deleteByPrimaryKey(hongBaoOrder.getHongBaoV2().getId());
        hongBaoOrderMapper.deleteByPrimaryKey(hongBaoOrder.getId());
 
    }
 
    @Transactional
    @Override
    public void testTransaction() {
        hongBaoV2Mapper.selectByPrimaryKey(1L);
    }
 
    private static Map<String, OrderInfo> orderInfoMap;
 
    private OrderInfo getOrderInfo(String orderId) {
        if (orderInfoMap == null) {
            orderInfoMap = new HashMap<>();
            Scanner scanner = null;
            try {
                scanner = new Scanner(new File("C:\\Users\\Administrator\\Desktop\\订单集中排查\\three_sale.txt"));
                while (scanner.hasNext()) {
                    OrderInfo orderInfo = new OrderInfo();
                    String info = scanner.next();
                    if (StringUtil.isNullOrEmpty(info))
                        continue;
 
                    String[] sts = info.split("#");
                    String orderid = sts[0];
                    orderInfo.setOrderId(orderid);
                    String firstUid = sts[1].split("-")[0];
                    String firstUidMoney = sts[1].split("-")[1];
                    orderInfo.setFirstUid(Long.parseLong(firstUid));
                    orderInfo.setFirstUidMoney(new BigDecimal(firstUidMoney));
 
                    String secondUid = sts[2].split("-")[0];
                    String secondUidMoney = null;
                    if (sts[2].split("-").length > 1)
                        secondUidMoney = sts[2].split("-")[1];
                    if (!StringUtil.isNullOrEmpty(secondUid))
                        orderInfo.setSecondUid(Long.parseLong(secondUid));
                    if (!StringUtil.isNullOrEmpty(secondUidMoney))
                        orderInfo.setSecondUidMoney(new BigDecimal(secondUidMoney));
                    orderInfoMap.put(orderInfo.getOrderId(), orderInfo);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            scanner.close();
        }
 
        return orderInfoMap.get(orderId);
    }
 
    @Transactional
    @Override
    public void repireFirstAndSecondLevel(String orderId) throws Exception {
        repireFirstShare(orderId);
        if (1 > 0)
            return;
        OrderInfo info = getOrderInfo(orderId);
        Map<Long, BigDecimal> oldMoneyMap = new HashMap<>();
        if (info.getFirstUid() != null)
            oldMoneyMap.put(info.getFirstUid(), info.getFirstUidMoney());
        if (info.getSecondUid() != null)
            oldMoneyMap.put(info.getSecondUid(), info.getSecondUidMoney());
 
        if (info != null) {
            List<CommonOrder> list = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                    info.getOrderId());
            // 查询是否有子红包
            for (CommonOrder commonOrder : list) {
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
                if (hongBaoOrder == null)
                    continue;
                List<HongBaoV2> hongBaoList = hongBaoV2Mapper.listChildrenById(hongBaoOrder.getHongBaoV2().getId());
                if (hongBaoList != null && hongBaoList.size() > 0)// 有子红包就不处理了
                    return;
            }
 
            for (CommonOrder commonOrder : list) {
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
                if (hongBaoOrder == null)
                    continue;
                HongBaoV2 hongBao = hongBaoOrder.getHongBaoV2();
                Long firstUid = info.getFirstUid();
                Long secondUid = info.getSecondUid();
                // 加入子红包
                UserInfo boss = null;
                if (firstUid != null)
                    boss = userInfoService.selectByPKey(firstUid);
 
                if (boss != null && hongBao.getState() != HongBaoV2.STATE_SHIXIAO) {// 1级BOSS存在且红包未失效,免单不支持多级分销
                    // 插入一级子红包
                    BigDecimal firstRate = hongBaoManageService
                            .getFirstInviteRate(boss.getRank() == null ? 0 : boss.getRank());
                    if (firstRate.compareTo(new BigDecimal(0)) <= 0)
                        return;
                    HongBaoV2 firstHongbao = new HongBaoV2();
                    firstHongbao.setBeizhu("2019年7月批量修改");
                    firstHongbao.setUserInfo(boss);
                    firstHongbao.setUrank(boss.getRank());
                    firstHongbao.setParent(hongBao);
                    firstHongbao.setCreateTime(new Date());
                    firstHongbao.setType(HongBaoV2.TYPE_YIJI);
                    firstHongbao.setVersion(2);
                    firstHongbao.setState(hongBao.getState());
 
                    if (hongBao.getState() == HongBaoV2.STATE_KELINGQU
                            || hongBao.getState() == HongBaoV2.STATE_YILINGQU) {
                        firstHongbao.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), firstRate.divide(new BigDecimal(100))));
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(commonOrder.getSettleTime());
                        calendar.add(Calendar.MONTH, 1);
                        firstHongbao.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                                calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25",
                                "yyyy-M-dd")));
                        if (firstHongbao.getPreGetTime().getTime() < System.currentTimeMillis()) {
                            firstHongbao.setGetTime(firstHongbao.getPreGetTime());
                            firstHongbao.setState(HongBaoV2.STATE_YILINGQU);
                        }
                    } else if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU) {
                        firstHongbao.setMoney(
                                MoneyBigDecimalUtil.mul(hongBao.getMoney(), firstRate.divide(new BigDecimal(100))));
                    }
                    // 返利为0的不通知
                    if (firstHongbao.getMoney() == null || firstHongbao.getMoney().compareTo(new BigDecimal(0)) <= 0)
                        continue;
 
                    hongBaoV2Mapper.insertSelective(firstHongbao);
 
                    // 插入二级子红包
                    if (secondUid == null)
                        boss = null;
                    else
                        boss = userInfoService.selectByPKey(secondUid);
 
                    if (boss != null) {// 二级BOSS存在
                        BigDecimal secondRate = hongBaoManageService
                                .getSecondInviteRate(boss.getRank() == null ? 0 : boss.getRank());
                        if (secondRate.compareTo(new BigDecimal(0)) <= 0)
                            return;
                        HongBaoV2 secondHongbao = new HongBaoV2();
                        secondHongbao.setBeizhu("2019年7月批量修改");
                        secondHongbao.setUserInfo(boss);
                        secondHongbao.setUrank(boss.getRank());
                        secondHongbao.setParent(hongBao);
                        secondHongbao.setCreateTime(new Date());
                        secondHongbao.setType(HongBaoV2.TYPE_ERJI);
                        secondHongbao.setVersion(2);
                        secondHongbao.setState(hongBao.getState());
                        if (hongBao.getState() == HongBaoV2.STATE_KELINGQU
                                || hongBao.getState() == HongBaoV2.STATE_YILINGQU) {
                            secondHongbao.setMoney(MoneyBigDecimalUtil.mul(hongBao.getMoney(),
                                    secondRate.divide(new BigDecimal(100))));
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(commonOrder.getSettleTime());
                            calendar.add(Calendar.MONTH, 1);
                            secondHongbao.setPreGetTime(new Date(TimeUtil.convertToTimeTemp(
                                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-25",
                                    "yyyy-M-dd")));
                            if (secondHongbao.getPreGetTime().getTime() < System.currentTimeMillis()) {
                                secondHongbao.setGetTime(secondHongbao.getPreGetTime());
                                secondHongbao.setState(HongBaoV2.STATE_YILINGQU);
                            }
 
                        } else if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU) {
                            secondHongbao.setMoney(MoneyBigDecimalUtil.mul(hongBao.getMoney(),
                                    secondRate.divide(new BigDecimal(100))));
                        }
 
                        // 返利为0的不统计
                        if (secondHongbao.getMoney() == null
                                || secondHongbao.getMoney().compareTo(new BigDecimal(0)) <= 0)
                            continue;
                        hongBaoV2Mapper.insertSelective(secondHongbao);
                    }
 
                }
            }
        }
 
        // 统计修改后的资金
        List<CommonOrder> newCommonOrderList = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                orderId);
        Map<Long, BigDecimal> newMap = new HashMap<>();
        if (newCommonOrderList != null)
            for (CommonOrder co : newCommonOrderList) {
                HongBaoOrder newHongBaoOrder = hongBaoOrderService.selectDetailByCommonOrderId(co.getId());
                if (newHongBaoOrder == null)
                    continue;
                HongBaoV2 hongBao = newHongBaoOrder.getHongBaoV2();
                List<HongBaoV2> children = hongBaoV2Service.listChildrenById(hongBao.getId());
                if (children != null)
                    for (HongBaoV2 child : children) {
                        if (newMap.get(child.getUserInfo().getId()) == null)
                            newMap.put(child.getUserInfo().getId(), new BigDecimal(0));
                        if (child.getState() == HongBaoV2.STATE_YILINGQU)
                            newMap.put(child.getUserInfo().getId(),
                                    newMap.get(child.getUserInfo().getId()).add(child.getMoney()));
                    }
            }
 
        for (Iterator<Long> its = newMap.keySet().iterator(); its.hasNext();) {
            Long uid = its.next();
            BigDecimal beforeGetMoney = oldMoneyMap.get(uid);
            BigDecimal afterGetMoney = newMap.get(uid);
            OrderRepairHistory history = new OrderRepairHistory();
            history.setAfterGetMoney(afterGetMoney);
            history.setBeforeGetMoney(beforeGetMoney);
            history.setOrderId(orderId);
            history.setUid(uid);
            orderRepairHistoryService.addOrderRepairHistory(history);
        }
 
    }
 
    private void repireFirstShare(String orderId) throws Exception {
        OrderInfo info = getOrderInfo(orderId);
        Long firstUid = info.getFirstUid();
        Map<Long, BigDecimal> oldMoneyMap = new HashMap<>();
        if (info.getFirstUid() != null)
            oldMoneyMap.put(info.getFirstUid(), info.getFirstUidMoney());
        if (info.getSecondUid() != null)
            oldMoneyMap.put(info.getSecondUid(), info.getSecondUidMoney());
 
        if (info != null) {
            List<CommonOrder> list = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                    info.getOrderId());
            // 查询是否有子红包
            for (CommonOrder commonOrder : list) {
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
                if (hongBaoOrder == null)
                    continue;
                List<HongBaoV2> hongBaoList = hongBaoV2Mapper.listChildrenById(hongBaoOrder.getHongBaoV2().getId());
                if (hongBaoList != null && hongBaoList.size() > 0)// 有子红包就不处理了
                    return;
            }
 
            for (CommonOrder commonOrder : list) {
                if (commonOrder.getState() == CommonOrder.STATE_SX || commonOrder.getState() == CommonOrder.STATE_WQ)
                    continue;
                // 分享赚
 
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
                if (hongBaoOrder == null)
                    continue;
 
                HongBaoV2 hongBao = hongBaoOrder.getHongBaoV2();
                // 4月17日后才有一级分享赚
                if (commonOrder.getThirdCreateTime().getTime() > TimeUtil.convertToTimeTemp("2019-04-17",
                        "yyyy-MM-dd")) {
                    UserInfo boss = null;
                    if (firstUid != null)
                        boss = userInfoService.selectByPKey(firstUid);
                    if (boss != null) {
                        BigDecimal firstLevelRate = hongBaoManageService.getFirstShareRate(1,
                                commonOrder.getThirdCreateTime().getTime());
                        HongBaoV2 child = new HongBaoV2();
                        child.setBeizhu("2019年7月批量修改");
                        child.setParent(hongBao);
                        child.setType(HongBaoV2.TYPE_SHARE_YIJI);
                        if (commonOrder.getState() == CommonOrder.STATE_FK) {
                            child.setState(HongBaoV2.STATE_BUKELINGQU);
                            child.setMoney(MoneyBigDecimalUtil.mul(commonOrder.getEstimate(),
                                    firstLevelRate.divide(new BigDecimal(100))));
                        } else if (commonOrder.getState() == CommonOrder.STATE_JS) {
                            child.setState(HongBaoV2.STATE_KELINGQU);
                            child.setMoney(MoneyBigDecimalUtil.mul(commonOrder.geteIncome(),
                                    firstLevelRate.divide(new BigDecimal(100))));
                            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")));
 
                            if (child.getPreGetTime().getTime() < System.currentTimeMillis()) {
                                child.setGetTime(child.getPreGetTime());
                                child.setState(HongBaoV2.STATE_YILINGQU);
                            }
 
                        }
                        child.setUserInfo(boss);
                        child.setUrank(boss.getRank());
                        child.setVersion(2);
                        child.setCreateTime(new Date());
                        hongBaoV2Mapper.insertSelective(child);
                    }
                }
            }
 
        }
 
        // 统计修改后的资金
        List<CommonOrder> newCommonOrderList = commonOrderMapper.listBySourceTypeAndOrderNo(Constant.SOURCE_TYPE_TAOBAO,
                orderId);
        Map<Long, BigDecimal> newMap = new HashMap<>();
        if (newCommonOrderList != null)
            for (CommonOrder co : newCommonOrderList) {
                HongBaoOrder newHongBaoOrder = hongBaoOrderService.selectDetailByCommonOrderId(co.getId());
                if (newHongBaoOrder == null)
                    continue;
                HongBaoV2 hongBao = newHongBaoOrder.getHongBaoV2();
                List<HongBaoV2> children = hongBaoV2Service.listChildrenById(hongBao.getId());
                if (children != null)
                    for (HongBaoV2 child : children) {
                        if (newMap.get(child.getUserInfo().getId()) == null)
                            newMap.put(child.getUserInfo().getId(), new BigDecimal(0));
                        if (child.getState() == HongBaoV2.STATE_YILINGQU)
                            newMap.put(child.getUserInfo().getId(),
                                    newMap.get(child.getUserInfo().getId()).add(child.getMoney()));
                    }
            }
 
        for (Iterator<Long> its = newMap.keySet().iterator(); its.hasNext();) {
            Long uid = its.next();
            BigDecimal beforeGetMoney = oldMoneyMap.get(uid);
            BigDecimal afterGetMoney = newMap.get(uid);
            OrderRepairHistory history = new OrderRepairHistory();
            history.setAfterGetMoney(afterGetMoney);
            history.setBeforeGetMoney(beforeGetMoney);
            history.setOrderId(orderId);
            history.setUid(uid);
            orderRepairHistoryService.addOrderRepairHistory(history);
        }
 
    }
 
    class OrderInfo {
        private String orderId;
        private Long firstUid;
        private BigDecimal firstUidMoney;
        private Long secondUid;
        private BigDecimal secondUidMoney;
 
        public String getOrderId() {
            return orderId;
        }
 
        public void setOrderId(String orderId) {
            this.orderId = orderId;
        }
 
        public Long getFirstUid() {
            return firstUid;
        }
 
        public void setFirstUid(Long firstUid) {
            this.firstUid = firstUid;
        }
 
        public BigDecimal getFirstUidMoney() {
            return firstUidMoney;
        }
 
        public void setFirstUidMoney(BigDecimal firstUidMoney) {
            this.firstUidMoney = firstUidMoney;
        }
 
        public Long getSecondUid() {
            return secondUid;
        }
 
        public void setSecondUid(Long secondUid) {
            this.secondUid = secondUid;
        }
 
        public BigDecimal getSecondUidMoney() {
            return secondUidMoney;
        }
 
        public void setSecondUidMoney(BigDecimal secondUidMoney) {
            this.secondUidMoney = secondUidMoney;
        }
    }
 
    @Override
    public List<OrderRepairHistory> listByUid(Long uid) {
 
        return orderRepairHistoryMapper.listByUid(uid);
    }
 
    @Transactional
    @Override
    public void doMoney(Long uid) {
        List<OrderRepairHistory> historyList = listByUid(uid);
        for (int i = 0; i < historyList.size(); i++) {
            if (historyList.get(i).getCreateTime().getTime() < TimeUtil.convertToTimeTemp("2019-07-15 17:00:38",
                    "yyyy-MM-dd HH:mm:ss")) {
                historyList.remove(i);
                i--;
            }
 
        }
 
        BigDecimal money = new BigDecimal(0);
        String orders = "";
        for (OrderRepairHistory history : historyList) {
            money = money.add(history.getAfterGetMoney().subtract(history.getBeforeGetMoney()));
            orders += history.getOrderId() + ",";
        }
        if (money.compareTo(new BigDecimal(0)) > 0)// 资金需要增加
        {
            try {
                UserMoneyDetail detail = UserMoneyDetailFactory.createSystemEqualize("订单统计异常修复", money,
                        new UserInfo(uid));
                // 系统补齐
                // 加资金
                userMoneyService.addUserMoney(uid, money, detail);
                pushMsg(uid, "关于近期订单与资金异常的排查与修复结果通知",
                        "尊敬的用户,经仔细核对您账户中的订单,发现您账户中有未统计或错误统计的订单,我们已经为您补齐资金,对应资金已经存入您的账户余额中,敬请查收注查收。感谢信任,返利券App终将成为您最信任的购物省钱助手。");
                userMoneyMsgNotificationService.systemEqualize(uid, "订单统计异常修复", money, userInfoService.getBalance(uid));
            } catch (UserMoneyDetailException e) {
                e.printStackTrace();
            }
 
        } else {// 资金需要减少,不要扣钱
            pushMsg(uid, "关于近期订单与资金异常的排查与修复结果通知",
                    "尊敬的用户,经仔细核对您账户中的订单,发现您账户中有错误统计的订单,我们已经为您恢复正常,所涉及订单多统计出来的资金,不会被扣除,即您账户中的资金将保持不变,已提现的资金,也不会收回,敬请知晓。感谢信任,返利券App终将成为您最信任的购物省钱助手。");
            // userMoneyMsgNotificationService.systemEqualize(uid, "订单统计异常修复",
            // money, userInfoService.getBalance(uid));
            // 加入提现审核异常保护中
            ExtractCheckCompensate check = new ExtractCheckCompensate();
            check.setBeiZhu("7月订单异常系统处理:" + orders);
            check.setCreateTime(new Date());
            check.setMoney(money);
            check.setUserInfo(new UserInfo(uid));
            check.setUpdateTime(new Date());
            extractCheckCompensateMapper.insertSelective(check);
        }
    }
 
    private void pushMsg(Long uid, String title, String content) {
 
        PushInfo pushInfo = new PushInfo();
        pushInfo.setTitle(title);
        pushInfo.setContent(content);
        pushInfo.setUids(uid + "");
        JSONObject jsonData = new JSONObject();
        jsonData.put("url", "");
        jsonData.put("ios", "全推");
        jsonData.put("android", "全推");
        pushInfo.setJsonData(jsonData.toString());
        pushInfo.setType(PushTypeEnum.ZNX);
        pushInfo.setArrayAndroid("[全推]");
        pushInfo.setArrayIOS("[全推]");
 
        pushInfo.setCreateTime(new Date());
 
        try {
            pushInfoService.save(pushInfo);
        } catch (PushInfoException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        try {
            pushInfoService.handPush(pushInfo.getId());
        } catch (PushInfoException e) {
            e.printStackTrace();
        } catch (PushException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
}