-- ===========================================
-- 班级操行分管理系统 - v2.0 数据库迁移脚本
-- 适用版本: v1.8 → v2.0
-- 字符集: utf8mb4
-- 
-- 说明:
--   v2.0 主要为应用层代码变更（UI折叠菜单、扣分类型扩展、
--   科目选择修复、页面改名、记录人优化、学期管理优化等），
--   数据库 schema 变更较少。本脚本主要处理历史数据迁移
--   和索引优化。
-- 
-- 迁移内容:
--   1. 将 conduct_records.recorder_name 从用户名更新为真实姓名
--   2. 将 attendance_records 相关记录中的 recorder_name 同步更新
--   3. 确保 semester_id 索引存在（学期记录数统计优化）
--   4. 数据验证
--
-- 重要: 执行前请备份数据库！
-- ===========================================

USE `classmanagerdb`;

-- ===========================================
-- 1. 更新 conduct_records 中的 recorder_name
--    v2.0 将 recorder_name 从用户名(username)改为真实姓名(real_name)
--    需要将历史记录中的用户名更新为对应的真实姓名
-- ===========================================

-- 通过 JOIN users 表将 recorder_name 从 username 更新为 real_name
UPDATE conduct_records cr
INNER JOIN users u ON cr.recorder_id = u.user_id
SET cr.recorder_name = u.real_name
WHERE cr.recorder_name != u.real_name
  OR cr.recorder_name IS NULL;

-- ===========================================
-- 2. 确保学期相关索引存在
--    v2.0 新增学期记录数统计功能，需要 semester_id 索引优化查询
-- ===========================================

SET @dbname = DATABASE();

-- conduct_records 表 semester_id 索引
SET @indexname = 'idx_conduct_semester_id';
SET @preparedStatement = (SELECT IF(
  (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
   WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = 'conduct_records' AND INDEX_NAME = @indexname) > 0,
  'SELECT 1',
  'ALTER TABLE conduct_records ADD INDEX idx_conduct_semester_id (semester_id)'
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- attendance_records 表 semester_id 索引
SET @indexname = 'idx_attendance_semester_id';
SET @preparedStatement = (SELECT IF(
  (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
   WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = 'attendance_records' AND INDEX_NAME = @indexname) > 0,
  'SELECT 1',
  'ALTER TABLE attendance_records ADD INDEX idx_attendance_semester_id (semester_id)'
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- ===========================================
-- 3. 确保之前版本的索引也存在（幂等兼容）
-- ===========================================

-- assignments 表 subject_id 索引（v1.8 科目删除数据检查）
SET @indexname = 'idx_assignments_subject_id';
SET @preparedStatement = (SELECT IF(
  (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
   WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = 'assignments' AND INDEX_NAME = @indexname) > 0,
  'SELECT 1',
  'ALTER TABLE assignments ADD INDEX idx_assignments_subject_id (subject_id)'
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- conduct_records 表 student_id 索引
SET @indexname = 'idx_conduct_student_id';
SET @preparedStatement = (SELECT IF(
  (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
   WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = 'conduct_records' AND INDEX_NAME = @indexname) > 0,
  'SELECT 1',
  'ALTER TABLE conduct_records ADD INDEX idx_conduct_student_id (student_id)'
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- conduct_records 表 created_at 索引
SET @indexname = 'idx_conduct_created_at';
SET @preparedStatement = (SELECT IF(
  (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
   WHERE TABLE_SCHEMA = @dbname AND TABLE_NAME = 'conduct_records' AND INDEX_NAME = @indexname) > 0,
  'SELECT 1',
  'ALTER TABLE conduct_records ADD INDEX idx_conduct_created_at (created_at)'
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- ===========================================
-- 4. 验证迁移结果
-- ===========================================

SELECT '===== v2.0 数据库迁移验证 =====' AS '';

-- 检查 recorder_name 是否已更新为真实姓名
SELECT 
    'recorder_name 迁移验证' AS `检查项`,
    COUNT(*) AS `总记录数`,
    SUM(CASE WHEN cr.recorder_name = u.real_name THEN 1 ELSE 0 END) AS `已匹配真实姓名`,
    SUM(CASE WHEN cr.recorder_name != u.real_name AND u.real_name IS NOT NULL THEN 1 ELSE 0 END) AS `仍为用户名`
FROM conduct_records cr
INNER JOIN users u ON cr.recorder_id = u.user_id;

-- 检查学期相关索引
SELECT 
    '学期索引验证' AS `检查项`,
    TABLE_NAME AS `表名`,
    INDEX_NAME AS `索引名`
FROM INFORMATION_SCHEMA.STATISTICS 
WHERE TABLE_SCHEMA = @dbname 
  AND INDEX_NAME IN ('idx_conduct_semester_id', 'idx_attendance_semester_id')
GROUP BY TABLE_NAME, INDEX_NAME;

-- 检查学期记录数统计示例
SELECT 
    '学期记录统计示例' AS `检查项`,
    s.semester_name,
    s.is_active,
    (SELECT COUNT(*) FROM conduct_records WHERE semester_id = s.semester_id) AS `操行分记录数`,
    (SELECT COUNT(*) FROM attendance_records WHERE semester_id = s.semester_id) AS `考勤记录数`
FROM semesters s
ORDER BY s.is_active DESC, s.created_at DESC
LIMIT 5;

SELECT 'v2.0 数据库迁移完成！' AS message;
