44323
2023-11-28 621d95aeff9feb8f4f1d7e2d33a18e5f2aa753c4
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
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
package com.dsh.course.service.impl;
 
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.Person;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.course.entity.*;
import com.dsh.course.entity.TAppUser;
import com.dsh.course.entity.dto.StudentQeryDto;
import com.dsh.course.feignclient.account.AppUserClient;
import com.dsh.course.feignclient.account.CoachClient;
import com.dsh.course.feignclient.account.StudentClient;
import com.dsh.course.feignclient.account.model.AppUser;
import com.dsh.course.feignclient.account.model.Coach;
import com.dsh.course.feignclient.account.model.Student;
import com.dsh.course.feignclient.account.model.TCourseInfoRecord;
import com.dsh.course.feignclient.activity.BenefitVideoClient;
import com.dsh.course.feignclient.activity.CouponClient;
import com.dsh.course.feignclient.activity.model.BenefitsVideos;
import com.dsh.course.feignclient.activity.model.Coupon;
import com.dsh.course.feignclient.model.RecordAppoint;
import com.dsh.course.feignclient.other.StoreClient;
import com.dsh.course.feignclient.other.model.Store;
import com.dsh.course.mapper.*;
import com.dsh.course.model.*;
import com.dsh.course.model.dto.DiscountJsonDto;
import com.dsh.course.model.vo.RegisterCourseVo;
import com.dsh.course.model.vo.request.*;
import com.dsh.course.model.vo.response.*;
import com.dsh.course.service.*;
import com.dsh.course.util.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 用户课程包购买记录 服务实现类
 * </p>
 *
 * @author administrator
 * @since 2023-06-14
 */
@Service
public class TCoursePackagePaymentServiceImpl extends ServiceImpl<TCoursePackagePaymentMapper, TCoursePackagePayment> implements TCoursePackagePaymentService {
 
 
    @Resource
    private BenefitVideoClient bfvoClient;
 
    @Resource
    private UserVideoDetailsMapper uvdmapper;
 
    @Resource
    private PostCourseVideoMapper pcvMapper;
 
    @Resource
    private TCoursePackageMapper tcpmapper;
 
    @Resource
    private StoreClient stoClient;
 
    @Resource
    private CoachClient coachClient;
 
    @Resource
    private CoursePackageStudentMapper cpsMapper;
 
    @Resource
    private CancelledClassesMapper cacMapper;
 
    @Resource
    private TCoursePackageDiscountMapper tcpdMapper;
 
    @Resource
    private CoursePackagePaymentConfigMapper cpConfigMapper;
 
    @Resource
    private CouponClient client;
 
    @Resource
    private PayMoneyUtil payMoneyUtil;
 
    @Resource
    private AppUserClient appuClient;
 
    @Resource
    private StudentClient studentClient;
 
    @Autowired
    private ICoursePackageSchedulingService coursePackageSchedulingService;
 
 
    @Autowired
    private RestTemplate internalRestTemplate;
 
 
    @Override
    public List<CoursePackagePaymentVO> listAll(CoursePackagePaymentQuery query) {
        return cpConfigMapper.listAll(query);
    }
 
    @Override
    public int changeState(CoursePackagePayDTO dto) {
 
        return cpConfigMapper.changeState(Long.valueOf(dto.getIds()), dto.getPayUserName(), dto.getUserId());
    }
 
    @Override
    public void updateBytime(TCoursePackagePayment coursePackagePayment) {
        this.baseMapper.updateBytime(coursePackagePayment);
    }
 
    @Override
    public List<RegisterOrderVO> listAllRegister(RegisterOrderQuery query) {
        String STime = null;
        String ETime = null;
        if (StringUtils.hasLength(query.getRegisterTime())) {
            STime = query.getRegisterTime().split(" - ")[0] + " 00:00:00";
            ETime = query.getRegisterTime().split(" - ")[1] + " 23:59:59";
        }
        return cpConfigMapper.listAllRegister(query, STime, ETime, query.getAmount());
    }
 
    @Override
    public List<Map<String, Object>> getStudentTotal(StudentQeryDto studentQeryDto) {
        List<Map<String, Object>> studentTotal = this.baseMapper.getStudentTotal(studentQeryDto);
 
        for (Map<String, Object> student : studentTotal) {
            Integer appUserId = (Integer) student.get("appUserId");
            AppUser appUser = appuClient.queryAppUser(appUserId);
            student.put("province", appUser.getProvince());
            student.put("provinceCode", appUser.getProvinceCode());
 
            student.put("city", appUser.getCity());
            student.put("cityCode", appUser.getCityCode());
 
            Student studentId = studentClient.queryStudentById((Integer) student.get("studentId"));
            student.put("studentName", studentId.getName());
            BigDecimal cashPayment = (BigDecimal) student.get("cashPayment");
            BigDecimal totalClassHours = (BigDecimal) student.get("totalClassHours");
            BigDecimal hasHours = (BigDecimal) student.get("hasHours");
            if (cashPayment == null) {
                continue;
            }
            if (totalClassHours.compareTo(BigDecimal.ZERO) == 0) {
                totalClassHours = totalClassHours.add(new BigDecimal("1"));
            }
            BigDecimal hasPayment = cashPayment.divide(totalClassHours, 2, RoundingMode.HALF_UP)
                    .multiply(hasHours).setScale(2, RoundingMode.HALF_UP);
            student.put("hasPayment", hasPayment);
        }
 
        if (studentQeryDto.getCityCode() != null && studentQeryDto.getCityCode() != "") {
            String value = studentQeryDto.getCityCode();
            boolean allZeros = value.substring(value.length() - 4).endsWith("0000");
            System.out.println(allZeros); // Output: true
            if (allZeros) {
                Iterator<Map<String, Object>> iterator = studentTotal.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> student = iterator.next();
                    String cityCode = (String) student.get("provinceCode");
                    if (!cityCode.equals(studentQeryDto.getCityCode())) {
                        iterator.remove(); // Remove the element from the list
                    }
                }
            } else {
                Iterator<Map<String, Object>> iterator = studentTotal.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> student = iterator.next();
                    String cityCode = (String) student.get("cityCode");
                    if (!cityCode.equals(studentQeryDto.getCityCode())) {
                        iterator.remove(); // Remove the element from the list
                    }
                }
            }
        }
 
        if (studentQeryDto.getStudentName() != null && studentQeryDto.getStudentName() != "") {
            List<Map<String, Object>> totallike = new ArrayList<>();
            for (Map<String, Object> student : studentTotal) {
                String studentName = (String) student.get("studentName");
                if (studentName.contains(studentQeryDto.getStudentName())) {
                    totallike.add(student);
                }
 
            }
            return totallike;
        }
        return studentTotal;
    }
 
    @Override
    public List<Map<String, Object>> bypac(PacQueryDto pacQueryDto) {
        if (pacQueryDto.getCityCode() != null && pacQueryDto.getCityCode() != "") {
            String value = pacQueryDto.getCityCode();
            boolean allZeros = value.substring(value.length() - 4).endsWith("0000");
            System.out.println(allZeros); // Output: true
 
            if (allZeros) {
                pacQueryDto.setProvinceCode(pacQueryDto.getCityCode());
                pacQueryDto.setCityCode(null);
            }
 
        }
        List<Map<String, Object>> maps = this.baseMapper.pacQueryDto(pacQueryDto);
 
        if (pacQueryDto.getName() != null && pacQueryDto.getName() != "") {
            List<Map<String, Object>> totallike = new ArrayList<>();
            for (Map<String, Object> student : maps) {
                String studentName = (String) student.get("name");
                if (studentName.contains(pacQueryDto.getName())) {
                    totallike.add(student);
                }
 
            }
            return totallike;
        }
 
 
        return maps;
    }
 
    @Override
    public List<TCoursePackagePayment> listOne(List<Integer> ids) {
        return this.baseMapper.listOne(ids);
    }
 
    @Override
    public Integer listStoreId(String code) {
        return this.baseMapper.queryStore(code);
    }
 
    /**
     * 获取课包购买人数
     *
     * @param coursePackageId
     * @return
     */
    @Override
    public Integer queryCountNumber(Integer coursePackageId) {
        return this.baseMapper.queryCountNumber(coursePackageId);
    }
 
    @Override
    public List<AppUserVideoResponse> queryAfterVideo(CourseOfAfterRequest search, List<Integer> courseIds) {
        List<AppUserVideoResponse> responses = new ArrayList<>();
        List<PostCourseVideo> videoList = new ArrayList<>();
        LambdaQueryWrapper<PostCourseVideo> queryWrapper = new LambdaQueryWrapper<PostCourseVideo>();
        if (courseIds.size() > 0) {
            queryWrapper.in(PostCourseVideo::getCoursePackageId, courseIds);
        }
        videoList = pcvMapper.selectList(queryWrapper);
        System.out.println(videoList);
        if (videoList.size() > 0) {
            List<Integer> videoIds = videoList.stream().map(PostCourseVideo::getCourseId).collect(Collectors.toList());
            List<UserVideoDetails> userVideoDetails = uvdmapper.selectList(new QueryWrapper<UserVideoDetails>()
                    .in("courseId", videoIds));
            if (userVideoDetails.size() > 0) {
                for (UserVideoDetails userVideoDetail : userVideoDetails) {
                    AppUserVideoResponse response = new AppUserVideoResponse();
                    TCoursePackage coursePackage = tcpmapper.selectById(userVideoDetail.getCoursePackageId());
                    response.setPackageName(coursePackage.getName());
                    response.setCoursePackageId(userVideoDetail.getCoursePackageId());
                    BenefitsVideos videosWithIds = bfvoClient.getVideosWithIds(userVideoDetail.getCourseId());
                    response.setVideoId(userVideoDetail.getCourseId());
                    response.setCoverImage(videosWithIds.getCover());
                    response.setVideoName(videosWithIds.getName());
                    response.setSynopsis(videosWithIds.getIntroduction());
                    response.setIntegral(videosWithIds.getIntegral());
                    response.setStudyStatus(userVideoDetail.getState());
                    responses.add(response);
                }
                Collections.sort(responses, Comparator.comparing(AppUserVideoResponse::getStudyStatus));
            }
            if (ToolUtil.isNotEmpty(search.getSearch())) {
                responses = responses.stream()
                        .filter(person -> person.getPackageName().contains(search.getSearch()))
                        .collect(Collectors.toList());
            }
            if (ToolUtil.isNotEmpty(search.getCourseTypeId())) {
                responses = responses.stream()
                        .filter(person -> Objects.equals(person.getCoursePackageId(), search.getCourseTypeId()))
                        .collect(Collectors.toList());
            }
        }
        return responses;
    }
 
    @Autowired
    private TCourseService courseService;
 
    @Override
    public CourseOfVideoResponse queryVideoDetails(CourseWithDetailsRequest detailsRequest, Integer appUserId) {
        CourseOfVideoResponse response = new CourseOfVideoResponse();
//        BenefitsVideos videosWithIds = bfvoClient.getVideosWithIds(detailsRequest.getVideoId());
        TCourse byId = courseService.getById(detailsRequest.getVideoId());
        TCoursePackage coursePackage = tcpmapper.selectById(detailsRequest.getCoursePackageId());
        CoursePackageScheduling byId1 = new CoursePackageScheduling();
        if (detailsRequest.getScId() != null) {
            byId1 = coursePackageSchedulingService.getById(detailsRequest.getScId());
        }
 
        if (null != coursePackage) {
            response.setCoursePackageId(coursePackage.getId());
            response.setVideoId(byId.getId());
            response.setVideoURL(byId.getCourseVideo());
            response.setVideoName(coursePackage.getName());
            UserVideoDetails userVideoDetails = uvdmapper.selectOne(new QueryWrapper<UserVideoDetails>()
                    .eq("appUserId", appUserId)
                    .eq("coursePackageId", coursePackage.getId())
                    .eq("courseId", detailsRequest.getVideoId()));
 
            if (userVideoDetails != null) {
                response.setStudyStatus(userVideoDetails.getState());
            } else {
                response.setStudyStatus(1);
            }
            response.setPackageName(coursePackage.getName());
            response.setSynopsis(byId.getIntroduce());
            response.setDetailedDiagram(byId.getIntroductionDrawing());
            response.setCover(byId.getCoverDrawing());
            if (byId1.getIntegral() != null) {
                response.setIntegral(String.valueOf(byId1.getIntegral()));
            }
 
        }
 
        return response;
    }
 
    @Override
    public String updateVideoStatus(UpdateCourseVideoStatusRequest detailsRequest, Integer appUserId) {
        UserVideoDetails userVideoDetails = uvdmapper.selectOne(new QueryWrapper<UserVideoDetails>()
                .eq("appUserId", appUserId)
                .eq("coursePackageId", detailsRequest.getCoursePackageId())
                .eq("courseId", detailsRequest.getVideoId())
        );
        if (null != userVideoDetails && userVideoDetails.getState() == 1 && detailsRequest.getIsOver() == 1) {
            userVideoDetails.setState(2);
            userVideoDetails.setUpdateTime(new Date());
            uvdmapper.updateById(userVideoDetails);
            return "SUCCESS";
        }
        return "ERROR";
    }
 
    @Autowired
    private TOrderService orderService;
 
    @Override
    public List<RegisterCourseVo> queryRegisteredCourseList(CourseOfAfterRequest courseTypeId, Integer appUserId) {
        List<RegisterCourseVo> courseVos = new ArrayList<>();
 
        List<TOrder> orders = orderService.list(new QueryWrapper<TOrder>().eq("appUserId", appUserId));
 
        List<String> paysId = new ArrayList<>();
 
        List<TCoursePackagePayment> tCoursePackagePayments = new ArrayList<>();
        for (TOrder order : orders) {
            String[] split = order.getPaysId().split(",");
//            paysId.add(split[0]);
            TCoursePackagePayment byId = this.getById(split[0]);
            byId.setPayStatus(order.getIsPay());
            byId.setOrderId(order.getId());
            tCoursePackagePayments.add(byId);
        }
 
//        List<TCoursePackagePayment> tCoursePackagePayments = this.list(new QueryWrapper<TCoursePackagePayment>()
//                .eq("appUserId",appUserId ));
//        List<TCoursePackagePayment> tCoursePackagePayments = this.list(new QueryWrapper<TCoursePackagePayment>()
//                .in("id",paysId ));
 
 
        System.out.println(tCoursePackagePayments);
        if (tCoursePackagePayments.size() > 0) {
            try {
                for (TCoursePackagePayment tCoursePackagePayment : tCoursePackagePayments) {
                    TCoursePackage coursePackage = tcpmapper.selectById(tCoursePackagePayment.getCoursePackageId());
                    Store store = stoClient.queryStoreById(coursePackage.getStoreId());
                    RegisterCourseVo registerCourseVo = new RegisterCourseVo();
                    // 2.0
                    registerCourseVo.setType(coursePackage.getType());
 
                    registerCourseVo.setOrderId(tCoursePackagePayment.getOrderId().longValue());
                    registerCourseVo.setCoursePayId(tCoursePackagePayment.getId());
                    registerCourseVo.setCoursePackageId(tCoursePackagePayment.getCoursePackageId());
                    registerCourseVo.setCoursePackTypeId(coursePackage.getCoursePackageTypeId());
                    registerCourseVo.setPackageImg(coursePackage.getCoverDrawing());
                    String storeAndCourse = coursePackage.getName() + "(" + store.getName() + ")";
                    registerCourseVo.setCourseNameStore(storeAndCourse);
//                registerCourseVo.setCourseTime(coursePackage.getClassStartTime()+"-"+coursePackage.getClassEndTime());
                    // 2.0
                    registerCourseVo.setCourseTime(new SimpleDateFormat("yyyy-MM-dd").format(tCoursePackagePayment.getInsertTime()));
                    Coach coach = coachClient.queryCoachById(coursePackage.getCoachId());
                    registerCourseVo.setCourseTeacher(ToolUtil.isEmpty(coach) ? "" : coach.getName());
                    if (coursePackage.getType() == 2) {
                        registerCourseVo.setTime(new SimpleDateFormat("yyyy-MM-dd").format(coursePackage.getStartTime()) + "-" + new SimpleDateFormat("yyyy-MM-dd").format(coursePackage.getEndTime()));
                    }
                    List<CoursePackageStudent> coursePackageStudents = cpsMapper.selectList(new QueryWrapper<CoursePackageStudent>()
                            .eq("coursePackageId", coursePackage.getId())
                            .eq("appUserId", appUserId));
 
                    List<Long> ids = new ArrayList<>();
                    for (CoursePackageStudent coursePackageStudent : coursePackageStudents) {
                        ids.add(coursePackageStudent.getCoursePackageSchedulingId());
                    }
                    List<CoursePackageScheduling> cps = new ArrayList<>();
 
                    if (!ids.isEmpty()) {
                        cps = coursePackageSchedulingService.list(new QueryWrapper<CoursePackageScheduling>().in("id", ids));
                    }
                    Integer counts = 0;
 
                    for (CoursePackageScheduling cp : cps) {
                        if (cp.getDeductClassHour() != null) {
                            counts = counts + cp.getDeductClassHour();
                        }
                    }
 
 
//                    Integer counts  = cpsMapper.selectCount(new QueryWrapper<CoursePackageStudent>()
//                            .eq("coursePackageId",coursePackage.getId())
//                            .eq("appUserId",appUserId ));
 
                    if (coursePackageStudents.size() > 0) {
//                        registerCourseVo.setCourseNums(coursePackageStudents.size() * 2);
                        registerCourseVo.setCourseNums(counts);
                    }
//                    registerCourseVo.setPayStatus(tCoursePackagePayment.getPayStatus());
                    registerCourseVo.setPayStatus(tCoursePackagePayment.getPayStatus());
 
                    courseVos.add(registerCourseVo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
 
            if (ToolUtil.isNotEmpty(courseTypeId.getSearch())) {
                courseVos = courseVos.stream()
                        .filter(person -> person.getCourseNameStore().contains(courseTypeId.getSearch()))
                        .collect(Collectors.toList());
            }
 
            if (ToolUtil.isNotEmpty(courseTypeId.getCourseTypeId())) {
                courseVos = courseVos.stream()
                        .filter(person -> Objects.equals(person.getCoursePackTypeId(), courseTypeId.getCourseTypeId()))
                        .collect(Collectors.toList());
            }
 
            if (courseVos.size() > 0) {
                courseVos = courseVos.stream()
                        .sorted(Comparator.comparingInt(person -> person.getPayStatus() == 1 ? -1 : 1))
                        .collect(Collectors.toList());
            }
        }
        return courseVos;
    }
 
    @Autowired
    private ICoursePackagePaymentConfigService coursePackagePaymentConfigService;
 
    @Autowired
    private TCoursePackageDiscountService coursePackageDiscountService;
 
    @Resource
    StoreClient storeClient;
 
    @Autowired
    private ICoursePackageOrderService coursePackageOrderService;
 
    @Autowired
    private ICoursePackageOrderStudentService coursePackageOrderStudentService;
 
    @Autowired
    private TCoursePackageService coursePackageService;
 
 
 
 
    @Override
    public CourseDetailsResponse queryRegisteredCourseDetails(Long coursePayId, Integer appUserId, String lon, String lat) {
        AppUser appUser = appuClient.queryAppUser(appUserId);
        CourseDetailsResponse response = new CourseDetailsResponse();
        CoursePackageOrder coursePackageOrder = coursePackageOrderService.getById(coursePayId);
 
 
        response.setChooseHours(coursePackageOrder.getClassHours());
 
        if (null != coursePackageOrder) {
            TCoursePackage coursePackage = tcpmapper.selectById(coursePackageOrder.getCoursePackageId());
            if (coursePackage.getType() == 2) {
                response.setTime(new SimpleDateFormat("yyyy.MM.dd").format(coursePackage.getStartTime()) + "-" + new SimpleDateFormat("yyyy.MM.dd").format(coursePackage.getEndTime()));
            }
            Store store = storeClient.queryStoreById(coursePackage.getStoreId());
            response.setStoreName(store.getName());
 
            if (ToolUtil.isNotEmpty(lon) && ToolUtil.isNotEmpty(lat)) {
                Map<String, Double> distance = GeodesyUtil.getDistance(lon + "," + lat, store.getLon() + "," + store.getLat());
                double wgs84 = new BigDecimal(distance.get("WGS84")).divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                response.setDistance(wgs84);
            }
            response.setCoursePackageId(coursePackageOrder.getCoursePackageId());
            response.setCoverDrawing(coursePackage.getCoverDrawing());
            response.setDetailDrawing(coursePackage.getDetailDrawing());
            response.setCoursePackageName(coursePackage.getName());
            response.setCoursePayId(coursePackageOrder.getId());
            response.setType(coursePackage.getType());
            List<Integer> integers = StrUtils.dealStrToList(coursePackage.getClassWeeks());
            String classWeeks = coursePackage.getClassWeeks();
            if (integers.size() > 0) {
                StringBuilder courWeeks = new StringBuilder("每" + classWeeks);
                response.setWeeks(courWeeks.toString());
            }
            ArrayList<String> classTime = new ArrayList<>();
            String[] split4 = coursePackage.getClassStartTime().split(",");
            String[] split3 = coursePackage.getClassEndTime().split(",");
            if (ToolUtil.isNotEmpty(coursePackage.getClassStartTime())) {
                for (int i = 0; i < split4.length; i++) {
                    String s = split4[i].substring(0, 5) + "-" + split3[i].substring(0, 5);
                    classTime.add(s);
                }
            }
 
            String joinedString = String.join("|", classTime);
 
            response.setCourseTimeFrame(joinedString);
 
 
            response.setIntroduceDrawing(coursePackage.getIntroduceDrawing());
 
            Integer payType = coursePackageOrder.getPayType();
            BigDecimal cashPayment = coursePackageOrder.getCashPayment();
            double cashPaymentValue = 0.0;
            if (cashPayment != null) {
 
                cashPaymentValue = cashPayment.doubleValue();
            }
            Integer playPaiCoin = coursePackageOrder.getPlayPaiCoin();
            TCoursePackageDiscount coursePackageDiscount = tcpdMapper.selectOne(new QueryWrapper<TCoursePackageDiscount>()
                    .eq("coursePackageId", coursePackage.getId())
                    .eq("type", 1)
                    .eq("auditStatus", 2));
            ObjectMapper objectMapper = new ObjectMapper();
            double discountMember = 0.0;
            if (coursePackageDiscount != null) {
                String content = coursePackageDiscount.getContent();
                DiscountJsonDto discountJsonDto = null;
                try {
                    discountJsonDto = objectMapper.readValue(content, DiscountJsonDto.class);
                    discountMember = discountJsonDto.getDiscountMember();
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
 
            switch (payType) {
                case 1:
                case 2:
                    response.setAmount(cashPaymentValue);
                    response.setVipAmount(discountMember);
                    break;
                case 3:
                    response.setWpGold(playPaiCoin);
                    break;
            }
 
            response.setPayStatus(coursePackageOrder.getPayStatus());
 
 
            List<CoursePackagePaymentConfigVo> list = new ArrayList<>();
            List<CoursePackagePaymentConfig> list1 = coursePackagePaymentConfigService.list(new QueryWrapper<CoursePackagePaymentConfig>().eq("coursePackageId", coursePackage.getId()).orderByAsc("classHours"));
            list1.forEach(coursePackagePaymentConfig -> {
                CoursePackagePaymentConfigVo coursePackagePaymentConfigVo = new CoursePackagePaymentConfigVo();
                coursePackagePaymentConfigVo.setId(coursePackagePaymentConfig.getId());
                coursePackagePaymentConfigVo.setClassHours(coursePackagePaymentConfig.getClassHours());
                coursePackagePaymentConfigVo.setPlayPaiCoin(coursePackagePaymentConfig.getPlayPaiCoin());
 
                if (ToolUtil.isNotEmpty(coursePackagePaymentConfig.getCashPayment()) && coursePackagePaymentConfig.getCashPayment() > 0 && ToolUtil.isNotEmpty(coursePackagePaymentConfig.getPlayPaiCoin()) && coursePackagePaymentConfig.getPlayPaiCoin() > 0) {
                    coursePackagePaymentConfigVo.setPayType(3);
                } else if (ToolUtil.isNotEmpty(coursePackagePaymentConfig.getCashPayment()) && coursePackagePaymentConfig.getCashPayment() > 0) {
                    coursePackagePaymentConfigVo.setPayType(1);
                } else if (ToolUtil.isNotEmpty(coursePackagePaymentConfig.getPlayPaiCoin()) && coursePackagePaymentConfig.getPlayPaiCoin() > 0) {
                    coursePackagePaymentConfigVo.setPayType(2);
                }
 
//                coursePackagePaymentConfigVo.setPayType(coursePackage.getPayType());
                //会员显示原价和支付价(会员价)。非会员显示会员价和支付价(最低)
                if (appUser.getIsVip() == 0) {//非会员
                    List<TCoursePackageDiscount> list2 = coursePackageDiscountService.list(new QueryWrapper<TCoursePackageDiscount>().eq("coursePackagePaymentConfigId", coursePackagePaymentConfig.getId())
                            .eq("type", 1).eq("auditStatus", 2));
                    Double vipPrice = coursePackagePaymentConfig.getCashPayment();
                    for (TCoursePackageDiscount coursePackageDiscount1 : list2) {
                        Double num1 = JSON.parseObject(coursePackageDiscount1.getContent()).getDouble("discountMember");
                        if (vipPrice.compareTo(num1) > 0) {
                            vipPrice = num1;
                        }
                    }
                    coursePackagePaymentConfigVo.setVipPrice(vipPrice);
                    Double paymentPrice = coursePackagePaymentConfig.getCashPayment();
                    List<TCoursePackageDiscount> list3 = coursePackageDiscountService.list(new QueryWrapper<TCoursePackageDiscount>().eq("coursePackagePaymentConfigId", coursePackagePaymentConfig.getId())
                            .eq("type", 3).eq("auditStatus", 2));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    for (TCoursePackageDiscount coursePackageDiscount2 : list3) {
                        /**
                         * [{
                         *     "startDate": "2023-01-01 00:00:00",
                         *     "endDate": "2023-12-31 23:59:59",
                         *     "startTime": "02:00:00",
                         *     "endTime": "23:00:00",
                         *     "weeks": [1, 2, 7],
                         *     "cashPayment": 100
                         * }]
                         */
                        JSONArray jsonArray = JSON.parseArray(coursePackageDiscount2.getContent());
                        for (int i = 0; i < jsonArray.size(); i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String startDate = jsonObject.getString("startDate");
                                String endDate = jsonObject.getString("endDate");
                                String startTime = jsonObject.getString("startTime");
                                String endTime = jsonObject.getString("endTime");
                                List<Integer> weeks = jsonObject.getJSONArray("weeks").toJavaList(Integer.class);
                                Double cashPayment2 = jsonObject.getDouble("cashPayment");
                                Date startDate_date = sdf.parse(startDate);
                                Date endDate_date = sdf.parse(endDate);
                                long timeMillis = System.currentTimeMillis();
                                if (timeMillis >= startDate_date.getTime() && timeMillis < endDate_date.getTime()) {
                                    Date date = new Date();
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTime(date);
                                    int week = calendar.get(Calendar.DAY_OF_WEEK);
                                    boolean isFirstSunday = (calendar.getFirstDayOfWeek() == Calendar.SUNDAY);
                                    if (isFirstSunday) {
                                        week = week - 1;
                                        if (week == 0) {
                                            week = 7;
                                        }
                                    }
                                    if (!weeks.contains(week)) {
                                        continue;
                                    }
 
                                    String[] split1 = startTime.split(":");
                                    Integer hour1 = Integer.valueOf(split1[0]);
                                    Calendar s = Calendar.getInstance();
                                    s.setTime(date);
                                    s.set(Calendar.HOUR_OF_DAY, hour1);
                                    s.set(Calendar.MINUTE, Integer.valueOf(split1[1]));
                                    s.set(Calendar.SECOND, Integer.valueOf(split1[2]));
 
                                    String[] split2 = endTime.split(":");
                                    Integer hour2 = Integer.valueOf(split2[0]);
                                    Calendar e = Calendar.getInstance();
                                    e.setTime(date);
                                    e.set(Calendar.HOUR_OF_DAY, hour2);
                                    e.set(Calendar.MINUTE, Integer.valueOf(split2[1]));
                                    e.set(Calendar.SECOND, Integer.valueOf(split2[2]));
 
                                    if (hour1 > hour2) {
                                        if (s.getTimeInMillis() > date.getTime()) {
                                            s.set(Calendar.DAY_OF_YEAR, s.get(Calendar.DAY_OF_YEAR) - 1);
                                        } else {
                                            e.set(Calendar.DAY_OF_YEAR, e.get(Calendar.DAY_OF_YEAR) + 1);
                                        }
                                    }
                                    if (timeMillis >= s.getTimeInMillis() && timeMillis < e.getTimeInMillis() && paymentPrice.compareTo(cashPayment2) > 0) {
                                        paymentPrice = cashPayment2;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    coursePackagePaymentConfigVo.setPaymentPrice(paymentPrice);
 
 
                    TCoursePackageDiscount discount = coursePackageDiscountService.getOne(new QueryWrapper<TCoursePackageDiscount>().eq("coursePackagePaymentConfigId", coursePackagePaymentConfig.getId())
                            .eq("type", 2).eq("auditStatus", 2));
 
                    Double continuingMember = JSON.parseObject(discount.getContent()).getDouble("continuingUser");
                    Double vipcontinuingMember = JSON.parseObject(discount.getContent()).getDouble("continuingMember");
 
 
                    if (coursePackagePaymentConfigVo.getPaymentPrice() > continuingMember) {
                        coursePackagePaymentConfigVo.setPaymentPrice(continuingMember);
                    }
                    if (coursePackagePaymentConfigVo.getVipPrice() > vipcontinuingMember) {
                        coursePackagePaymentConfigVo.setVipPrice(vipcontinuingMember);
                    }
 
 
                    if (coursePackagePaymentConfigVo.getPaymentPrice() < coursePackagePaymentConfigVo.getVipPrice()) {
                        coursePackagePaymentConfigVo.setOriginalPrice(coursePackagePaymentConfig.getCashPayment());
                        coursePackagePaymentConfigVo.setVipPrice(null);
                    }
 
                } else {
                    List<TCoursePackageDiscount> list2 = coursePackageDiscountService.list(new QueryWrapper<TCoursePackageDiscount>().eq("coursePackagePaymentConfigId", coursePackagePaymentConfig.getId())
                            .eq("type", 1).eq("auditStatus", 2));
                    Double vipPrice = coursePackagePaymentConfig.getCashPayment();
                    for (TCoursePackageDiscount coursePackageDiscount3 : list2) {
                        Double num1 = JSON.parseObject(coursePackageDiscount3.getContent()).getDouble("discountMember");
                        if (vipPrice.compareTo(num1) > 0) {
                            vipPrice = num1;
                        }
                    }
                    coursePackagePaymentConfigVo.setPaymentPrice(vipPrice);
                    coursePackagePaymentConfigVo.setOriginalPrice(coursePackagePaymentConfig.getCashPayment());
                }
                list.add(coursePackagePaymentConfigVo);
            });
            response.setList(list);
        }
        return response;
    }
 
    @Override
    public ResultUtil ContinuationOrpaymentCourse(Integer ids, ClasspaymentRequest request) {
        AppUser userIdFormRedis = appuClient.queryAppUser(ids);
        TCoursePackagePayment tCoursePackagePayment = this.baseMapper.selectById(request.getCoursePayId());
        String code = "";
        BigDecimal money = tCoursePackagePayment.getCashPayment();
        Integer wpGold = tCoursePackagePayment.getPlayPaiCoin();
        if (tCoursePackagePayment.getPayStatus() == 1) {
//            待支付的订单
            code = tCoursePackagePayment.getCode();
            tCoursePackagePayment.setPayType(request.getPayType());
            if (request.getUseConpon() == 1) {
                tCoursePackagePayment.setUserCouponId(Long.valueOf(request.getUseConpon()));
            }
            this.baseMapper.updateById(tCoursePackagePayment);
        } else {
//            续课的订单
//            查询是否续课优惠
 
            CoursePackagePaymentConfig paymentConfig = cpConfigMapper.selectOne(new QueryWrapper<CoursePackagePaymentConfig>()
                    .eq("coursePackageId", request.getLessonId())
                    .eq("classHours", request.getCourseHoursNum()));
            TCoursePackageDiscount coursePackageDiscount = tcpdMapper.selectOne(new QueryWrapper<TCoursePackageDiscount>()
                    .eq("coursePackageId", request.getLessonId())
                    .eq("type", 2)
                    .eq("auditStatus", 1)
                    .eq("coursePackagePaymentConfigId", paymentConfig.getCoursePackageId()));
            if (ToolUtil.isNotEmpty(coursePackageDiscount)) {
                String content = coursePackageDiscount.getContent();
                JSONObject jsonObject = JSON.parseObject(content);
                if (userIdFormRedis.getIsVip() == 1) {
                    Double jsonObjectDouble = jsonObject.getDouble("num1");
                    money = BigDecimal.valueOf(jsonObjectDouble);
                } else {
                    Double jsonObjectDouble = jsonObject.getDouble("num2");
                    money = BigDecimal.valueOf(jsonObjectDouble);
                }
            }
            TCoursePackagePayment newPayment = new TCoursePackagePayment();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            newPayment.setCode(sdf.format(new Date()) + UUIDUtil.getNumberRandom(5));
            newPayment.setAppUserId(userIdFormRedis.getId());
            newPayment.setStudentId(request.getStuId());
            newPayment.setCoursePackageId(request.getLessonId());
            newPayment.setClassHours(tCoursePackagePayment.getClassHours());
            newPayment.setOriginalPrice(tCoursePackagePayment.getOriginalPrice());
            newPayment.setTotalClassHours(tCoursePackagePayment.getTotalClassHours());
            newPayment.setLaveClassHours(tCoursePackagePayment.getTotalClassHours());
            if (request.getUseConpon() == 1) {
                newPayment.setUserCouponId(Long.valueOf(request.getUseConpon()));
            }
            newPayment.setAbsencesNumber(0);
            newPayment.setPayUserType(1);
            newPayment.setPayStatus(1);
            newPayment.setStatus(1);
            newPayment.setPayType(request.getPayType());
            newPayment.setState(1);
            newPayment.setInsertTime(new Date());
            this.baseMapper.insert(newPayment);
            code = newPayment.getCode();
        }
        switch (request.getPayType()) {
            case 1:
                if (request.getUseConpon() == 1) {
                    Coupon coupon = client.queryCouponById(request.getConponId());
                    if (coupon.getType() == 1) {
                        Map<String, Object> couponRules = client.getCouponRules(coupon.getId());
                        Double conditionalAmount = (Double) couponRules.get("conditionalAmount");
                        Double deductionAmount = (Double) couponRules.get("deductionAmount");
                        if (money.compareTo(BigDecimal.valueOf(conditionalAmount)) >= 0) {
                            money = BigDecimal.valueOf(deductionAmount);
                        }
                    }
                    if (coupon.getType() == 2) {
                        Map<String, Object> couponRules = client.getCouponRules(coupon.getId());
                        Object amount = couponRules.get("deductionAmount");
                        money = BigDecimal.valueOf((Double) amount);
                    }
                }
                try {
                    return WeChatPayment(code, money);
                } catch (Exception e) {
                    return ResultUtil.runErr();
                }
            case 2:
                if (request.getUseConpon() == 1) {
                    Coupon coupon = client.queryCouponById(request.getConponId());
                    if (coupon.getType() == 1) {
                        Map<String, Object> couponRules = client.getCouponRules(coupon.getId());
                        Double conditionalAmount = (Double) couponRules.get("conditionalAmount");
                        Double deductionAmount = (Double) couponRules.get("deductionAmount");
                        if (money.compareTo(BigDecimal.valueOf(conditionalAmount)) >= 0) {
                            money = BigDecimal.valueOf(deductionAmount);
                        }
                    }
                    if (coupon.getType() == 2) {
                        Map<String, Object> couponRules = client.getCouponRules(coupon.getId());
                        Object amount = couponRules.get("deductionAmount");
                        money = BigDecimal.valueOf((Double) amount);
                    }
                }
                return AlipayPayment(code, money);
            case 3:
                PlaypaiGoldPayment(userIdFormRedis, code, wpGold);
                break;
            default:
                break;
        }
        return ResultUtil.success();
    }
 
 
    public ResultUtil WeChatPayment(String code, BigDecimal request) throws Exception {
        TCoursePackagePaymentMapper baseMapper1 = this.baseMapper;
        ResultUtil weixinpay = payMoneyUtil.weixinpay("课包续费", "", code, request.toString(),
                "/base/coursePackage/wechatRegisteredCoursesCallback", "APP", "");
        if (weixinpay.getCode() == 200) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 10) {
                            int min = 5000;
                            wait += (min * num);
                            Thread.sleep(wait);
                            TCoursePackagePayment coursePackagePayment = baseMapper1.getCoursePackagePaymentByCode(code);
                            if (coursePackagePayment.getPayStatus() == 2) {
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
                            if (resultUtil.getCode() == 200 && coursePackagePayment.getPayStatus() == 1) {
                                /**
                                 * SUCCESS—支付成功,
                                 * REFUND—转入退款,
                                 * NOTPAY—未支付,
                                 * CLOSED—已关闭,
                                 * REVOKED—已撤销(刷卡支付),
                                 * USERPAYING--用户支付中,
                                 * PAYERROR--支付失败(其他原因,如银行返回失败)
                                 */
                                Map<String, String> data1 = resultUtil.getData();
                                String s = data1.get("trade_state");
                                String transaction_id = data1.get("transaction_id");
                                if ("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10) {
                                    coursePackagePayment.setState(3);
                                    baseMapper1.deleteById(coursePackagePayment.getId());
                                    break;
                                }
                                if ("SUCCESS".equals(s)) {
                                    coursePackagePayment.setPayStatus(2);
                                    coursePackagePayment.setOrderNumber(transaction_id);
                                    baseMapper1.updateById(coursePackagePayment);
                                    break;
                                }
                                if ("USERPAYING".equals(s)) {
                                    num++;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return weixinpay;
    }
 
 
    public ResultUtil AlipayPayment(String code, BigDecimal request) {
        TCoursePackagePaymentMapper baseMapper1 = this.baseMapper;
        ResultUtil alipay = payMoneyUtil.alipay("课包购买", "课包购买", "", code, request.toString(),
                "/base/coursePackage/alipayRegisteredCoursesCallback");
        if (alipay.getCode() == 200) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 10) {
                            int min = 5000;
                            wait += (min * num);
                            Thread.sleep(wait);
                            TCoursePackagePayment coursePackagePayment = baseMapper1.getCoursePackagePaymentByCode(code);
                            if (coursePackagePayment.getPayStatus() == 2) {
                                break;
                            }
                            AlipayTradeQueryResponse alipayTradeQueryResponse = payMoneyUtil.queryALIOrder(code);
 
                            if (coursePackagePayment.getPayStatus() == 1) {
                                /**
                                 * WAIT_BUYER_PAY(交易创建,等待买家付款)、
                                 * TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、
                                 * TRADE_SUCCESS(交易支付成功)、
                                 * TRADE_FINISHED(交易结束,不可退款)
                                 */
//                                Map<String, String> data1 = resultUtil.getData();
                                String s = alipayTradeQueryResponse.getTradeStatus();
                                String tradeNo = alipayTradeQueryResponse.getTradeNo();
                                if ("TRADE_CLOSED".equals(s) || "TRADE_FINISHED".equals(s) || num == 10) {
                                    coursePackagePayment.setState(3);
                                    baseMapper1.deleteById(coursePackagePayment.getId());
                                    break;
                                }
                                if ("TRADE_SUCCESS".equals(s)) {
                                    coursePackagePayment.setPayStatus(2);
                                    coursePackagePayment.setOrderNumber(tradeNo);
                                    baseMapper1.updateById(coursePackagePayment);
                                    break;
                                }
                                if ("WAIT_BUYER_PAY".equals(s)) {
                                    num++;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return alipay;
    }
 
    public ResultUtil PlaypaiGoldPayment(AppUser appUser, String code, Integer wpGold) {
        TCoursePackagePayment packagePayment = this.baseMapper.selectOne(new QueryWrapper<TCoursePackagePayment>()
                .eq("code", code));
        if (appUser.getPlayPaiCoins() < wpGold) {
            return ResultUtil.error("玩牌币不足!");
        }
        packagePayment.setPayStatus(2);
        packagePayment.setPayUserId(appUser.getId());
        packagePayment.setPlayPaiCoin(wpGold);
        this.baseMapper.updateById(packagePayment);
 
        appUser.setPlayPaiCoins(ToolUtil.isNotEmpty(appUser.getPlayPaiCoins()) ? appUser.getPlayPaiCoins() - wpGold : wpGold);
        appuClient.updateAppUser(appUser);
        return ResultUtil.success();
    }
 
 
    @Override
    public List<RecordAppoint> obtainStuClassDetails(Integer stuId, Integer appUserId, Integer pageNum) {
        List<RecordAppoint> recordVoList = new ArrayList<>();
        List<TCoursePackagePayment> tCoursePackagePayments = this.baseMapper.selectList(new QueryWrapper<TCoursePackagePayment>()
                .eq("studentId", stuId)
                .eq("appUserId", appUserId)
                .eq("payStatus", 2)
                .eq("status", 1)
                .orderByDesc("insertTime"));
 
        List<Integer> ids = new ArrayList<>();
        for (TCoursePackagePayment tCoursePackagePayment : tCoursePackagePayments) {
            ids.add(tCoursePackagePayment.getCoursePackageId());
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        if (tCoursePackagePayments.size() > 0) {
 
//            int pageNum = 1; // 页码
            int pageSize = 10; // 每页记录数
            Page<CoursePackageStudent> page = new Page<>(pageNum, pageSize);
 
//            for (TCoursePackagePayment tCoursePackagePayment : tCoursePackagePayments) {
//                List<CoursePackageStudent> coursePackageStudent1 = cpsMapper.selectList(new QueryWrapper<CoursePackageStudent>()
//                        .in("coursePackageId",ids)
//                        .eq("studentId",stuId)
//                        .eq("appUserId",appUserId)
//                        .eq("reservationStatus",1));
            IPage<CoursePackageStudent> coursePackageStudentPage = cpsMapper.selectPage(page, new QueryWrapper<CoursePackageStudent>()
                    .in("coursePackageId", ids)
                    .eq("studentId", stuId)
                    .eq("appUserId", appUserId)
                    .eq("reservationStatus", 1));
            List<CoursePackageStudent> coursePackageStudent1 = coursePackageStudentPage.getRecords();
 
 
            if (ToolUtil.isNotEmpty(coursePackageStudent1) && coursePackageStudent1.size() > 0) {
                TCoursePackage coursePackage = new TCoursePackage();
                Integer coursePackageId = -1;
                for (CoursePackageStudent coursePackageStudent : coursePackageStudent1) {
                    RecordAppoint recordVo = new RecordAppoint();
                    recordVo.setCoursePackageId(coursePackageStudent.getCoursePackageId());
 
                    if (!coursePackageStudent.getCoursePackageId().equals(coursePackageId)) {
                        coursePackage = tcpmapper.selectById(coursePackageStudent.getCoursePackageId());
                        coursePackageId = coursePackageStudent.getCoursePackageId();
                    }
 
                    recordVo.setSid(Arrays.asList(coursePackage.getStoreId()));
                    List<Integer> rid = stoClient.querySiteId(coursePackage.getStoreId());
                    recordVo.setRid(rid);
                    recordVo.setUserId(appUserId);
                    recordVo.setSiteId(coursePackage.getSiteId());
                    List<Integer> ids1 = getIds(coursePackage.getSiteId());
                    recordVo.setIds(ids1);
 
                    recordVo.setCoursePackageName(coursePackage.getName());
                    for (TCoursePackagePayment tCoursePackagePayment : tCoursePackagePayments) {
                        if (Objects.equals(coursePackageStudent.getCoursePackageId(), tCoursePackagePayment.getCoursePackageId())) {
                            recordVo.setCourseHours(tCoursePackagePayment.getClassHours());
 
                        }
                    }
 
//                        recordVo.setCourseHours(tCoursePackagePayment.getClassHours());
                    Date date = DateUtil.getDate();
 
 
                    CoursePackageScheduling byId = coursePackageSchedulingService.getById(coursePackageStudent.getCoursePackageSchedulingId());
//                        String classStartTime = coursePackage.getClassStartTime();
//                        String classEndTime = coursePackage.getClassEndTime();
                    //这里是过滤今天之后的数据
 
//                        if (byId == null||byId.getClassDate().after(new Date())){
//                            continue;
//                        }
 
                    if (byId == null) {
                        continue;
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateString1 = sdf.format(byId.getClassDate());
                    String dateString2 = sdf.format(byId.getEndDate());
 
 
                    recordVo.setTimeFrame(dateString1 + "-" + dateString2.substring(11));
 
//                        recordVo.setTimeFrame(simpleDateFormat.format(date)+" "+classStartTime+"-"+classEndTime);
                    Store store = stoClient.queryStoreById(coursePackage.getStoreId());
                    recordVo.setStoreNameAddr(store.getName() + store.getAddress());
                    recordVo.setCourseStuRecordId(coursePackageStudent.getId());
                    String classWeeks = coursePackage.getClassWeeks();
                    String[] split = classWeeks.split(";");
                    List<String> integerList = Arrays.asList(split);
                    String weekOfDate = DateTimeHelper.getWeekOfDate(new Date());
                    if (integerList.contains(weekOfDate)) {
                        String dat = simpleDateFormat.format(byId.getClassDate()) + " " + dateString1.substring(11);
 
                        Date start = null;
                        try {
                            start = format.parse(dat);
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        //已取消
                        if (byId.getStatus() == 4) {
                            recordVo.setStatus(4);
                        } else if (coursePackageStudent.getSignInOrNot() == 2) {
                            //已请假
                            recordVo.setStatus(5);
                        } else if (start.after(new Date())) {
                            //待上课
                            recordVo.setStatus(1);
                        }
//                            else if(coursePackageStudent.getSignInOrNot()==2){
//                                recordVo.setStatus(5);
//                            }
                        else {
//                                CancelledClasses cancelledClasses = cacMapper.selectOne(new QueryWrapper<CancelledClasses>()
//                                        .eq("coursePackageId",coursePackageStudent.getCoursePackageId()));
                            CancelledClasses cancelledClasses = cacMapper.selectOne(new QueryWrapper<CancelledClasses>()
                                    .eq("coursePackageSchedulingId", byId.getId()).last("limit 1"));
                            if (ToolUtil.isNotEmpty(cancelledClasses)) {
                                recordVo.setStatus(3);
                                // 消课 到课状态0 旷课
                                if (coursePackageStudent.getSignInOrNot() == 0) {
                                    recordVo.setStatus(6);
                                }
 
                            } else {
                                Date now = new Date();
                                if (now.after(byId.getClassDate()) && now.before(byId.getEndDate())) {
                                    recordVo.setStatus(2);
                                } else {
                                    recordVo.setStatus(3);
 
                                }
                            }
                        }
                    } else {
                        recordVo.setStatus(1);
                    }
                    recordVoList.add(recordVo);
                }
 
            } else {
//                    recordVo.setStatus(4);
            }
 
        }
//        }
 
        return recordVoList;
    }
 
    public List<Integer> getIds(Integer siteId) {
        HttpRequest httpRequest = HttpRequest.get("https://try.daowepark.com/v7/user_api/general/get_space_area?space_id=" + siteId);
        HttpResponse execute = httpRequest.execute();
        String body = execute.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Object data = jsonObject.get("data");
        JSONArray array = JSONArray.parseArray(data.toString());
        List<Integer> ids = new ArrayList<>();
        for (Object o : array) {
            JSONObject jsonObject1 = JSONObject.parseObject(o.toString());
            Object id = jsonObject1.get("id");
            Integer integer = Integer.valueOf(id.toString());
            ids.add(integer);
        }
        return ids;
 
    }
 
    @Override
    public ResultUtil insertVipPaymentCallback(String code, String orderNumber) {
        TCoursePackagePayment coursePackagePayment = this.baseMapper.getCoursePackagePaymentByCode(code);
        if (coursePackagePayment.getPayStatus() != 1) {
            return ResultUtil.success();
        }
        coursePackagePayment.setPayStatus(2);
        coursePackagePayment.setOrderNumber(orderNumber);
        this.baseMapper.updateById(coursePackagePayment);
        return ResultUtil.success();
    }
 
    @Override
    public List<BillingRequest> queryAmountDatas(Integer appUserId, String monthStart, String monthEnd) {
        return this.baseMapper.billingDataRequestVo(appUserId, monthStart, monthEnd);
    }
 
 
    /**
     * 获取课包报名信息
     *
     * @param page
     * @param queryRegistrationRecord
     * @return
     */
    @Override
    public List<Map<String, Object>> queryRegistrationRecord(Page<Map<String, Object>> page, QueryRegistrationRecord queryRegistrationRecord) {
        Integer coursePackageId = queryRegistrationRecord.getCoursePackageId();
        TCoursePackage coursePackage = coursePackageService.getById(coursePackageId);
        String userName = queryRegistrationRecord.getUserName();
        List<Integer> userIds = null;
        List<Integer> studentIds = null;
        if (ToolUtil.isNotEmpty(userName)) {
            List<AppUser> appUsers = appuClient.queryAppUserListByName(userName);
            if (appUsers.size() > 0) {
                userIds = appUsers.stream().map(AppUser::getId).collect(Collectors.toList());
            }
        }
        String studentName = queryRegistrationRecord.getStudentName();
        if (ToolUtil.isNotEmpty(studentName)) {
            List<Student> students = studentClient.queryStudentListByName(studentName);
            if (students.size() > 0) {
                studentIds = students.stream().map(Student::getId).collect(Collectors.toList());
            }
        }
 
        List<Map<String, Object>> list = new ArrayList<>();
 
        if (coursePackage.getType()==1){
      list = this.baseMapper.queryRegistrationRecord(page, coursePackageId, userIds, studentIds);}else {
            list = this.baseMapper.queryRegistrationRecord1(page, coursePackageId, userIds, studentIds);
        }
        for (Map<String, Object> map : list) {
 
            Long id = Long.valueOf(map.get("id").toString());
            Integer appUserId = Integer.valueOf(map.get("appUserId").toString());
            Integer studentId = 0;
            if (coursePackage.getType()==1) {
                studentId = Integer.valueOf(map.get("studentId").toString());
            }else {
                studentId = Integer.valueOf(map.get("studentIds").toString());
            }
 
            TAppUser appUser = appuClient.queryAppUser1(appUserId);
            map.put("userName", null != appUser ? appUser.getName() : "");
            map.put("phone", null != appUser ? appUser.getPhone() : "");
            Student student = studentClient.queryStudentById(studentId);
            map.put("studentName", null != student ? student.getName() : "");
            Integer integer = cpsMapper.selectCount(new QueryWrapper<CoursePackageStudent>().eq("appUserId", appUserId)
                    .eq("studentId", studentId).eq("coursePackagePaymentId", id).eq("signInOrNot", 2));
            map.put("already", integer);
        }
        return list;
    }
 
 
    /**
     * 获取未预约排课学员列表
     *
     * @param page
     * @param queryWalkInStudentList
     * @return
     */
    @Override
    public List<Map<String, Object>> queryWalkInStudentList(Page<Map<String, Object>> page, QueryWalkInStudentList queryWalkInStudentList) {
        Long coursePackageSchedulingId = queryWalkInStudentList.getCoursePackageSchedulingId();
        CoursePackageScheduling coursePackageScheduling = coursePackageSchedulingService.getById(coursePackageSchedulingId);
        String userName = queryWalkInStudentList.getUserName();
        List<Integer> userIds = null;
        List<Integer> studentIds = null;
        if (ToolUtil.isNotEmpty(userName)) {
            List<AppUser> appUsers = appuClient.queryAppUserListByName(userName);
            if (appUsers.size() > 0) {
                userIds = appUsers.stream().map(AppUser::getId).collect(Collectors.toList());
            }
        }
        String studentName = queryWalkInStudentList.getStudentName();
        if (ToolUtil.isNotEmpty(studentName)) {
            List<Student> students = studentClient.queryStudentListByName(studentName);
            if (students.size() > 0) {
                studentIds = students.stream().map(Student::getId).collect(Collectors.toList());
            }
        }
        List<Long> coursePackagePaymentId = null;
        List<CoursePackageStudent> coursePackageStudents = cpsMapper.selectList(new QueryWrapper<CoursePackageStudent>().eq("coursePackageSchedulingId", coursePackageSchedulingId).eq("reservationStatus", 1));
        if (coursePackageStudents.size() > 0) {
            coursePackagePaymentId = coursePackageStudents.stream().map(CoursePackageStudent::getCoursePackagePaymentId).collect(Collectors.toList());
        }
 
        List<Map<String, Object>> list = this.baseMapper.queryWalkInStudentList(page, coursePackageScheduling.getCoursePackageId(), coursePackagePaymentId, userIds, studentIds);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Integer now = Integer.valueOf(sdf.format(new Date()));
        for (Map<String, Object> map : list) {
            Integer appUserId = Integer.valueOf(map.get("appUserId").toString());
            Integer student_Id = Integer.valueOf(map.get("studentId").toString());
            AppUser appUser = appuClient.queryAppUser(appUserId);
            Student student = studentClient.queryStudentById(student_Id);
            map.put("userName", appUser.getName());
            map.put("phone", student.getPhone());
            map.put("studentName", student.getName());
            map.put("age", null != student.getBirthday() ? now - Integer.valueOf(sdf.format(student.getBirthday())) : "-");
            map.put("sex", student.getSex());
        }
        return list;
    }
 
    @Override
    public List<PayCourseRes> getMyCourseList(Integer storeId, Integer appUserId) {
        // 找到购买的课包
        List<CoursePackageOrderStudent> tCoursePackagePayments = coursePackageOrderStudentService.list(new LambdaQueryWrapper<CoursePackageOrderStudent>().eq(CoursePackageOrderStudent::getAppUserId, appUserId));
        ArrayList<PayCourseRes> payCourseRes = new ArrayList<>();
        for (CoursePackageOrderStudent tCoursePackagePayment : tCoursePackagePayments) {
            TCoursePackage tCoursePackage = tcpmapper.selectById(tCoursePackagePayment.getCoursePackageId());
            if (tCoursePackage.getType() != 1) {
                continue;
            }
            if (tCoursePackage.getStoreId().equals(storeId)) {
                PayCourseRes payCourseRes1 = new PayCourseRes();
                payCourseRes1.setId(tCoursePackagePayment.getId());
                payCourseRes1.setName(tCoursePackage.getName());
                payCourseRes1.setCourseNum(tCoursePackagePayment.getLaveClassHours());
                payCourseRes.add(payCourseRes1);
 
            }
        }
        return payCourseRes;
    }
 
    @Override
    public PayCourseInfoReq payCourseInfo(Integer courseId) {
        PayCourseInfoReq payCourseInfoReq = new PayCourseInfoReq();
        TCoursePackage tCoursePackage = tcpmapper.selectById(courseId);
        payCourseInfoReq.setId(courseId);
        payCourseInfoReq.setName(tCoursePackage.getName());
        payCourseInfoReq.setNum(tCoursePackage.getNeedNum());
        payCourseInfoReq.setWeek(tCoursePackage.getClassWeeks());
        String classStartTime = tCoursePackage.getClassStartTime();
        String classEndTime = tCoursePackage.getClassEndTime();
        String[] split = classStartTime.split(",");
        String[] split1 = classEndTime.split(",");
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < classStartTime.split(",").length; i++) {
            String s = split[i] + "-" + split1[i];
            strings.add(s);
        }
        payCourseInfoReq.setTime(strings);
        List<Integer> week = week(tCoursePackage.getClassWeeks());
 
        // 今天周几
        int i = cn.hutool.core.date.DateUtil.dayOfWeek(new Date()) - 1;
 
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        ArrayList<String> strings1 = new ArrayList<>();
 
        for (Integer integer : week) {
            if (integer < i) {
                // 找下一周的时间
                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.DATE, 7 - (i - integer));
                Date time = instance.getTime();
                strings1.add(format.format(time));
 
            } else if (integer > i) {
                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.DATE, integer - i);
                Date time = instance.getTime();
                strings1.add(format.format(time));
            } else {
                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.DATE, 7);
                Date time = instance.getTime();
                strings1.add(format.format(time));
            }
        }
        payCourseInfoReq.setDay(strings1);
        return payCourseInfoReq;
    }
 
    private static List<Integer> week(String week) {
        String[] split = week.split(";");
        ArrayList<Integer> integers = new ArrayList<>();
        for (String s : split) {
            switch (s) {
                case "周一":
                    integers.add(1);
                    break;
                case "周二":
                    integers.add(2);
                    break;
                case "周三":
                    integers.add(3);
                    break;
                case "周四":
                    integers.add(4);
                    break;
                case "周五":
                    integers.add(5);
                    break;
                case "周六":
                    integers.add(6);
                    break;
                case "周日":
                    integers.add(7);
                    break;
            }
        }
        return integers;
    }
 
    @Autowired
    private TCoursePackageService packageService;
 
 
    @Autowired
    private TCoursePackagePaymentService packagePaymentService;
    @Autowired
    private CoursePackageStudentService coursePackageStudentService;
 
    @Autowired
    private CourseCounsumService courseCounsumService;
 
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public ResultUtil payCourse(PayCourseReq req, Integer userId) throws ParseException {
        // 扣除 原来的课时数
        // 添加购买课时 paytyoe为7
        // 排课可期  判断课程时间段  添加排课表  添加上课记录表
        // 找到原来的课包 扣课时
        CoursePackageOrderStudent coursePackageOrderStudent = coursePackageOrderStudentService.getById(req.getOldCourseId());
        if (req.getNum() > coursePackageOrderStudent.getLaveClassHours()) {
            return ResultUtil.error("当前课包课时数不足");
        }
        TCoursePackage coursePackage = coursePackageService.getById(coursePackageOrderStudent.getCoursePackageId());
        TCoursePackage coursePackage1 = coursePackageService.getById(req.getCourseId());
        //判断剩余课时是否已经全部进行排课,如果排课需要删除已经排好的记录
        List<CoursePackageScheduling> list1 = coursePackageSchedulingService.list(new QueryWrapper<CoursePackageScheduling>()
                .eq("studentId", coursePackageOrderStudent.getStudentId()).eq("status", 1)
                .eq("type", 1).orderByDesc("classDate"));
        //已经排课但没有使用的课时数量
        int number = list1.size() * coursePackage.getNeedNum();
        Integer laveClassHours1 = coursePackageOrderStudent.getLaveClassHours();
        laveClassHours1 -= number;
        //需要购买使用的课时数
        Integer num = req.getNum();
        //需要删除多余的排课记录
        if(num.compareTo(laveClassHours1) > 0){
            //课时数差额
            int number1 = num - laveClassHours1;
            double o = number1 % coursePackage.getNeedNum();
            int l = 0;
            if(0 != o){
                l = 1;
            }
            int n = Double.valueOf(number1 / coursePackage.getNeedNum()).intValue() + l;
            for (int i = 0; i < n; i++) {
                CoursePackageScheduling coursePackageScheduling = list1.get(i);
                coursePackageSchedulingService.getBaseMapper().deleteById(coursePackageScheduling.getId());
 
                coursePackageStudentService.getBaseMapper().delete(new QueryWrapper<CoursePackageStudent>()
                        .eq("coursePackageSchedulingId", coursePackageScheduling.getId()));
            }
        }
 
 
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String classStartTime = coursePackage1.getClassStartTime();
        String classEndTime = coursePackage1.getClassEndTime();
        String[] split5 = classStartTime.split(",");
        String[] split6 = classEndTime.split(",");
        List<String> time = req.getTime();
        for (String s : time) {
            for (int i = 0; i < split5.length; i++) {
                CoursePackageScheduling coursePackageScheduling = new CoursePackageScheduling();
                coursePackageScheduling.setType(3);
                coursePackageScheduling.setAppUserId(userId);
                coursePackageScheduling.setStudentId(req.getStuId());
                coursePackageScheduling.setCoursePackageId(req.getCourseId());
                try {
                    Date parse = format.parse(s + " " + split5[i]);
                    Date parse1 = format.parse(s + " " + split6[i]);
                    coursePackageScheduling.setClassDate(parse);
                    coursePackageScheduling.setEndDate(parse1);
                    coursePackageScheduling.setStatus(1);
                    coursePackageSchedulingService.save(coursePackageScheduling);
 
                    CoursePackageStudent student1 = new CoursePackageStudent();
                    student1.setAppUserId(userId);
                    student1.setStudentId(req.getStuId());
                    student1.setCoursePackageId(req.getCourseId());
                    student1.setCoursePackagePaymentId(coursePackageOrderStudent.getId());
                    student1.setCoursePackageSchedulingId(coursePackageScheduling.getId());
                    student1.setSignInOrNot(1);
                    student1.setReservationStatus(1);
                    student1.setInsertTime(new Date());
                    student1.setType(1);
                    cpsMapper.insert(student1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
 
            }
        }
 
        coursePackageOrderStudent.setLaveClassHours(coursePackageOrderStudent.getLaveClassHours() - req.getNum());
        coursePackageOrderStudentService.updateById(coursePackageOrderStudent);
 
 
        CourseCounsum courseCounsum = new CourseCounsum();
        courseCounsum.setPaymentId(coursePackageOrderStudent.getId());
        courseCounsum.setChangeType(0);
        courseCounsum.setNum(req.getNum());
        courseCounsum.setInsertTime(new Date());
        courseCounsum.setReason("体验购课");
        courseCounsum.setAppUserId(userId);
        courseCounsumService.save(courseCounsum);
 
 
        if (coursePackageOrderStudent.getLaveClassHours() <= 3) {
            Integer appUserId = userId;
 
            //调用推送
            HttpHeaders headers = new HttpHeaders();
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            String s1 = appUserId + "_" + "Three";
            //定时修改排课状态
            String s = internalRestTemplate.getForObject("http://mb-cloud-gateway/netty/sendMsgToClient?id=" + s1, String.class);
            JSONObject jsonObject1 = JSON.parseObject(s, JSONObject.class);
            if (jsonObject1.getIntValue("code") != 200) {
                System.err.println(jsonObject1.getString("msg"));
            }
        }
 
        return ResultUtil.success();
 
    }
 
    @Override
    public void updateUseTime(Long id, Date date) {
        this.baseMapper.updateUseTime(id, date);
    }
 
    @Override
    public List<Integer> getStudentIds(Long payId, Integer classId, Integer appId) {
        return this.baseMapper.getStudentIds(payId, classId, appId);
    }
 
    @Override
    public boolean updateHoursById(TCoursePackagePayment byId, int i) {
        return this.baseMapper.updateHoursById1(byId.getId(), i);
    }
 
 
    public static Date[] generateDateArray(int numDays, Date date) {
//        LocalDate tomorrow = LocalDate.now().plusDays(1);
        LocalDate tomorrow = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().plusDays(1);
 
        Date[] dates = new Date[numDays];
 
        for (int i = 0; i < numDays; i++) {
            LocalDate currentDate = tomorrow.plusDays(i);
            dates[i] = Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        }
 
        return dates;
    }
 
}