-- 修复粉丝团群聊：为没有关联群组的粉丝团自动创建群组

-- 1. 查看当前粉丝团状态
SELECT id, anchor_id, anchor_name, name, group_id, member_count FROM eb_fan_group;

-- 2. 为所有没有group_id的粉丝团创建群组并关联
-- 这是一个存储过程，用于批量修复

DELIMITER //

DROP PROCEDURE IF EXISTS fix_fan_group_chat //

CREATE PROCEDURE fix_fan_group_chat()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE v_fan_group_id INT;
    DECLARE v_anchor_id INT;
    DECLARE v_anchor_name VARCHAR(64);
    DECLARE v_name VARCHAR(64);
    DECLARE v_member_count INT;
    DECLARE v_new_group_id BIGINT;
    
    -- 游标：查找所有没有group_id的粉丝团
    DECLARE cur CURSOR FOR 
        SELECT id, anchor_id, anchor_name, name, member_count 
        FROM eb_fan_group 
        WHERE (group_id IS NULL OR group_id = 0) AND status = 1;
    
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
    OPEN cur;
    
    read_loop: LOOP
        FETCH cur INTO v_fan_group_id, v_anchor_id, v_anchor_name, v_name, v_member_count;
        IF done THEN
            LEAVE read_loop;
        END IF;
        
        -- 1. 创建群组
        INSERT INTO eb_group (group_name, owner_id, avatar, description, member_count, ext_field1, create_time, update_time)
        VALUES (v_name, v_anchor_id, '', CONCAT(v_anchor_name, '的粉丝团群聊'), v_member_count + 1, 'fan_group', NOW(), NOW());
        
        SET v_new_group_id = LAST_INSERT_ID();
        
        -- 2. 更新粉丝团的group_id
        UPDATE eb_fan_group SET group_id = v_new_group_id WHERE id = v_fan_group_id;
        
        -- 3. 将主播加入群组成员（如果不存在）
        -- role: 0-普通成员 1-管理员 2-群主
        INSERT IGNORE INTO eb_group_member (group_id, user_id, nickname, role, join_time)
        VALUES (v_new_group_id, v_anchor_id, v_anchor_name, 2, NOW());
        
        -- 4. 将粉丝团现有成员也加入群组
        INSERT IGNORE INTO eb_group_member (group_id, user_id, nickname, role, join_time)
        SELECT v_new_group_id, uid, nickname, 0, join_time
        FROM eb_fan_group_member
        WHERE group_id = v_fan_group_id AND status = 1;
        
    END LOOP;
    
    CLOSE cur;
END //

DELIMITER ;

-- 执行修复
CALL fix_fan_group_chat();

-- 删除存储过程
DROP PROCEDURE IF EXISTS fix_fan_group_chat;

-- 验证结果
SELECT fg.id, fg.name, fg.group_id, g.id as group_table_id, g.group_name, g.member_count
FROM eb_fan_group fg
LEFT JOIN eb_group g ON fg.group_id = g.id;

-- 简化版本（如果不想用存储过程，可以手动执行以下SQL）：
-- 针对粉丝团 id=4

-- 步骤1: 创建群组
-- INSERT INTO eb_group (group_name, owner_id, avatar, description, member_count, ext_field1, create_time, update_time)
-- SELECT name, anchor_id, '', CONCAT(anchor_name, '的粉丝团群聊'), member_count + 1, 'fan_group', NOW(), NOW()
-- FROM eb_fan_group WHERE id = 4;

-- 步骤2: 更新粉丝团的group_id
-- UPDATE eb_fan_group SET group_id = LAST_INSERT_ID() WHERE id = 4;

-- 步骤3: 将主播加入群组
-- role: 0-普通成员 1-管理员 2-群主
-- INSERT INTO eb_group_member (group_id, user_id, nickname, role, join_time)
-- SELECT fg.group_id, fg.anchor_id, fg.anchor_name, 2, NOW()
-- FROM eb_fan_group fg WHERE fg.id = 4;
