无关风月
2024-11-15 529c840af92391b54e3547868e7cf1b65e90cef6
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
package com.xinquan.course.controller.client;
 
 
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinquan.common.core.constant.SecurityConstants;
import com.xinquan.common.core.domain.R;
import com.xinquan.common.core.utils.WebUtils;
import com.xinquan.common.core.utils.page.BeanUtils;
import com.xinquan.common.core.utils.page.CollUtils;
import com.xinquan.common.core.utils.page.PageDTO;
import com.xinquan.common.core.web.domain.BaseModel;
import com.xinquan.common.security.service.TokenService;
import com.xinquan.common.security.utils.SecurityUtils;
import com.xinquan.course.api.domain.Course;
import com.xinquan.course.api.domain.CourseDTO;
import com.xinquan.course.api.vo.CourseVO;
import com.xinquan.course.api.vo.StudyPageVO;
import com.xinquan.course.api.domain.CourseCategory;
import com.xinquan.course.api.domain.CourseChapter;
import com.xinquan.course.domain.CourseLearningRecord;
import com.xinquan.course.domain.CourseUserFavorite;
import com.xinquan.course.domain.export.CourseExport;
import com.xinquan.course.domain.export.CourseOffExport;
import com.xinquan.course.domain.vo.ClientCourseCategoryVO;
import com.xinquan.course.domain.vo.ClientCourseVO;
import com.xinquan.course.service.*;
import com.xinquan.meditation.api.domain.Meditation;
import com.xinquan.meditation.api.feign.RemoteMeditationService;
import com.xinquan.system.api.RemoteBannerService;
import com.xinquan.system.api.domain.AppUser;
import com.xinquan.system.api.domain.AppUserCourse;
import com.xinquan.system.api.domain.AppUserViewingHistory;
import com.xinquan.system.api.domain.vo.AppUserVO;
import com.xinquan.system.api.domain.vo.BannerVO;
import com.xinquan.course.api.domain.OrderCourseVO;
import com.xinquan.system.api.model.LoginUser;
import com.xinquan.user.api.feign.RemoteAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
 
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
 
/**
 * <p>
 * 线上课程表 前端控制器
 * </p>
 *
 * @author mitao
 * @since 2024-08-21
 */
@Api(tags = {"用户端-课程相关接口"})
@RestController
@RequiredArgsConstructor
@RequestMapping("/client/course/course")
public class ClientCourseController {
 
    private final CourseCategoryService courseCategoryService;
    private final CourseService courseService;
    private final RemoteBannerService remoteBannerService;
    private final RemoteAppUserService remoteAppUserService;
    @Resource
    private CourseChapterService courseChapterService;
    @Resource
    private CourseUserFavoriteService courseUserFavoriteService;
 
    @Resource
    private RemoteMeditationService remoteMeditationService;
    @Resource
    private CourseLearningRecordService courseLearningRecordService;
 
    @GetMapping("/getCourseCount")
    public R<String> getCourseCount() {
        StringBuilder stringBuilder = new StringBuilder();
        List<Course> list = courseService.lambdaQuery().eq(BaseModel::getDelFlag, 0)
                .eq(Course::getCourseType,1).list();
        List<Course> list1 = courseService.lambdaQuery().eq(BaseModel::getDelFlag, 0)
                .eq(Course::getCourseType, 2).list();
        stringBuilder.append(list.size()+list1.size()).append(",");
        List<Course> collect1 = list.stream().filter(t -> t.getChargeType() == 1).collect(Collectors.toList());
        List<Course> collect2 = list.stream().filter(t -> t.getChargeType() == 2).collect(Collectors.toList());
        List<Course> collect3 = list.stream().filter(t -> t.getChargeType() == 3).collect(Collectors.toList());
        stringBuilder.append(collect1.size()).append(",");
        stringBuilder.append(collect2.size()).append(",");
        stringBuilder.append(collect3.size()).append(",");
        stringBuilder.append(list1.size());
        return R.ok(stringBuilder.toString());
    }
    /**
     * 根据课程id 查询学习人数
     * @param id
     * @return
     */
    @GetMapping("/getCountByCourseId/{id}")
    public R<Integer> getCountByCourseId(
                                          @PathVariable("id")String id)
    {
        int size = courseLearningRecordService.lambdaQuery().eq(CourseLearningRecord::getCourseId, id)
                .groupBy(CourseLearningRecord::getAppUserId).list().size();
 
        return R.ok(size);
    }
    /**
     * 根据课程id 查询章节列表
     * @param id
     * @return
     */
    @GetMapping("/getChapterByCourseId/{id}")
    public R<List<CourseChapter>> getChapterByCourseId(
                                          @PathVariable("id")String id)
    {
        return R.ok(courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId,id).list());
    }
 
 
 
 
    @GetMapping("/getCourseByIds/{pageCurr}/{pageSize}/{ids}")
    public R<Page<Course>> getCourseByIds(@PathVariable("pageCurr") Integer pageCurr,
                                                  @PathVariable("pageSize") Integer pageSize,
                                                  @PathVariable("ids")String ids)
    {
        List<Long> collect = courseChapterService.lambdaQuery().in(CourseChapter::getId, Arrays.asList(ids.split(",")))
                .list().stream().map(CourseChapter::getCourseId).collect(Collectors.toList());
        if(collect.isEmpty()){
            collect.add(-1L);
        }
        Page<Course> page = courseService
                .lambdaQuery()
                .in(Course::getId,collect)
                .page(new Page<>(pageCurr, pageSize));
 
        if (page.getRecords().isEmpty()){
            return R.ok(page);
        }
        // 查询人数
        return R.ok(page);
    }
 
    /**
     * 远程调用 通过课程名字查询课程ids
     * @return
     */
    @PostMapping("/getCourseIdsByName/{name}")
    public R<List<Long>> getCourseIdsByName(@PathVariable("name") String name) {
        List<Long> collect = courseService.lambdaQuery().like(Course::getCourseTitle, name)
                .list().stream().map(Course::getId)
                .collect(Collectors.toList());
        return R.ok(collect);
    }
 
    @ApiOperation(value = "课程管理列表导出", tags = {"管理后台-课程管理"})
    @PutMapping("/export")
    public void export(@RequestBody CourseDTO courseDTO)
    {
        List<Long> longs = new ArrayList<>();
        LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseLambdaQueryWrapper.like(StringUtils.isNotBlank(courseDTO.getTutor()), Course::getTutor, courseDTO.getTutor())
                .eq(Objects.nonNull(courseDTO.getCateId()), Course::getCateId, courseDTO.getCateId())
                .eq(Objects.nonNull(courseDTO.getCourseType()), Course::getCourseType, courseDTO.getCourseType())
                .eq(Objects.nonNull(courseDTO.getChargeType()), Course::getChargeType, courseDTO.getChargeType())
                .eq(Objects.nonNull(courseDTO.getListingStatus()), Course::getListingStatus, courseDTO.getListingStatus())
                .orderByDesc(Course::getSortNum);
        if (org.springframework.util.StringUtils.hasLength(courseDTO.getIds())){
            courseLambdaQueryWrapper.in(Course::getId, Arrays.asList(courseDTO.getIds().split(",")));
        }
        if (org.springframework.util.StringUtils.hasLength(courseDTO.getCourseTitle())){
            List<Long> collect = courseService.lambdaQuery().like(Course::getCourseTitle, courseDTO.getCourseTitle()).list()
                    .stream().map(Course::getId).collect(Collectors.toList());
            longs.addAll(collect);
            List<Long> collect1 = courseChapterService.lambdaQuery().like(CourseChapter::getChapterTitle, courseDTO.getCourseTitle()).list()
                    .stream().map(CourseChapter::getCourseId).collect(Collectors.toList());
            longs.addAll(collect1);
            if (longs.isEmpty()){
                longs.add(-1L);
            }
            courseLambdaQueryWrapper.in(Course::getId, longs);
        }
        List<Course> page = courseService.list(courseLambdaQueryWrapper);
        List<CourseExport> courseExports = new ArrayList<>();
        List<CourseOffExport> courseOffExports = new ArrayList<>();
        for (Course record : page) {
            CourseExport courseExport = new CourseExport();
            CourseOffExport courseOffExport = new CourseOffExport();
            CourseCategory byId = courseCategoryService.getById(record.getCateId());
            if (Objects.nonNull(byId)){
                record.setCategoryName(byId.getName());
                courseExport.setCategoryName(byId.getName());
            }
            record.setUid(record.getId().toString());
            long count = courseChapterService.count(new LambdaQueryWrapper<CourseChapter>().eq(CourseChapter::getCourseId, record.getId()));
            record.setCourseChapterCount(count);
            // 查询收藏数量
            long count1 = courseUserFavoriteService.count(new LambdaQueryWrapper<CourseUserFavorite>()
                    .eq(CourseUserFavorite::getCourseId, record.getId()));
            record.setCollectCount(count1);
            int size1 = courseLearningRecordService.lambdaQuery().eq(CourseLearningRecord::getCourseId, record.getId())
                    .groupBy(CourseLearningRecord::getAppUserId).list().size();
            // 查询学习人数
//            int size = remoteAppUserService.getUserByCourseId(record.getId()).getData().size();
            record.setCount(size1);
            courseExport.setName(record.getCourseTitle());
            courseExport.setTutor(record.getTutor());
            if (record.getCourseType()==1){
            switch (record.getChargeType()){
                case 1:
                    courseExport.setGeneralPrice("免费");
                    break;
                case 2:
                    courseExport.setGeneralPrice("会员免费");
                    break;
                case 3:
                    courseExport.setGeneralPrice("¥"+record.getGeneralPrice());
                    break;
            }
            }
 
            courseExport.setCourseChapterCount(count+"");
            courseExport.setListingStatus(record.getListingStatus()+"");
            courseExport.setRealLearnedNum(size1+"");
            courseExport.setCollectCount(count1+"");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = df.format(record.getCreateTime());
            courseExport.setCreateTime(format);
            courseExports.add(courseExport);
            // 线下
            courseOffExport.setName(record.getCourseTitle());
            courseOffExport.setTutor(record.getTutor());
            courseOffExport.setAddress(record.getAddress()+record.getAddressDetail());
            courseOffExport.setListingStatus(record.getListingStatus()+"");
            courseOffExport.setCollectCount(count1+"");
            courseOffExport.setCreateTime(format);
            courseOffExports.add(courseOffExport);
        }
        if (courseDTO.getCourseType()==1){
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), CourseExport.class, courseExports);
            HttpServletResponse response = WebUtils.response();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream outputStream = null;
            try {
                String fileName = URLEncoder.encode("线上课程导出.xls", "utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), CourseOffExport.class, courseOffExports);
            HttpServletResponse response = WebUtils.response();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream outputStream = null;
            try {
                String fileName = URLEncoder.encode("线下课程导出.xls", "utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @PostMapping("/courseManagementList")
    @ApiOperation(value = "课程管理列表-分页", tags = {"管理后台-课程管理"})
    public R<PageDTO<Course>> courseManagementList(@RequestBody CourseDTO courseDTO) {
        List<Long> longs = new ArrayList<>();
        LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseLambdaQueryWrapper.like(StringUtils.isNotBlank(courseDTO.getTutor()), Course::getTutor, courseDTO.getTutor())
                .eq(Objects.nonNull(courseDTO.getCateId()), Course::getCateId, courseDTO.getCateId())
                .eq(Objects.nonNull(courseDTO.getCourseType()), Course::getCourseType, courseDTO.getCourseType())
                .eq(Objects.nonNull(courseDTO.getChargeType()), Course::getChargeType, courseDTO.getChargeType())
                .eq(Objects.nonNull(courseDTO.getListingStatus()), Course::getListingStatus, courseDTO.getListingStatus())
                .orderByDesc(Course::getCreateTime);
        if (org.springframework.util.StringUtils.hasLength(courseDTO.getCourseTitle())){
            List<Long> collect = courseService.lambdaQuery().like(Course::getCourseTitle, courseDTO.getCourseTitle()).list()
                    .stream().map(Course::getId).collect(Collectors.toList());
            longs.addAll(collect);
            List<Long> collect1 = courseChapterService.lambdaQuery().like(CourseChapter::getChapterTitle, courseDTO.getCourseTitle()).list()
                    .stream().map(CourseChapter::getCourseId).collect(Collectors.toList());
            longs.addAll(collect1);
            if (longs.isEmpty()){
                longs.add(-1L);
            }
            courseLambdaQueryWrapper.in(Course::getId, longs);
        }
        Page<Course> page = courseService.page(new Page<>(courseDTO.getPageCurr(), courseDTO.getPageSize()), courseLambdaQueryWrapper);
        if (CollUtils.isEmpty(page.getRecords())) {
            return R.ok(PageDTO.empty(page));
        }
        for (Course record : page.getRecords()) {
            CourseCategory byId = courseCategoryService.getById(record.getCateId());
            if (Objects.nonNull(byId)){
                record.setCategoryName(byId.getName());
            }
            record.setUid(record.getId().toString());
            long count = courseChapterService.count(new LambdaQueryWrapper<CourseChapter>().eq(CourseChapter::getCourseId, record.getId()));
            record.setCourseChapterCount(count);
            // 查询收藏数量
            long count1 = courseUserFavoriteService.count(new LambdaQueryWrapper<CourseUserFavorite>()
                    .eq(CourseUserFavorite::getCourseId, record.getId()));
            record.setCollectCount(count1);
            // 查询学习人数
//            record.setCount(remoteAppUserService.getUserByCourseId(record.getId()).getData().size());
            int size1 = courseLearningRecordService.lambdaQuery().eq(CourseLearningRecord::getCourseId, record.getId())
                    .groupBy(CourseLearningRecord::getAppUserId).list().size();
            List<CourseChapter> list = courseChapterService.lambdaQuery()
                    .eq(CourseChapter::getCourseId, record.getId()).list();
            // 章节列表累加虚拟学习人数
            int temp = 0;
            for (CourseChapter courseChapter : list) {
                temp+=courseChapter.getVirtualLearnedNum();
            }
            record.setCount(size1+temp);
        }
        return R.ok(PageDTO.of(page, Course.class));
    }
    @PostMapping("/addCourse")
    @ApiOperation(value = "新增课程管理", tags = "管理后台-课程管理")
    public R addCourse(@RequestBody Course homeBackgroundMusic) {
        homeBackgroundMusic.setCreateBy(SecurityUtils.getUsername());
        homeBackgroundMusic.setCreateTime(LocalDateTime.now());
        return R.ok(courseService.save(homeBackgroundMusic));
    }
    @GetMapping("/detailCourse")
    @ApiOperation(value = "查看详情课程管理", tags = "管理后台-课程管理")
    public R<Course> detailCourse(String uid) {
        Course byId = courseService.getById(uid);
        CourseCategory byId1 = courseCategoryService.getById(byId.getCateId());
        if (byId1!=null){
            byId.setCategoryName(byId1.getName());
        }
        List<CourseChapter> list = courseChapterService.lambdaQuery()
                .eq(CourseChapter::getCourseId, uid).list();
 
        int a = 0;
        int b = 0;
        for (CourseChapter courseChapter : list) {
            a+= courseChapter.getVirtualLearnedNum();
            Long data1 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
            b+=data1;
        }
        int size1 = courseLearningRecordService.lambdaQuery()
                .eq(CourseLearningRecord::getCourseId, uid).groupBy(CourseLearningRecord::getAppUserId)
                .list().size();
        byId.setVirtualLearnedNum(a);
        byId.setRealLearnedNum(b);
        byId.setCount(a+b);
        byId.setList(list);
        int size = courseUserFavoriteService.lambdaQuery()
                .eq(CourseUserFavorite::getCourseId, uid).list().size();
        byId.setCollectCount((long) size);
        return R.ok(byId);
    }
    @GetMapping("/updateState")
    @ApiOperation(value = "修改课程上下架状态", tags = "管理后台-课程管理")
    public R updateState(String uid) {
        Course byId = courseService.getById(uid);
        if (byId.getListingStatus() == 1){
            byId.setListingStatus(2);
        }else {
            byId.setListingStatus(1);
        }
        courseService.updateById(byId);
        return R.ok();
    }
    @PostMapping("/updateCourse")
    @ApiOperation(value = "修改课程管理", tags = "管理后台-课程管理")
    public R updateCourse(@RequestBody Course homeBackgroundMusic) {
        homeBackgroundMusic.setUpdateBy(SecurityUtils.getUsername());
        homeBackgroundMusic.setUpdateTime(LocalDateTime.now());
        return R.ok(courseService.updateById(homeBackgroundMusic));
    }
    @PostMapping("/deleteCourse")
    @ApiOperation(value = "批量删除", tags = "管理后台-课程管理")
    public R deleteCourse(String ids) {
        return R.ok(courseService.removeBatchByIds(Arrays.asList(ids.split(",")).stream().map(Long::valueOf).collect(Collectors.toList())));
    }
 
 
 
    @GetMapping("/cateList")
    public R<List<CourseCategory>> cateList() {
        List<CourseCategory> list = courseCategoryService.list();
        for (CourseCategory courseCategory : list) {
            courseCategory.setUid(courseCategory.getId().toString());
        }
        return R.ok(list);
    }
    @PostMapping("/courseList")
    public R<PageDTO<Course>> courseList(@RequestBody CourseDTO courseDTO) {
        Page<Course> page = courseService.lambdaQuery()
                .like(StringUtils.isNotBlank(courseDTO.getCourseTitle()), Course::getCourseTitle, courseDTO.getCourseTitle())
                .like(StringUtils.isNotBlank(courseDTO.getTutor()), Course::getTutor, courseDTO.getTutor())
                .eq(Objects.nonNull(courseDTO.getCateId()), Course::getCateId, courseDTO.getCateId())
                .eq(Objects.nonNull(courseDTO.getCourseType()), Course::getCourseType, courseDTO.getCourseType())
                .orderByDesc(Course::getSortNum)
                .page(new Page<>(courseDTO.getPageCurr(), courseDTO.getPageSize()));
        if (CollUtils.isEmpty(page.getRecords())) {
            return R.ok(PageDTO.empty(page));
        }
        for (Course record : page.getRecords()) {
            CourseCategory byId = courseCategoryService.getById(record.getCateId());
            if (Objects.nonNull(byId)){
                record.setCategoryName(byId.getName());
            }
            record.setUid(record.getId().toString());
        }
        return R.ok(PageDTO.of(page, Course.class));
    }
    @Autowired
    private TokenService tokenService;
    @PostMapping("/myCollect")
    @ApiOperation(value = "我的收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "state", value = "1冥想 2课程", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageCurr", value = "分页参数,当前页码", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "分页参数,每页数量", dataType = "Integer", required = true)
    })
    public R<List<OrderCourseVO>> myCollect(@RequestParam(value = "state")Integer state,
                                               @RequestParam(value = "pageCurr")Integer pageCurr,
                                               @RequestParam(value = "pageSize")Integer pageSize) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser==null){
            return R.tokenError("登录失效");
        }
        Long userId = loginUser.getUserid();
        List<OrderCourseVO> orderCourseVOS = new ArrayList<>();
 
        switch (state){
            case 1:
                Page<Meditation> data = remoteMeditationService.getMeditationById(pageCurr, pageSize,userId)
                        .getData();
                for (Meditation meditation : data.getRecords()) {
                    OrderCourseVO orderCourseVO = new OrderCourseVO();
                    orderCourseVO.setBusinessId(meditation.getId());
                    orderCourseVO.setCourseTitle(meditation.getMeditationTitle());
                    orderCourseVO.setDescription(meditation.getDetailDescription());
                    orderCourseVO.setChargeType(meditation.getChargeType());
                    orderCourseVO.setGeneralPrice(meditation.getGeneralPrice());
                    orderCourseVO.setIosPrice(meditation.getIosPrice());
                    orderCourseVO.setCoverUrl(meditation.getCoverUrl());
                    orderCourseVO.setCoverDescription(meditation.getCoverDescription());
                    orderCourseVO.setCount(meditation.getRealLearnedNum()+meditation.getVirtualLearnedNum());
                    orderCourseVOS.add(orderCourseVO);
                }
                break;
            case 2:
                List<Long> collect = courseUserFavoriteService.lambdaQuery()
                        .eq(CourseUserFavorite::getAppUserId, userId).list().stream()
                        .map(CourseUserFavorite::getCourseId).collect(Collectors.toList());
                if(collect.isEmpty())collect.add(-1L);
                Page<Course> page = courseService
                .lambdaQuery()
                .in(Course::getId, collect)
                .page(new Page<>(pageCurr, pageSize));
                for (Course record : page.getRecords()) {
                    OrderCourseVO orderCourseVO = new OrderCourseVO();
                    orderCourseVO.setBusinessId(record.getId());
                    orderCourseVO.setCourseTitle(record.getCourseTitle());
                    orderCourseVO.setDescription(record.getDescription());
                    orderCourseVO.setChargeType(record.getChargeType());
                    orderCourseVO.setGeneralPrice(record.getGeneralPrice());
                    orderCourseVO.setIosPrice(record.getIosPrice());
                    orderCourseVO.setCoverUrl(record.getCoverUrl());
                    List<CourseChapter> list = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, record.getId()).list();
                    int temp = 0 ;
                    int temp1 = 0 ;
                    for (CourseChapter courseChapter : list) {
                        temp+= courseChapter.getVirtualLearnedNum();
                        Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                        temp1+=data2;
                    }
                    orderCourseVO.setCount(temp+temp1);
                    orderCourseVOS.add(orderCourseVO);
                }
                break;
        }
        return R.ok(orderCourseVOS);
    }
    @PostMapping("/collectCourse")
    @ApiOperation(value = "收藏/取消课程")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程id", name = "id", required = true, dataType = "Long"),
    })
    public R collectCourse(@RequestParam(value = "id")Long id) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser==null){
            return R.tokenError("登录失效");
        }
        Long userId = loginUser.getUserid();
        CourseUserFavorite one = courseUserFavoriteService.lambdaQuery()
                .eq(CourseUserFavorite::getAppUserId, userId)
                .eq(CourseUserFavorite::getCourseId, id).one();
        if (one==null){
            // 收藏课程
            CourseUserFavorite courseUserFavorite = new CourseUserFavorite();
            courseUserFavorite.setAppUserId(userId);
            courseUserFavorite.setCourseId(id);
            courseUserFavoriteService.save(courseUserFavorite);
        }else{
            // 取消收藏
            courseUserFavoriteService.removeById(one);
        }
        return R.ok();
    }
 
 
    /**
     * 远程调用 根据课程id查询课程信息
     *
     * @return 课程分类列表
     */
    @PostMapping("/getCourseByIdAny")
    public R<OrderCourseVO> getCourseByIdAny(@RequestBody OrderCourseVO req) {
        Course byId = courseService.getById(req.getBusinessId());
        List<AppUser> data = remoteAppUserService.getUserByCourseId(req.getBusinessId()).getData();
        if (data!=null){
            req.setCount(data.size());
            req.setCourseTitle(byId.getCourseTitle());
            req.setDescription(byId.getDescription());
            req.setGeneralPrice(byId.getGeneralPrice());
            req.setIosPrice(byId.getIosPrice());
            req.setCoverUrl(byId.getCoverUrl());
        }
        return R.ok(req);
    }
 
    /**
     * 获取轮播图列表
     *
     * @return 轮播图列表
     */
    @GetMapping("/getBannerList")
    @ApiOperation(value = "获取轮播图列表")
    public R<List<BannerVO>> getBannerList() {
        return remoteBannerService.getBannerList(SecurityConstants.INNER);
    }
 
    /**
     * 获取课程分类列表
     *
     * @return 课程分类列表
     */
    @GetMapping("/getCourseCategoryList")
    @ApiOperation(value = "获取课程分类列表")
    public R<List<ClientCourseCategoryVO>> getCourseCategoryList() {
        return R.ok(courseCategoryService.getCourseCategoryList());
    }
    /**
     * 远程调用 根据分类id 获取分类对象
     *
     * @return 课程分类列表
     */
    @GetMapping("/getCategoryById/{id}")
    public R<CourseCategory> getCategoryById(@PathVariable("id") String id) {
        return R.ok(courseCategoryService.getById(id));
    }
    /**
     * 课程详情
     *
     * @return 课程详情
     */
 
 
    /**
     * 课程详情
     *
     * @return 课程详情
     */
    @PostMapping("/getPayCourseInfoById")
    @ApiOperation(value = "根据id获取课程详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程id", name = "id", required = true, dataType = "String"),
    })
    public R<ClientCourseVO> getPayCourseInfoById(@RequestParam(value = "id")Long id) {
 
        Course byId = courseService.getById(id);
        ClientCourseVO clientCourseVO = new ClientCourseVO();
        BeanUtils.copyProperties(byId, clientCourseVO);
        clientCourseVO.setIsBuy(2);
        List<AppUser> data = remoteAppUserService.getUserByCourseId(id).getData();
        if (byId.getChargeType()==1 && tokenService.getLoginUser()==null){
            if (data!=null){
                clientCourseVO.setCount(data.size());
                if (data.size()>=5){
                    clientCourseVO.setHeaders(data.stream().limit(5).map(AppUser::getAvatar).collect(Collectors.toList()));
                }else{
                    clientCourseVO.setHeaders(data.stream().map(AppUser::getAvatar).collect(Collectors.toList()));
                }
            }
        }else{
            LoginUser loginUser = tokenService.getLoginUser();
            if (loginUser==null){
                return R.tokenError("登录失效");
            }
            Long userId = loginUser.getUserid();
            AppUser data1 = remoteAppUserService.getAppUserById(userId + "").getData();
            if (data1.getVipExpireTime()!=null && data1.getVipExpireTime().isAfter(LocalDateTime.now())){
                clientCourseVO.setIsVip(1);
            }else{
                clientCourseVO.setIsVip(0);
            }
            List<Long> collect9 = data.stream().map(AppUser::getId).collect(Collectors.toList());
            if (!collect9.isEmpty()){
                if (collect9.contains(userId)){
                    clientCourseVO.setIsBuy(1);
                }
            }
            if(byId.getChargeType() != 1){
                List<CourseChapter> list = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, byId.getId())
                        .list();
                // 累加实际学习人数
                int a = 0;
                int b = 0;
                for (CourseChapter courseChapter : list) {
                    Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                    a+=data2;
                    b+=courseChapter.getVirtualLearnedNum();
                }
                clientCourseVO.setCount(a+b);
            }else if (data!=null){
                // 查询学习人数和头像列表
                clientCourseVO.setCount(data.size());
                List<CourseChapter> list = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, byId.getId())
                        .list();
                // 累加实际学习人数
                int a = 0;
                int b = 0;
                for (CourseChapter courseChapter : list) {
                    Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                    a+=data2;
                    b+=courseChapter.getVirtualLearnedNum();
                }
                clientCourseVO.setCount(a+b);
                if (data.size()>=5){
                    clientCourseVO.setHeaders(data.stream().limit(5).map(AppUser::getAvatar).collect(Collectors.toList()));
                }else{
                    clientCourseVO.setHeaders(data.stream().map(AppUser::getAvatar).collect(Collectors.toList()));
                }
                List<Long> collect = data.stream().map(AppUser::getId).collect(Collectors.toList());
                if (!collect.isEmpty()){
                    if (collect.contains(userId)){
                        clientCourseVO.setIsBuy(1);
                    }
                }
 
            }
            // 查询是否已收藏课程
            clientCourseVO.setIsCollect(courseUserFavoriteService.lambdaQuery()
                    .eq(CourseUserFavorite::getAppUserId, userId)
                    .eq(CourseUserFavorite::getCourseId, id).one() == null ? 2 : 1);
        }
 
 
        // 查询用户是否已购买该课程
        // 查询章节
        List<CourseChapter> page = courseChapterService.lambdaQuery()
                .eq(CourseChapter::getCourseId, id)
                .orderByDesc(CourseChapter::getSortNum)
                .list();
        for (CourseChapter courseChapter : page) {
            // 累加实际学习人数
            int a = 0;
            int b = 0;
            Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
            a+=data2;
            b+=courseChapter.getVirtualLearnedNum();
            courseChapter.setRealLearnedNum(a);
            courseChapter.setVirtualLearnedNum(b);
            LoginUser loginUser = tokenService.getLoginUser();
            if (loginUser!=null){
                Integer data1 = remoteAppUserService.getCourseChapterHistoryState(loginUser.getUserid(), courseChapter.getId()).getData();
                courseChapter.setIsOver(data1);
            }else{
                courseChapter.setIsOver(2);
            }
        }
        clientCourseVO.setList(page);
 
        // 查询推荐课程
        List<Course> list = courseService.lambdaQuery().eq(Course::getCateId, byId.getCateId())
                .eq(Course::getCourseType,1)
                .eq(Course::getListingStatus,1)
                .ne(Course::getId,id)
                .eq(Course::getRecommend, 1).list();
        List<Course> courses = new ArrayList<>();
        // 随机获取两个课程
        if (CollUtils.isNotEmpty(list)) {
            int size = list.size();
            int index = (int) (Math.random() * size);
            if (size >= 2){
                for (int i = 0; i < 2; i++) {
                    courses.add(list.get(i));
                }
            }else{
                courses.addAll(list);
            }
        }
        for (Course cours : courses) {
            List<AppUser> data3 = remoteAppUserService.getUserByCourseId(id).getData();
            cours.setCount(data3.size());
        }
 
        clientCourseVO.setList2(courses);
        if (byId.getChargeType() == 1){
            byId.setGeneralPrice(new BigDecimal("0"));
        }
        return R.ok(clientCourseVO);
    }
    /**
     * 课程详情
     *
     * @return 课程详情
     */
    @PostMapping("/getPayCourseInfoByIdShare")
    @ApiOperation(value = "根据id获取课程详情",tags = "分享H5")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程id", name = "id", required = true, dataType = "String"),
    })
    public R<ClientCourseVO> getPayCourseInfoByIdShare(@RequestParam(value = "id")Long id) {
 
        Course byId = courseService.getById(id);
        ClientCourseVO clientCourseVO = new ClientCourseVO();
        BeanUtils.copyProperties(byId, clientCourseVO);
        // 查询章节
        List<CourseChapter> page = courseChapterService.lambdaQuery()
                .eq(CourseChapter::getCourseId, id)
                .orderByDesc(CourseChapter::getSortNum)
                .list();
        for (CourseChapter courseChapter : page) {
            int size = courseLearningRecordService.lambdaQuery()
                    .eq(CourseLearningRecord::getChapterId, courseChapter.getId())
                    .list().size();
            courseChapter.setRealLearnedNum(size+courseChapter.getVirtualLearnedNum());
        }
        clientCourseVO.setList(page);
        clientCourseVO.setIsBuy(0);
        // 查询学习人数和头像列表
        List<AppUser> data = remoteAppUserService.getUserByCourseId(id).getData();
        if (data!=null){
            clientCourseVO.setCount(data.size());
            if (data.size()>=5){
                clientCourseVO.setHeaders(data.stream().limit(5).map(AppUser::getAvatar).collect(Collectors.toList()));
            }else{
                clientCourseVO.setHeaders(data.stream().map(AppUser::getAvatar).collect(Collectors.toList()));
            }
            List<Long> collect = data.stream().map(AppUser::getUserId).collect(Collectors.toList());
        }
        // 查询推荐课程
        List<Course> list = courseService.lambdaQuery().eq(Course::getCateId, byId.getCateId())
                .eq(Course::getCourseType,1)
                .eq(Course::getListingStatus,1)
                .ne(Course::getId,id)
                .eq(Course::getRecommend, 1).list();
        List<Course> courses = new ArrayList<>();
        // 随机获取两个课程
        if (CollUtils.isNotEmpty(list)) {
            int size = list.size();
            int index = (int) (Math.random() * size);
            if (size >= 2){
                for (int i = 0; i < 2; i++) {
                    courses.add(list.get(index));
                }
            }else{
                courses.add(list.get(index));
            }
        }
        for (Course cours : courses) {
            List<AppUser> data1 = remoteAppUserService.getUserByCourseId(id).getData();
            cours.setCount(data1.size());
        }
        clientCourseVO.setList2(courses);
        if (byId.getChargeType() == 1){
            byId.setGeneralPrice(new BigDecimal("0"));
        }
        return R.ok(clientCourseVO);
    }
 
    /**
     * 获取课程列表-分页
     *
     * @param courseTitle 课程标题
     * @param cateId      分类id
     * @param pageCurr    分页参数,当前页码
     * @param pageSize    分页参数,每页数量
     * @return 课程分页列表
     */
    @PostMapping("/getCoursePageList")
    @ApiOperation(value = "获取课程列表-分页")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程标题", name = "courseTitle", required = false, dataType = "String"),
            @ApiImplicitParam(value = "课程分类id", name = "cateId", required = false, dataType = "Long"),
            @ApiImplicitParam(value = "分页参数,当前页码", name = "pageCurr", required = true, dataType = "Integer"),
            @ApiImplicitParam(value = "分页参数,每页数量", name = "pageSize", required = true, dataType = "Integer")
    })
    public R<PageDTO<ClientCourseVO>> getCourseList(
            @RequestParam(defaultValue = "", value = "courseTitle", required = false) String courseTitle,
            @RequestParam(required = false) Long cateId,
            @RequestParam(value = "pageCurr", defaultValue = "1") Integer pageCurr,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageDTO<ClientCourseVO> coursePageList = courseService.getCoursePageList(courseTitle, cateId, pageCurr, pageSize);
 
        for (ClientCourseVO record : coursePageList.getList()) {
            int size1 = courseLearningRecordService.lambdaQuery().eq(CourseLearningRecord::getCourseId, record.getId())
                    .groupBy(CourseLearningRecord::getAppUserId).list().size();
            List<CourseChapter> list = courseChapterService.lambdaQuery()
                    .eq(CourseChapter::getCourseId, record.getId()).list();
            // 章节列表累加虚拟学习人数
            int temp = 0;
            int temp1 = 0;
            for (CourseChapter courseChapter : list) {
                temp+=courseChapter.getVirtualLearnedNum();
                Long data1 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                temp1+=data1;
            }
            record.setCount(temp1+temp);
        }
        return R.ok(coursePageList);
    }
    @PostMapping("/studyPageByChapterId")
    @ApiOperation(value = "课程学习页面")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "章节id", name = "chapterId", required = true, dataType = "Long"),
    })
    public R<List<CourseChapter>> studyPageByChapterId(@RequestParam(value = "chapterId")Long chapterId) {
 
        CourseChapter byId1 = courseChapterService.getById(chapterId);
        Course byId = courseService.getById(byId1.getCourseId());
        Long id = byId1.getCourseId();
        // 查询章节
        List<CourseChapter> page = courseChapterService.lambdaQuery()
                .eq(CourseChapter::getCourseId, id)
                .orderByDesc(CourseChapter::getSortNum)
                .list();
 
        for (CourseChapter courseChapter : page) {
            AppUserViewingHistory data = remoteAppUserService.getCourseStudyHistory(courseChapter.getId()).getData();
            if (data!=null){
                courseChapter.setMinuteLook(data.getMinuteLook());
                courseChapter.setSecondLook(data.getSecondLook());
                courseChapter.setIsOver(data.getIsOver());
            }
            int size = courseLearningRecordService
                    .lambdaQuery().eq(CourseLearningRecord::getChapterId, courseChapter.getId())
                    .list().size();
            courseChapter.setRealLearnedNum(size+courseChapter.getVirtualLearnedNum());
        }
        if (byId.getChargeType() == 1&&tokenService.getLoginUser()==null){
            return R.ok(page);
        }else{
            LoginUser loginUser = tokenService.getLoginUser();
            if (loginUser==null){
                return R.tokenError("登录失效");
            }
            Long userid = loginUser.getUserid();
            // 新增学习记录
            CourseLearningRecord one = courseLearningRecordService.lambdaQuery().eq(CourseLearningRecord::getAppUserId, userid)
                    .eq(CourseLearningRecord::getChapterId, chapterId).one();
            if (one==null){
                CourseLearningRecord courseLearningRecord = new CourseLearningRecord();
                courseLearningRecord.setAppUserId(userid);
                if (byId!=null){
                    courseLearningRecord.setCourseId(byId.getId());
                }
                courseLearningRecord.setChapterId(chapterId);
                courseLearningRecordService.save(courseLearningRecord);
            }
 
            return R.ok(page);
 
        }
 
    }
    @PostMapping("/confirmOrder")
    @ApiOperation(value = "确认订单页面")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程id", name = "courseId", required = true, dataType = "Long")
    })
    public R<Course> confirmOrder(@RequestParam(value = "courseId")Long courseId) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser==null){
            return R.tokenError("登录失效");
        }
        Long userId = loginUser.getUserid();
 
        Course byId = courseService.getById(courseId);
        AppUser data = remoteAppUserService.getAppUserById(userId + "").getData();
        byId.setBalance(data.getBalance());
        System.err.println("课程类型"+byId.getChargeType());
        if (byId.getChargeType() == 1){
            byId.setGeneralPrice(new BigDecimal("0"));
        }
        System.err.println("返回数据"+byId);
        return R.ok(byId);
    }
    @PostMapping("/successOrder")
    @ApiOperation(value = "支付成功页面")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程id", name = "courseId", required = true, dataType = "Long")
    })
    public R<List<Course>> successOrder(@RequestParam(value = "courseId")Long courseId) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser==null){
            return R.tokenError("登录失效");
        }
        Long userId = loginUser.getUserid();
        Course byId = courseService.getById(courseId);
        List<Course> list = courseService.lambdaQuery().eq(Course::getCateId, byId.getCateId())
                .eq(Course::getListingStatus,1)
                .ne(Course::getId,courseId)
                .eq(Course::getCourseType, 1).list();
        for (Course course : list) {
            List<AppUser> data = remoteAppUserService.getUserByCourseId(courseId).getData();
            List<CourseChapter> list1 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, course).list();
            int a = 0;
            int b = 0;
            for (CourseChapter courseChapter : list1) {
                a+= courseChapter.getVirtualLearnedNum();
                Long data1 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                b+=data1;
            }
            course.setCount(a+b);
            course.setRealLearnedNum(a+b);
        }
        List<Course> courses = new ArrayList<>();
 
        // 如果list集合数据大于2 随机获取两个返回
        if (CollUtils.isNotEmpty(list) && list.size() > 4) {
            int size = list.size();
            int index = (int) (Math.random() * size);
            for (int i = 0; i < 4; i++) {
                courses.add(list.get(index));
            }
            return R.ok(courses);
        }else {
            return R.ok(list);
        }
    }
    @GetMapping("/studyPage")
    @ApiOperation(value = "学习")
    public R<StudyPageVO> studyPage() {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser==null){
            return R.tokenError("登录失效");
        }
        Long userId = loginUser.getUserid();
        if(userId ==null || userId == 0)return R.tokenError("登录失效");
        StudyPageVO studyPageVO = new StudyPageVO();
        List<CourseVO> courseVOS = new ArrayList<>();
 
        PageDTO<AppUserCourse> data = remoteAppUserService.getPayCourse(1, 909999,userId+"").getData();
        List<AppUserCourse> list = data.getList();
        if (CollUtils.isNotEmpty(list)) {
            List<Long> courseIds = list.stream().map(AppUserCourse::getCourseId).collect(Collectors.toList());
            List<Course> page = courseService.lambdaQuery()
                    .in(Course::getId, courseIds)
                    .list();
            for (Course course : page) {
                CourseVO courseVO = new CourseVO();
                List<CourseChapter> list1 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, course.getId()).list();
                int a = 0;
                int b = 0;
                for (CourseChapter courseChapter : list1) {
                    a+= courseChapter.getVirtualLearnedNum();
                    Long data1 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                    b+=data1;
                }
                course.setCount(a+b);
                course.setRealLearnedNum(a+b);
                course.setVirtualLearnedNum(0);
                BeanUtils.copyProperties(course, courseVO);
                courseVOS.add(courseVO);
            }
        }
        List<Long> data1 = remoteAppUserService.getCourseHistoryByUserId(userId).getData();
        for (Long l : data1) {
            CourseChapter byId1 = courseChapterService.getById(l);
            Course byId = courseService.getById(byId1.getCourseId());
            if (byId!=null){
                CourseVO courseVO = new CourseVO();
                BeanUtils.copyProperties(byId, courseVO);
                List<CourseChapter> list1 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, byId1.getCourseId()).list();
                int a = 0;
                int b = 0;
                for (CourseChapter courseChapter : list1) {
                    a+= courseChapter.getVirtualLearnedNum();
                    Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                    b+=data2;
                }
                courseVO.setCount(a+b);
                courseVO.setRealLearnedNum(a+b);
                courseVO.setVirtualLearnedNum(0);
                courseVO.setId(byId.getId());
                courseVO.setCoverUrl(byId.getCoverUrl());
                courseVOS.add(courseVO);
            }
        }
        // 查询两个相同类型的线上免费课程
        List<Course> freeCourseList = courseService.lambdaQuery()
                .eq(Course::getCourseType, 1)
                .eq(Course::getChargeType, 1)
                .list();
        // 远程查询用户观看历史
        if (!data1.isEmpty()){
            // 随机获取两个
            if (CollUtils.isNotEmpty(freeCourseList) && freeCourseList.size() > 2) {
                List<Course> courses = new ArrayList<>();
                for (Course cours : freeCourseList) {
                    List<CourseChapter> list1 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, cours.getId()).list();
                    int a = 0;
                    int b = 0;
                    for (CourseChapter courseChapter : list1) {
                        a+= courseChapter.getVirtualLearnedNum();
                        Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                        b+=data2;
                    }
                    cours.setCount(a+b);
                    cours.setRealLearnedNum(a+b);
                    cours.setVirtualLearnedNum(0);
                }
                for (int i = 0; i < 2; i++) {
                    courses.add(freeCourseList.get(i));
                }
                studyPageVO.setFreeCourseList(courses);
            }else{
                for (Course cours : freeCourseList) {
                    List<CourseChapter> list1 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, cours.getId()).list();
                    int a = 0;
                    int b = 0;
                    for (CourseChapter courseChapter : list1) {
                        a+= courseChapter.getVirtualLearnedNum();
                        Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                        b+=data2;
                    }
                    cours.setCount(a+b);
                    cours.setRealLearnedNum(a+b);
                }
                studyPageVO.setFreeCourseList(freeCourseList);
            }
            for (Long l : data1) {
                CourseChapter byId1 = courseChapterService.getById(l);
                Course byId = courseService.getById(byId1.getCourseId());
                if (byId!=null){
                    CourseVO courseVO = new CourseVO();
                    BeanUtils.copyProperties(byId, courseVO);
                    List<CourseChapter> list1 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, byId1.getCourseId()).list();
                    int a = 0;
                    int b = 0;
                    for (CourseChapter courseChapter : list1) {
                        a+= courseChapter.getVirtualLearnedNum();
                        Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                        b+=data2;
                    }
                    courseVO.setCount(a+b);
                    courseVO.setRealLearnedNum(a+b);
                    courseVO.setVirtualLearnedNum(0);
                    courseVO.setId(byId.getId());
                    courseVO.setCoverUrl(byId.getCoverUrl());
                    courseVOS.add(courseVO);
                }
            }
            studyPageVO.setCourseList(courseVOS);
            return R.ok(studyPageVO);
        }else{
            List<Course> list1 = courseService.lambdaQuery()
                    .eq(Course::getChargeType, 1)
                    .eq(Course::getListingStatus, 1)
                    .list();
            if (list1.size()>=2){
                List<Course> courses = new ArrayList<>();
                courses.add(list1.get(0));
                courses.add(list1.get(1));
                for (Course cours : courses) {
                    List<CourseChapter> list3 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, cours.getId()).list();
                    int a = 0;
                    int b = 0;
                    for (CourseChapter courseChapter : list3) {
                        a+= courseChapter.getVirtualLearnedNum();
                        Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                        b+=data2;
                    }
                    cours.setCount(a+b);
                    cours.setRealLearnedNum(a+b);
                }
                studyPageVO.setFreeCourseList(courses);
            }else if (list1.size()==1){
                List<Course> courses = new ArrayList<>();
                courses.add(list1.get(0));
                for (Course course : freeCourseList) {
                    if (!course.getId().equals(list1.get(0).getId())){
                        courses.add(course);
                        break;
                    }
                }
                for (Course cours : courses) {
                    List<CourseChapter> list3 = courseChapterService.lambdaQuery().eq(CourseChapter::getCourseId, cours.getId()).list();
                    int a = 0;
                    int b = 0;
                    for (CourseChapter courseChapter : list3) {
                        a+= courseChapter.getVirtualLearnedNum();
                        Long data2 = remoteAppUserService.getCourseChapterHistoryCount(courseChapter.getId()).getData();
                        b+=data2;
                    }
                    cours.setCount(a+b);
                    cours.setRealLearnedNum(a+b);
                }
                studyPageVO.setFreeCourseList(courses);
            }
            studyPageVO.setCourseList(courseVOS);
            return R.ok(studyPageVO);
        }
 
    }
}