-- 修复课件时长数据
-- 执行日期：2025-12-05
-- 问题：部分课件的duration字段为0或null，导致进度计算不准确

USE ry_study;

-- 1. 查看当前课程1的所有课件时长情况
SELECT 
    id,
    name,
    type,
    duration,
    file_path
FROM courseware
WHERE course_id = 1
ORDER BY id;

-- 2. 根据学习详情中的最大播放位置，推算视频的实际时长并更新
-- （如果有学生播放到末尾，最大videoPosition可以作为duration的参考）
UPDATE courseware c
SET c.duration = (
    SELECT MAX(ld.video_end_position) + 3  -- 加3秒作为缓冲
    FROM learning_detail ld
    WHERE ld.courseware_id = c.id
      AND ld.video_end_position > 0
)
WHERE c.type = 'video'
  AND c.course_id = 1
  AND (c.duration IS NULL OR c.duration = 0)
  AND EXISTS (
      SELECT 1 FROM learning_detail ld2
      WHERE ld2.courseware_id = c.id
        AND ld2.video_end_position > 0
  );

-- 3. 手动设置已知的课件时长（根据日志）
-- 课件873：实际17秒，当前配置30秒
UPDATE courseware 
SET duration = 17 
WHERE id = 873 AND course_id = 1;

-- 课件882：实际3秒，当前配置0
UPDATE courseware 
SET duration = 3 
WHERE id = 882 AND course_id = 1;

-- 4. 验证修复结果
SELECT 
    id,
    name,
    type,
    duration,
    CASE 
        WHEN duration IS NULL THEN '⚠️ NULL'
        WHEN duration = 0 THEN '⚠️ 0'
        ELSE '✅ 正常'
    END as status
FROM courseware
WHERE course_id = 1
ORDER BY id;

-- 5. 检查学习详情中的最大播放位置（可以作为duration的参考）
SELECT 
    c.id as courseware_id,
    c.name,
    c.duration as configured_duration,
    MAX(ld.video_end_position) as max_position,
    COUNT(ld.id) as record_count
FROM courseware c
LEFT JOIN learning_detail ld ON ld.courseware_id = c.id
WHERE c.course_id = 1 AND c.type = 'video'
GROUP BY c.id, c.name, c.duration
ORDER BY c.id;
