-- 快速修复题目格式和数据
USE study;

-- 1. 设置默认分值
UPDATE question SET score = 5 WHERE score IS NULL OR score = 0;
UPDATE question_bank_item SET score = 5 WHERE score IS NULL OR score = 0;

-- 2. 为排序为空的题目设置排序
SET @row_number = 0;
SET @exam_id = NULL;
UPDATE question q
JOIN (
    SELECT id, exam_id, (@row_number:=IF(@exam_id=exam_id, @row_number+1, 1)) AS new_order, (@exam_id:=exam_id)
    FROM question
    ORDER BY exam_id, IFNULL(sort_order, 999), id
) AS ranked ON q.id = ranked.id
SET q.sort_order = ranked.new_order
WHERE q.sort_order IS NULL;

-- 3. 同步考试题量和总分
UPDATE exam e
LEFT JOIN (
    SELECT 
        exam_id,
        COUNT(*) AS actual_count,
        SUM(IFNULL(score, 0)) AS actual_score
    FROM question
    GROUP BY exam_id
) AS stats ON e.id = stats.exam_id
SET 
    e.question_count = IFNULL(stats.actual_count, 0),
    e.total_score = IFNULL(stats.actual_score, 0);

-- 4. 规范化多选题答案格式
UPDATE question 
SET correct_answer = REPLACE(REPLACE(correct_answer, ', ', ','), ' ,', ',')
WHERE question_type = 'multiple';

UPDATE question_bank_item 
SET correct_answer = REPLACE(REPLACE(correct_answer, ', ', ','), ' ,', ',')
WHERE question_type = 'multiple';

-- 5. 规范化判断题答案
UPDATE question 
SET correct_answer = CASE 
    WHEN LOWER(correct_answer) IN ('true', 't', '1', 'yes', '对') THEN '正确'
    WHEN LOWER(correct_answer) IN ('false', 'f', '0', 'no', '错') THEN '错误'
    ELSE correct_answer
END
WHERE question_type = 'judge';

UPDATE question_bank_item 
SET correct_answer = CASE 
    WHEN LOWER(correct_answer) IN ('true', 't', '1', 'yes', '对') THEN '正确'
    WHEN LOWER(correct_answer) IN ('false', 'f', '0', 'no', '错') THEN '错误'
    ELSE correct_answer
END
WHERE question_type = 'judge';

-- 6. 验证修复结果
SELECT 
    e.id,
    e.exam_name,
    e.question_count AS 记录题量,
    e.total_score AS 记录总分,
    COUNT(q.id) AS 实际题量,
    SUM(IFNULL(q.score, 0)) AS 实际总分,
    CASE 
        WHEN e.question_count = COUNT(q.id) AND e.total_score = SUM(IFNULL(q.score, 0)) THEN '✓ 正确'
        ELSE '❌ 不一致'
    END AS 状态
FROM exam e
LEFT JOIN question q ON e.id = q.exam_id
GROUP BY e.id
ORDER BY e.create_time DESC
LIMIT 10;
