USE zhibo;

-- ==========================================
-- 修复直播间主播关联 - 完整方案
-- ==========================================

-- 步骤1: 查看当前情况
SELECT '========== 当前数据情况 ==========' as info;

-- 查看有多少主播
SELECT 
    '认证主播数量' as item,
    COUNT(*) as count
FROM eb_user 
WHERE is_streamer = 1;

-- 查看直播间情况
SELECT 
    '总直播间数' as item,
    COUNT(*) as count
FROM eb_live_room
UNION ALL
SELECT 
    'uid为空或0的直播间' as item,
    COUNT(*) as count
FROM eb_live_room
WHERE uid IS NULL OR uid = 0
UNION ALL
SELECT 
    'uid无效的直播间(用户不存在)' as item,
    COUNT(*) as count
FROM eb_live_room
WHERE uid IS NOT NULL AND uid > 0 AND uid NOT IN (SELECT uid FROM eb_user);

-- 步骤2: 选择一个默认主播
-- 优先选择有最多关注记录的主播
SELECT '========== 选择默认主播 ==========' as info;

SELECT 
    u.uid,
    u.nickname,
    u.phone,
    u.is_streamer,
    COUNT(fr.id) as follower_count
FROM eb_user u
LEFT JOIN eb_follow_record fr ON fr.followed_id = u.uid AND fr.follow_status = '关注'
WHERE u.is_streamer = 1
GROUP BY u.uid, u.nickname, u.phone, u.is_streamer
ORDER BY follower_count DESC, u.uid ASC
LIMIT 5;

-- 使用第一个主播作为默认主播（uid=318 根据之前的数据）
SET @default_streamer_id = (
    SELECT u.uid
    FROM eb_user u
    WHERE u.is_streamer = 1
    ORDER BY u.uid ASC
    LIMIT 1
);

SELECT CONCAT('默认主播ID: ', @default_streamer_id) as info;

-- 获取默认主播的昵称
SET @default_streamer_name = (
    SELECT nickname 
    FROM eb_user 
    WHERE uid = @default_streamer_id
);

SELECT CONCAT('默认主播昵称: ', @default_streamer_name) as info;

-- 步骤3: 修复所有无效的直播间
SELECT '========== 开始修复直播间数据 ==========' as info;

-- 3.1 修复 uid 为空或0的直播间
UPDATE eb_live_room 
SET uid = @default_streamer_id,
    streamer_name = @default_streamer_name
WHERE uid IS NULL OR uid = 0;

SELECT CONCAT('已修复 uid 为空或0的直播间: ', ROW_COUNT(), ' 条') as result;

-- 3.2 修复 uid 指向不存在用户的直播间
UPDATE eb_live_room 
SET uid = @default_streamer_id,
    streamer_name = @default_streamer_name
WHERE uid IS NOT NULL 
  AND uid > 0 
  AND uid NOT IN (SELECT uid FROM eb_user);

SELECT CONCAT('已修复 uid 无效的直播间: ', ROW_COUNT(), ' 条') as result;

-- 步骤4: 验证修复结果
SELECT '========== 修复结果验证 ==========' as info;

SELECT 
    '总直播间数' as item,
    COUNT(*) as count
FROM eb_live_room
UNION ALL
SELECT 
    'uid有效的直播间' as item,
    COUNT(*) as count
FROM eb_live_room
WHERE uid IN (SELECT uid FROM eb_user)
UNION ALL
SELECT 
    'uid无效的直播间' as item,
    COUNT(*) as count
FROM eb_live_room
WHERE uid NOT IN (SELECT uid FROM eb_user);

-- 步骤5: 查看修复后的直播间样例
SELECT '========== 修复后的直播间样例 ==========' as info;

SELECT 
    r.id,
    r.uid,
    u.nickname as actual_streamer_name,
    r.streamer_name as room_streamer_name,
    r.title,
    r.is_live,
    r.create_time
FROM eb_live_room r
LEFT JOIN eb_user u ON r.uid = u.uid
ORDER BY r.id DESC
LIMIT 10;

-- 步骤6: 添加外键约束（可选，确保数据一致性）
-- 注意：添加外键前必须确保所有数据都有效
SELECT '========== 添加外键约束 ==========' as info;

-- 检查是否已存在外键
SELECT 
    CONSTRAINT_NAME,
    CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = 'zhibo'
  AND TABLE_NAME = 'eb_live_room'
  AND CONSTRAINT_TYPE = 'FOREIGN KEY';

-- 如果没有外键，添加外键约束
-- ALTER TABLE eb_live_room
-- ADD CONSTRAINT fk_live_room_user
-- FOREIGN KEY (uid) REFERENCES eb_user(uid)
-- ON DELETE CASCADE
-- ON UPDATE CASCADE;

SELECT '提示: 外键约束已注释，如需启用请手动执行' as info;

-- 步骤7: 创建触发器，确保新建直播间时uid必须有效（可选）
SELECT '========== 创建验证触发器 ==========' as info;

DELIMITER $$

DROP TRIGGER IF EXISTS before_live_room_insert$$
CREATE TRIGGER before_live_room_insert
BEFORE INSERT ON eb_live_room
FOR EACH ROW
BEGIN
    DECLARE user_exists INT;
    
    -- 检查uid是否为空
    IF NEW.uid IS NULL OR NEW.uid = 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = '直播间必须指定有效的主播ID';
    END IF;
    
    -- 检查用户是否存在
    SELECT COUNT(*) INTO user_exists
    FROM eb_user
    WHERE uid = NEW.uid;
    
    IF user_exists = 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = '指定的主播用户不存在';
    END IF;
    
    -- 检查用户是否是认证主播
    SELECT COUNT(*) INTO user_exists
    FROM eb_user
    WHERE uid = NEW.uid AND is_streamer = 1;
    
    IF user_exists = 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = '只有认证主播才能创建直播间';
    END IF;
END$$

DROP TRIGGER IF EXISTS before_live_room_update$$
CREATE TRIGGER before_live_room_update
BEFORE UPDATE ON eb_live_room
FOR EACH ROW
BEGIN
    DECLARE user_exists INT;
    
    -- 如果uid被修改，进行验证
    IF NEW.uid != OLD.uid THEN
        -- 检查uid是否为空
        IF NEW.uid IS NULL OR NEW.uid = 0 THEN
            SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = '直播间必须指定有效的主播ID';
        END IF;
        
        -- 检查用户是否存在
        SELECT COUNT(*) INTO user_exists
        FROM eb_user
        WHERE uid = NEW.uid;
        
        IF user_exists = 0 THEN
            SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = '指定的主播用户不存在';
        END IF;
    END IF;
END$$

DELIMITER ;

SELECT '触发器创建完成' as info;

-- 步骤8: 最终统计
SELECT '========== 最终统计 ==========' as info;

SELECT 
    u.uid,
    u.nickname,
    COUNT(r.id) as room_count,
    SUM(CASE WHEN r.is_live = 1 THEN 1 ELSE 0 END) as live_room_count
FROM eb_user u
LEFT JOIN eb_live_room r ON r.uid = u.uid
WHERE u.is_streamer = 1
GROUP BY u.uid, u.nickname
ORDER BY room_count DESC;

SELECT '========== 修复完成 ==========' as info;
