zjk
2026-09-29 54dcf0a82e7490fa58b1c056d5c0b9cb739c2931
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
package com.tcm.training.admin.live.service;
 
import cn.idev.excel.FastExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tcm.training.admin.app.notice.service.AppSystemNoticeDispatchCommand;
import com.tcm.training.admin.app.notice.service.AppSystemNoticeDispatchService;
import com.tcm.training.admin.app.notice.service.AppSystemNoticeType;
import com.tcm.training.admin.common.Jsons;
import com.tcm.training.admin.common.PageResponse;
import com.tcm.training.admin.live.dto.HealthCourseSaveRequest;
import com.tcm.training.admin.live.dto.HealthCourseStatusRequest;
import com.tcm.training.admin.live.dto.HealthCourseVideoSaveRequest;
import com.tcm.training.admin.live.entity.Expert;
import com.tcm.training.admin.live.entity.CoursePurchaseOrder;
import com.tcm.training.admin.live.entity.HealthCourse;
import com.tcm.training.admin.live.entity.HealthCourseMemberJoinRecord;
import com.tcm.training.admin.live.entity.HealthCourseVideo;
import com.tcm.training.admin.live.entity.LiveCourseCategory;
import com.tcm.training.admin.live.excel.HealthCourseExportRow;
import com.tcm.training.admin.live.excel.HealthCourseVideoImportRow;
import com.tcm.training.admin.live.mapper.ExpertMapper;
import com.tcm.training.admin.live.mapper.HealthCourseMapper;
import com.tcm.training.admin.live.mapper.CoursePurchaseOrderMapper;
import com.tcm.training.admin.live.mapper.HealthCourseMemberJoinRecordMapper;
import com.tcm.training.admin.live.mapper.HealthCourseVideoMapper;
import com.tcm.training.admin.live.mapper.LiveCourseCategoryMapper;
import com.tcm.training.admin.live.vo.ExpertVO;
import com.tcm.training.admin.live.vo.HealthCourseDetailRow;
import com.tcm.training.admin.live.vo.HealthCourseDetailVO;
import com.tcm.training.admin.live.vo.HealthCourseListItemVO;
import com.tcm.training.admin.live.vo.HealthCourseListRow;
import com.tcm.training.admin.live.vo.HealthCourseOptionVO;
import com.tcm.training.admin.live.vo.HealthCourseStatusVO;
import com.tcm.training.admin.live.vo.HealthCourseVideoDetailVO;
import com.tcm.training.admin.live.vo.HealthCourseVideoItemVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
@Service
public class HealthCourseAppService {
 
    private final HealthCourseMapper healthCourseMapper;
    private final HealthCourseVideoMapper healthCourseVideoMapper;
    private final LiveCourseCategoryMapper liveCourseCategoryMapper;
    private final ExpertMapper expertMapper;
    private final CoursePurchaseOrderMapper coursePurchaseOrderMapper;
    private final HealthCourseMemberJoinRecordMapper healthCourseMemberJoinRecordMapper;
    private final AppSystemNoticeDispatchService appSystemNoticeDispatchService;
 
    public HealthCourseAppService(HealthCourseMapper healthCourseMapper,
                                  HealthCourseVideoMapper healthCourseVideoMapper,
                                  LiveCourseCategoryMapper liveCourseCategoryMapper,
                                  ExpertMapper expertMapper,
                                  CoursePurchaseOrderMapper coursePurchaseOrderMapper,
                                  HealthCourseMemberJoinRecordMapper healthCourseMemberJoinRecordMapper,
                                  AppSystemNoticeDispatchService appSystemNoticeDispatchService) {
        this.healthCourseMapper = healthCourseMapper;
        this.healthCourseVideoMapper = healthCourseVideoMapper;
        this.liveCourseCategoryMapper = liveCourseCategoryMapper;
        this.expertMapper = expertMapper;
        this.coursePurchaseOrderMapper = coursePurchaseOrderMapper;
        this.healthCourseMemberJoinRecordMapper = healthCourseMemberJoinRecordMapper;
        this.appSystemNoticeDispatchService = appSystemNoticeDispatchService;
    }
 
    public PageResponse<HealthCourseListItemVO> page(int page,
                                                     int pageSize,
                                                     String keyword,
                                                     Long levelCategoryId,
                                                     Long difficultyCategoryId,
                                                     Integer status) {
        IPage<HealthCourseListRow> result = healthCourseMapper.selectCoursePage(
                new Page<HealthCourseListRow>(page, pageSize),
                trimToNull(keyword),
                levelCategoryId,
                difficultyCategoryId,
                status
        );
        List<HealthCourseListItemVO> list = new ArrayList<HealthCourseListItemVO>();
        for (HealthCourseListRow row : result.getRecords()) {
            list.add(toCourseListItem(row));
        }
        return PageResponse.of(list, result.getTotal(), result.getCurrent(), result.getSize());
    }
 
    public HealthCourseDetailVO detail(Long id) {
        HealthCourseDetailRow row = healthCourseMapper.selectCourseDetail(id);
        if (row == null) {
            throw new IllegalArgumentException("课程不存在");
        }
        return toCourseDetail(row);
    }
 
    @Transactional
    public HealthCourseDetailVO create(HealthCourseSaveRequest req) {
        validateCategories(req.getLevelCategoryId(), req.getDifficultyCategoryId());
        validateExpert(req.getExpertId());
 
        HealthCourse course = new HealthCourse();
        fillCourse(course, req);
        course.setRealSalesCount(0);
        course.setLearnUserCount(0);
        course.setFavoriteCount(0);
        course.setTotalDurationSeconds(0);
        course.setVideoCount(0);
        course.setDeleted(0);
        healthCourseMapper.insert(course);
        return detail(course.getId());
    }
 
    @Transactional
    public HealthCourseDetailVO update(Long id, HealthCourseSaveRequest req) {
        validateCategories(req.getLevelCategoryId(), req.getDifficultyCategoryId());
        validateExpert(req.getExpertId());
        HealthCourse course = requireCourse(id);
        fillCourse(course, req);
        healthCourseMapper.updateById(course);
        return detail(id);
    }
 
    @Transactional
    public HealthCourseStatusVO patchStatus(Long id, HealthCourseStatusRequest req) {
        HealthCourse course = requireCourse(id);
        course.setStatus(req.getStatus());
        healthCourseMapper.updateById(course);
        return new HealthCourseStatusVO(id, req.getStatus());
    }
 
    @Transactional
    public void delete(Long id) {
        requireCourse(id);
        List<HealthCourseVideo> videos = healthCourseVideoMapper.selectList(new LambdaQueryWrapper<HealthCourseVideo>()
                .eq(HealthCourseVideo::getCourseId, id)
                .eq(HealthCourseVideo::getDeleted, 0));
        for (HealthCourseVideo video : videos) {
            healthCourseVideoMapper.deleteById(video.getId());
        }
        healthCourseMapper.deleteById(id);
    }
 
    public void export(HttpServletResponse response,
                       String keyword,
                       Long levelCategoryId,
                       Long difficultyCategoryId,
                       Integer status) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode("养生课程", "UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
 
        List<HealthCourseListRow> rows = healthCourseMapper.selectCourseList(
                trimToNull(keyword),
                levelCategoryId,
                difficultyCategoryId,
                status
        );
        List<HealthCourseExportRow> exports = new ArrayList<HealthCourseExportRow>();
        for (int i = 0; i < rows.size(); i++) {
            HealthCourseListRow row = rows.get(i);
            HealthCourseExportRow export = new HealthCourseExportRow();
            export.setSerialNo(i + 1);
            export.setTitle(defaultText(row.getTitle()));
            export.setLevelName(defaultText(row.getLevelName()));
            export.setDifficultyName(defaultText(row.getDifficultyName()));
            export.setSalePrice(row.getSalePrice() == null ? BigDecimal.ZERO : row.getSalePrice());
            export.setSalesCount(resolveSalesCount(row.getBaseSalesCount(), row.getRealSalesCount()));
            export.setStudyingCount(defaultNumber(row.getStudyingCount()));
            export.setTotalDuration(formatDuration(defaultNumber(row.getTotalDurationSeconds())));
            export.setFavoriteCount(defaultNumber(row.getFavoriteCount()));
            export.setExpertName(defaultText(row.getExpertName()));
            export.setStatusText(statusText(row.getStatus()));
            exports.add(export);
        }
        FastExcel.write(response.getOutputStream(), HealthCourseExportRow.class)
                .sheet("养生课程")
                .doWrite(exports);
    }
 
    public List<HealthCourseOptionVO> options(String keyword) {
        List<HealthCourse> courses = healthCourseMapper.selectList(new LambdaQueryWrapper<HealthCourse>()
                .eq(HealthCourse::getDeleted, 0)
                .like(keyword != null && !keyword.trim().isEmpty(), HealthCourse::getTitle, keyword == null ? null : keyword.trim())
                .orderByAsc(HealthCourse::getSort)
                .orderByDesc(HealthCourse::getId));
        List<HealthCourseOptionVO> list = new ArrayList<HealthCourseOptionVO>();
        for (HealthCourse course : courses) {
            list.add(new HealthCourseOptionVO(course.getId(), course.getTitle()));
        }
        return list;
    }
 
    public PageResponse<HealthCourseVideoItemVO> pageVideos(Long courseId,
                                                            int page,
                                                            int pageSize,
                                                            String chapterName,
                                                            Integer priceType) {
        requireCourse(courseId);
        LambdaQueryWrapper<HealthCourseVideo> qw = new LambdaQueryWrapper<HealthCourseVideo>()
                .eq(HealthCourseVideo::getCourseId, courseId)
                .eq(HealthCourseVideo::getDeleted, 0)
                .orderByAsc(HealthCourseVideo::getSort)
                .orderByAsc(HealthCourseVideo::getId);
        if (chapterName != null && !chapterName.trim().isEmpty()) {
            qw.like(HealthCourseVideo::getChapterName, chapterName.trim());
        }
        if (priceType != null) {
            if (priceType == 0) {
                qw.eq(HealthCourseVideo::getSalePrice, BigDecimal.ZERO);
            } else if (priceType == 1) {
                qw.gt(HealthCourseVideo::getSalePrice, BigDecimal.ZERO);
            }
        }
        IPage<HealthCourseVideo> result = healthCourseVideoMapper.selectPage(new Page<HealthCourseVideo>(page, pageSize), qw);
        List<HealthCourseVideoItemVO> list = new ArrayList<HealthCourseVideoItemVO>();
        for (HealthCourseVideo item : result.getRecords()) {
            list.add(toVideoItem(item));
        }
        return PageResponse.of(list, result.getTotal(), result.getCurrent(), result.getSize());
    }
 
    public PageResponse<HealthCourseVideoItemVO> pageVideoResources(int page,
                                                                    int pageSize,
                                                                    String courseKeyword,
                                                                    Long courseId,
                                                                    Integer courseType,
                                                                    String chapterName,
                                                                    Integer priceType,
                                                                    Integer status) {
        List<Long> matchedCourseIds = resolveMatchedCourseIds(courseKeyword, courseId);
        if (matchedCourseIds.isEmpty()) {
            return PageResponse.of(Collections.<HealthCourseVideoItemVO>emptyList(), 0, page, pageSize);
        }
        LambdaQueryWrapper<HealthCourseVideo> qw = new LambdaQueryWrapper<HealthCourseVideo>()
                .in(HealthCourseVideo::getCourseId, matchedCourseIds)
                .eq(HealthCourseVideo::getDeleted, 0)
                .eq(courseType != null, HealthCourseVideo::getCourseType, courseType)
                .eq(status != null, HealthCourseVideo::getStatus, status)
                .orderByAsc(HealthCourseVideo::getSort)
                .orderByDesc(HealthCourseVideo::getId);
        if (chapterName != null && !chapterName.trim().isEmpty()) {
            qw.like(HealthCourseVideo::getChapterName, chapterName.trim());
        }
        if (priceType != null) {
            if (priceType == 0) {
                qw.eq(HealthCourseVideo::getSalePrice, BigDecimal.ZERO);
            } else if (priceType == 1) {
                qw.gt(HealthCourseVideo::getSalePrice, BigDecimal.ZERO);
            }
        }
        IPage<HealthCourseVideo> result = healthCourseVideoMapper.selectPage(new Page<HealthCourseVideo>(page, pageSize), qw);
        Map<Long, String> courseTitleMap = resolveCourseTitleMap(extractCourseIds(result.getRecords()));
        List<HealthCourseVideoItemVO> list = new ArrayList<HealthCourseVideoItemVO>();
        for (HealthCourseVideo item : result.getRecords()) {
            list.add(toVideoItem(item, courseTitleMap.get(item.getCourseId())));
        }
        return PageResponse.of(list, result.getTotal(), result.getCurrent(), result.getSize());
    }
 
    public HealthCourseVideoDetailVO detailVideo(Long courseId, Long videoId) {
        return toVideoDetail(requireVideo(courseId, videoId));
    }
 
    @Transactional
    public HealthCourseVideoDetailVO createVideo(Long courseId, HealthCourseVideoSaveRequest req) {
        req.setCourseId(courseId);
        return createVideoResource(req);
    }
 
    @Transactional
    public HealthCourseVideoDetailVO updateVideo(Long courseId, Long videoId, HealthCourseVideoSaveRequest req) {
        req.setCourseId(courseId);
        return updateVideoResource(videoId, req);
    }
 
    @Transactional
    public void deleteVideo(Long courseId, Long videoId) {
        requireVideo(courseId, videoId);
        healthCourseVideoMapper.deleteById(videoId);
        refreshCourseStats(courseId);
    }
 
    public HealthCourseVideoDetailVO detailVideoResource(Long id) {
        HealthCourseVideo video = requireVideoById(id);
        return toVideoDetail(video, requireCourse(video.getCourseId()).getTitle());
    }
 
    @Transactional
    public HealthCourseVideoDetailVO createVideoResource(HealthCourseVideoSaveRequest req) {
        Long courseId = requireVideoCourseId(req.getCourseId());
        validateVideo(req);
        HealthCourseVideo next = new HealthCourseVideo();
        next.setCourseId(courseId);
        fillVideo(next, req);
        next.setSort(resolveNextVideoSort(courseId));
        next.setDeleted(0);
        healthCourseVideoMapper.insert(next);
        refreshCourseStats(courseId);
        dispatchCourseUpdateNotice(courseId, next);
        return detailVideoResource(next.getId());
    }
 
    @Transactional
    public HealthCourseVideoDetailVO updateVideoResource(Long id, HealthCourseVideoSaveRequest req) {
        HealthCourseVideo video = requireVideoById(id);
        Long targetCourseId = req.getCourseId() == null ? video.getCourseId() : requireVideoCourseId(req.getCourseId());
        req.setCourseId(targetCourseId);
        validateVideo(req);
        Long oldCourseId = video.getCourseId();
        video.setCourseId(targetCourseId);
        fillVideo(video, req);
        healthCourseVideoMapper.updateById(video);
        refreshCourseStats(targetCourseId);
        if (!oldCourseId.equals(targetCourseId)) {
            refreshCourseStats(oldCourseId);
        }
        return detailVideoResource(id);
    }
 
    @Transactional
    public void deleteVideoResource(Long id) {
        HealthCourseVideo video = requireVideoById(id);
        healthCourseVideoMapper.deleteById(id);
        refreshCourseStats(video.getCourseId());
    }
 
    public void downloadVideoResourceTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode("视频与课程资源导入模板", "UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
        List<HealthCourseVideoImportRow> rows = new ArrayList<HealthCourseVideoImportRow>();
        HealthCourseVideoImportRow sample = new HealthCourseVideoImportRow();
        sample.setCourseId(1L);
        sample.setCourseTitle("中医针灸资格证");
        sample.setCourseTypeText(courseTypeText(HealthCourseVideo.COURSE_TYPE_HEALTH));
        sample.setChapterName("方剂学");
        sample.setSalePrice(BigDecimal.ZERO);
        sample.setDurationSeconds(238);
        sample.setVideoUrl("https://example.com/video.mp4");
        sample.setStatusText(statusText(1));
        rows.add(sample);
        FastExcel.write(response.getOutputStream(), HealthCourseVideoImportRow.class)
                .sheet("视频资源导入模板")
                .doWrite(rows);
    }
 
    @Transactional
    public void importVideoResources(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("请选择导入文件");
        }
        List<HealthCourseVideoImportRow> rows = FastExcel.read(file.getInputStream())
                .head(HealthCourseVideoImportRow.class)
                .sheet()
                .doReadSync();
        if (rows == null || rows.isEmpty()) {
            throw new IllegalArgumentException("导入文件不能为空");
        }
        Set<Long> touchedCourseIds = new LinkedHashSet<Long>();
        int rowNum = 1;
        for (HealthCourseVideoImportRow row : rows) {
            rowNum++;
            if (row == null || isImportRowEmpty(row)) {
                continue;
            }
            validateImportRow(row, rowNum);
            HealthCourse course = requireCourse(row.getCourseId());
            HealthCourseVideo video = new HealthCourseVideo();
            video.setCourseId(course.getId());
            video.setCourseType(HealthCourseVideo.COURSE_TYPE_HEALTH);
            video.setChapterName(row.getChapterName().trim());
            video.setVideoSourceType(HealthCourseVideo.VIDEO_SOURCE_URL);
            video.setVideoUrl(row.getVideoUrl().trim());
            video.setVideoFileName(null);
            video.setDurationSeconds(row.getDurationSeconds());
            video.setSalePrice(row.getSalePrice() == null ? BigDecimal.ZERO : row.getSalePrice());
            video.setSort(resolveNextVideoSort(course.getId()));
            video.setStatus(parseStatusText(row.getStatusText()));
            video.setDeleted(0);
            healthCourseVideoMapper.insert(video);
            touchedCourseIds.add(course.getId());
            dispatchCourseUpdateNotice(course.getId(), video);
        }
        if (touchedCourseIds.isEmpty()) {
            throw new IllegalArgumentException("导入文件没有可用数据");
        }
        for (Long courseId : touchedCourseIds) {
            refreshCourseStats(courseId);
        }
    }
 
    private void fillCourse(HealthCourse course, HealthCourseSaveRequest req) {
        course.setTitle(req.getTitle().trim());
        course.setLevelCategoryId(req.getLevelCategoryId());
        course.setDifficultyCategoryId(req.getDifficultyCategoryId());
        course.setExpertId(req.getExpertId());
        course.setSalePrice(req.getSalePrice());
        course.setSummary(trimToNull(req.getSummary()));
        course.setTargetUsers(trimToNull(req.getTargetUsers()));
        course.setCoverImg(req.getCoverImg().trim());
        course.setBannerImgs(req.getBannerImgs());
        course.setContent(req.getContent().trim());
        course.setBaseSalesCount(req.getBaseSalesCount() == null ? 0 : req.getBaseSalesCount());
        // 正在学习人数由后台表单配置初始值,App 端每次进入课程详情会在此基础上自增
        course.setStudyingCount(req.getStudyingCount() == null ? 0 : req.getStudyingCount());
        course.setStatus(req.getStatus());
        course.setIsHomeRecommend(req.getIsHomeRecommend());
        course.setSort(defaultNumber(req.getSort()));
    }
 
    private void fillVideo(HealthCourseVideo video, HealthCourseVideoSaveRequest req) {
        video.setCourseType(resolveCourseType(req.getCourseType()));
        video.setChapterName(req.getChapterName().trim());
        video.setVideoSourceType(req.getVideoSourceType());
        video.setVideoUrl(req.getVideoUrl().trim());
        video.setVideoFileName(trimToNull(req.getVideoFileName()));
        video.setDurationSeconds(req.getDurationSeconds());
        video.setSalePrice(req.getSalePrice());
        video.setStatus(resolveVideoStatus(req.getStatus()));
    }
 
    private void validateCategories(Long levelCategoryId, Long difficultyCategoryId) {
        LiveCourseCategory level = requireCategory(levelCategoryId, LiveCourseCategoryAppService.TYPE_LEVEL, "养生主题");
        LiveCourseCategory difficulty = requireCategory(difficultyCategoryId, LiveCourseCategoryAppService.TYPE_DIFFICULTY, "难度");
        if (level == null || difficulty == null) {
            throw new IllegalArgumentException("分类不存在");
        }
    }
 
    private LiveCourseCategory requireCategory(Long id, String type, String label) {
        LiveCourseCategory category = liveCourseCategoryMapper.selectOne(new LambdaQueryWrapper<LiveCourseCategory>()
                .eq(LiveCourseCategory::getId, id)
                .eq(LiveCourseCategory::getType, type)
                .eq(LiveCourseCategory::getDeleted, 0)
                .last("limit 1"));
        if (category == null) {
            throw new IllegalArgumentException(label + "不存在");
        }
        return category;
    }
 
    private void validateExpert(Long expertId) {
        Expert expert = expertMapper.selectOne(new LambdaQueryWrapper<Expert>()
                .eq(Expert::getId, expertId)
                .eq(Expert::getDeleted, 0)
                .last("limit 1"));
        if (expert == null) {
            throw new IllegalArgumentException("授课专家不存在");
        }
        if (expert.getStatus() == null || expert.getStatus() != 1) {
            throw new IllegalArgumentException("授课专家已禁用");
        }
    }
 
    private void validateVideo(HealthCourseVideoSaveRequest req) {
        Integer courseType = resolveCourseType(req.getCourseType());
        if (courseType != HealthCourseVideo.COURSE_TYPE_HEALTH) {
            throw new IllegalArgumentException("课程类型不合法");
        }
        if (req.getCourseId() == null) {
            throw new IllegalArgumentException("请选择关联课程");
        }
        if (req.getVideoSourceType() == null
                || (req.getVideoSourceType() != HealthCourseVideo.VIDEO_SOURCE_URL
                && req.getVideoSourceType() != HealthCourseVideo.VIDEO_SOURCE_UPLOAD)) {
            throw new IllegalArgumentException("视频来源不合法");
        }
        if (req.getVideoUrl() == null || req.getVideoUrl().trim().isEmpty()) {
            throw new IllegalArgumentException("请输入视频地址");
        }
        if (req.getSalePrice() != null && req.getSalePrice().compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("售价不能小于0");
        }
    }
 
    private Integer resolveVideoStatus(Integer status) {
        return status == null ? 1 : status;
    }
 
    private int resolveNextVideoSort(Long courseId) {
        HealthCourseVideo latest = healthCourseVideoMapper.selectOne(new LambdaQueryWrapper<HealthCourseVideo>()
                .eq(HealthCourseVideo::getCourseId, courseId)
                .eq(HealthCourseVideo::getDeleted, 0)
                .orderByDesc(HealthCourseVideo::getSort)
                .last("limit 1"));
        if (latest == null || latest.getSort() == null) {
            return 10;
        }
        return latest.getSort() + 10;
    }
 
    private void refreshCourseStats(Long courseId) {
        HealthCourse course = requireCourse(courseId);
        List<HealthCourseVideo> videos = healthCourseVideoMapper.selectList(new LambdaQueryWrapper<HealthCourseVideo>()
                .eq(HealthCourseVideo::getCourseId, courseId)
                .eq(HealthCourseVideo::getDeleted, 0));
        int totalDurationSeconds = 0;
        for (HealthCourseVideo video : videos) {
            totalDurationSeconds += video.getDurationSeconds() == null ? 0 : video.getDurationSeconds();
        }
        course.setVideoCount(videos.size());
        course.setTotalDurationSeconds(totalDurationSeconds);
        healthCourseMapper.updateById(course);
    }
 
    /**
     * 在课程新增章节后通知已购课或已加入学习的用户。
     */
    private void dispatchCourseUpdateNotice(Long courseId, HealthCourseVideo video) {
        if (courseId == null || video == null || video.getId() == null) {
            return;
        }
        HealthCourse course = requireCourse(courseId);
        Set<Long> appUserIds = new LinkedHashSet<Long>();
        List<CoursePurchaseOrder> orders = coursePurchaseOrderMapper.selectList(new LambdaQueryWrapper<CoursePurchaseOrder>()
                .eq(CoursePurchaseOrder::getDeleted, 0)
                .eq(CoursePurchaseOrder::getStatus, "PAID")
                .eq(CoursePurchaseOrder::getCourseId, courseId));
        for (CoursePurchaseOrder order : orders) {
            if (order.getAppUserId() != null) {
                appUserIds.add(order.getAppUserId());
            }
        }
        List<HealthCourseMemberJoinRecord> joinRecords = healthCourseMemberJoinRecordMapper.selectList(new LambdaQueryWrapper<HealthCourseMemberJoinRecord>()
                .eq(HealthCourseMemberJoinRecord::getDeleted, 0)
                .eq(HealthCourseMemberJoinRecord::getCourseId, courseId));
        for (HealthCourseMemberJoinRecord joinRecord : joinRecords) {
            if (joinRecord.getAppUserId() != null) {
                appUserIds.add(joinRecord.getAppUserId());
            }
        }
        for (Long appUserId : appUserIds) {
            AppSystemNoticeDispatchCommand command = new AppSystemNoticeDispatchCommand();
            command.setAppUserId(appUserId);
            command.setNoticeTypeCode(AppSystemNoticeType.COURSE_UPDATE_NOTICE);
            command.setTitle("课程更新通知");
            command.setContent(course.getTitle() + " 已更新新章节");
            // 使用章节主键作为引用,保证同一章节对同一用户只发一次。
            command.setReferenceType("HEALTH_COURSE_VIDEO");
            command.setReferenceId(video.getId());
            command.setRequireUserSetting(Boolean.TRUE);
            Map<String, String> payload = new LinkedHashMap<String, String>();
            payload.put("courseId", String.valueOf(courseId));
            payload.put("courseTitle", course.getTitle());
            payload.put("videoId", String.valueOf(video.getId()));
            payload.put("chapterName", defaultText(video.getChapterName()));
            command.setPayload(payload);
            appSystemNoticeDispatchService.createAndPush(command);
        }
    }
 
    private HealthCourse requireCourse(Long id) {
        HealthCourse course = healthCourseMapper.selectById(id);
        if (course == null) {
            throw new IllegalArgumentException("课程不存在");
        }
        return course;
    }
 
    private HealthCourseVideo requireVideo(Long courseId, Long videoId) {
        requireCourse(courseId);
        HealthCourseVideo video = requireVideoById(videoId);
        if (!courseId.equals(video.getCourseId())) {
            throw new IllegalArgumentException("视频课程不属于当前课程");
        }
        return video;
    }
 
    private HealthCourseListItemVO toCourseListItem(HealthCourseListRow row) {
        HealthCourseListItemVO vo = new HealthCourseListItemVO();
        vo.setId(row.getId());
        vo.setTitle(row.getTitle());
        vo.setLevelName(row.getLevelName());
        vo.setDifficultyName(row.getDifficultyName());
        vo.setSalePrice(row.getSalePrice() == null ? BigDecimal.ZERO : row.getSalePrice());
        vo.setSalesCount(resolveSalesCount(row.getBaseSalesCount(), row.getRealSalesCount()));
        vo.setLearnUserCount(defaultNumber(row.getLearnUserCount()));
        vo.setStudyingCount(defaultNumber(row.getStudyingCount()));
        vo.setTotalDurationSeconds(defaultNumber(row.getTotalDurationSeconds()));
        vo.setFavoriteCount(defaultNumber(row.getFavoriteCount()));
        vo.setExpert(new ExpertVO(row.getExpertId(), row.getExpertName(), row.getExpertAvatar()));
        vo.setCoverImg(row.getCoverImg());
        vo.setStatus(row.getStatus());
        vo.setIsHomeRecommend(row.getIsHomeRecommend());
        vo.setSort(defaultNumber(row.getSort()));
        vo.setCreatedAt(row.getCreatedAt());
        return vo;
    }
 
    private HealthCourseDetailVO toCourseDetail(HealthCourseDetailRow row) {
        HealthCourseDetailVO vo = new HealthCourseDetailVO();
        vo.setId(row.getId());
        vo.setTitle(row.getTitle());
        vo.setLevelCategoryId(row.getLevelCategoryId());
        vo.setLevelName(row.getLevelName());
        vo.setDifficultyCategoryId(row.getDifficultyCategoryId());
        vo.setDifficultyName(row.getDifficultyName());
        vo.setExpert(new ExpertVO(row.getExpertId(), row.getExpertName(), row.getExpertAvatar()));
        vo.setSalePrice(row.getSalePrice() == null ? BigDecimal.ZERO : row.getSalePrice());
        vo.setSummary(row.getSummary());
        vo.setTargetUsers(row.getTargetUsers());
        vo.setCoverImg(row.getCoverImg());
        vo.setBannerImgs(Jsons.parseStringList(row.getBannerImgs()));
        vo.setContent(row.getContent());
        vo.setBaseSalesCount(defaultNumber(row.getBaseSalesCount()));
        vo.setRealSalesCount(defaultNumber(row.getRealSalesCount()));
        vo.setSalesCount(resolveSalesCount(row.getBaseSalesCount(), row.getRealSalesCount()));
        vo.setLearnUserCount(defaultNumber(row.getLearnUserCount()));
        vo.setStudyingCount(defaultNumber(row.getStudyingCount()));
        vo.setFavoriteCount(defaultNumber(row.getFavoriteCount()));
        vo.setTotalDurationSeconds(defaultNumber(row.getTotalDurationSeconds()));
        vo.setVideoCount(defaultNumber(row.getVideoCount()));
        vo.setStatus(row.getStatus());
        vo.setIsHomeRecommend(row.getIsHomeRecommend());
        vo.setSort(row.getSort());
        vo.setCreatedAt(row.getCreatedAt());
        vo.setUpdatedAt(row.getUpdatedAt());
        return vo;
    }
 
    private HealthCourseVideoItemVO toVideoItem(HealthCourseVideo item) {
        return toVideoItem(item, null);
    }
 
    private HealthCourseVideoItemVO toVideoItem(HealthCourseVideo item, String courseTitle) {
        HealthCourseVideoItemVO vo = new HealthCourseVideoItemVO();
        vo.setId(item.getId());
        vo.setCourseType(resolveCourseType(item.getCourseType()));
        vo.setCourseTypeText(courseTypeText(item.getCourseType()));
        vo.setCourseId(item.getCourseId());
        vo.setCourseTitle(defaultText(courseTitle));
        vo.setChapterName(item.getChapterName());
        vo.setVideoSourceType(item.getVideoSourceType());
        vo.setVideoUrl(item.getVideoUrl());
        vo.setVideoFileName(item.getVideoFileName());
        vo.setDurationSeconds(item.getDurationSeconds());
        vo.setDurationText(formatDuration(defaultNumber(item.getDurationSeconds())));
        vo.setSalePrice(item.getSalePrice() == null ? BigDecimal.ZERO : item.getSalePrice());
        vo.setWatchCount(0);
        vo.setSort(item.getSort());
        vo.setStatus(item.getStatus());
        vo.setStatusText(statusText(item.getStatus()));
        vo.setCreatedAt(item.getCreatedAt());
        return vo;
    }
 
    private HealthCourseVideoDetailVO toVideoDetail(HealthCourseVideo item) {
        return toVideoDetail(item, null);
    }
 
    private HealthCourseVideoDetailVO toVideoDetail(HealthCourseVideo item, String courseTitle) {
        HealthCourseVideoDetailVO vo = new HealthCourseVideoDetailVO();
        vo.setId(item.getId());
        vo.setCourseType(resolveCourseType(item.getCourseType()));
        vo.setCourseTypeText(courseTypeText(item.getCourseType()));
        vo.setCourseId(item.getCourseId());
        vo.setCourseTitle(defaultText(courseTitle));
        vo.setChapterName(item.getChapterName());
        vo.setVideoSourceType(item.getVideoSourceType());
        vo.setVideoUrl(item.getVideoUrl());
        vo.setVideoFileName(item.getVideoFileName());
        vo.setDurationSeconds(item.getDurationSeconds());
        vo.setSalePrice(item.getSalePrice() == null ? BigDecimal.ZERO : item.getSalePrice());
        vo.setWatchCount(0);
        vo.setSort(item.getSort());
        vo.setStatus(item.getStatus());
        vo.setCreatedAt(item.getCreatedAt());
        vo.setUpdatedAt(item.getUpdatedAt());
        return vo;
    }
 
    private Integer resolveSalesCount(Integer baseSalesCount, Integer realSalesCount) {
        return defaultNumber(baseSalesCount) + defaultNumber(realSalesCount);
    }
 
    private Integer defaultNumber(Integer value) {
        return value == null ? 0 : value;
    }
 
    private String formatDuration(Integer seconds) {
        int totalSeconds = seconds == null ? 0 : seconds;
        int minutes = totalSeconds / 60;
        int remainSeconds = totalSeconds % 60;
        return minutes + ":" + String.format("%02d", remainSeconds);
    }
 
    private String statusText(Integer status) {
        return status != null && status == 1 ? "启用" : "禁用";
    }
 
    private String courseTypeText(Integer courseType) {
        return resolveCourseType(courseType) == HealthCourseVideo.COURSE_TYPE_HEALTH ? "养生课程" : "-";
    }
 
    private String defaultText(String text) {
        return text == null || text.trim().isEmpty() ? "-" : text;
    }
 
    private String trimToNull(String text) {
        if (text == null) {
            return null;
        }
        String trimmed = text.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
 
    private Integer resolveCourseType(Integer courseType) {
        return courseType == null ? HealthCourseVideo.COURSE_TYPE_HEALTH : courseType;
    }
 
    private Long requireVideoCourseId(Long courseId) {
        return requireCourse(courseId).getId();
    }
 
    private HealthCourseVideo requireVideoById(Long id) {
        HealthCourseVideo video = healthCourseVideoMapper.selectById(id);
        if (video == null) {
            throw new IllegalArgumentException("视频课程不存在");
        }
        return video;
    }
 
    private List<Long> resolveMatchedCourseIds(String courseKeyword, Long courseId) {
        if (courseId != null) {
            return Collections.singletonList(requireCourse(courseId).getId());
        }
        List<HealthCourse> courses = healthCourseMapper.selectList(new LambdaQueryWrapper<HealthCourse>()
                .eq(HealthCourse::getDeleted, 0)
                .like(courseKeyword != null && !courseKeyword.trim().isEmpty(), HealthCourse::getTitle, courseKeyword == null ? null : courseKeyword.trim()));
        if (courses.isEmpty()) {
            return Collections.emptyList();
        }
        List<Long> ids = new ArrayList<Long>();
        for (HealthCourse course : courses) {
            ids.add(course.getId());
        }
        return ids;
    }
 
    private Map<Long, String> resolveCourseTitleMap(Collection<Long> courseIds) {
        if (courseIds == null || courseIds.isEmpty()) {
            return Collections.emptyMap();
        }
        List<HealthCourse> courses = healthCourseMapper.selectList(new LambdaQueryWrapper<HealthCourse>()
                .in(HealthCourse::getId, courseIds)
                .eq(HealthCourse::getDeleted, 0));
        Map<Long, String> map = new LinkedHashMap<Long, String>();
        for (HealthCourse course : courses) {
            map.put(course.getId(), course.getTitle());
        }
        return map;
    }
 
    private List<Long> extractCourseIds(List<HealthCourseVideo> videos) {
        Set<Long> ids = new LinkedHashSet<Long>();
        for (HealthCourseVideo video : videos) {
            ids.add(video.getCourseId());
        }
        return new ArrayList<Long>(ids);
    }
 
    private boolean isImportRowEmpty(HealthCourseVideoImportRow row) {
        return row.getCourseId() == null
                && (row.getChapterName() == null || row.getChapterName().trim().isEmpty())
                && row.getSalePrice() == null
                && row.getDurationSeconds() == null
                && (row.getVideoUrl() == null || row.getVideoUrl().trim().isEmpty())
                && (row.getStatusText() == null || row.getStatusText().trim().isEmpty());
    }
 
    private void validateImportRow(HealthCourseVideoImportRow row, int rowNum) {
        if (row.getCourseId() == null) {
            throw new IllegalArgumentException("第" + rowNum + "行:关联课程ID不能为空");
        }
        if (row.getCourseTypeText() != null && !row.getCourseTypeText().trim().isEmpty() && !"养生课程".equals(row.getCourseTypeText().trim())) {
            throw new IllegalArgumentException("第" + rowNum + "行:课程类型仅支持养生课程");
        }
        if (row.getChapterName() == null || row.getChapterName().trim().isEmpty()) {
            throw new IllegalArgumentException("第" + rowNum + "行:小节名称不能为空");
        }
        if (row.getSalePrice() != null && row.getSalePrice().compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("第" + rowNum + "行:小节价格不能小于0");
        }
        if (row.getDurationSeconds() == null || row.getDurationSeconds() < 0) {
            throw new IllegalArgumentException("第" + rowNum + "行:时长必须大于等于0");
        }
        if (row.getVideoUrl() == null || row.getVideoUrl().trim().isEmpty()) {
            throw new IllegalArgumentException("第" + rowNum + "行:视频地址不能为空");
        }
        try {
            parseStatusText(row.getStatusText());
        } catch (IllegalArgumentException ex) {
            throw new IllegalArgumentException("第" + rowNum + "行:" + ex.getMessage());
        }
    }
 
    private Integer parseStatusText(String statusText) {
        if (statusText == null || statusText.trim().isEmpty() || "启用".equals(statusText.trim())) {
            return 1;
        }
        if ("禁用".equals(statusText.trim())) {
            return 0;
        }
        throw new IllegalArgumentException("状态仅支持启用或禁用");
    }
}