<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yushu.system.mapper.SysConversationMapper">
    
    <resultMap type="SysConversation" id="SysConversationResult">
        <result property="conversationId"    column="conversation_id"    />
        <result property="conversationType"    column="conversation_type"    />
        <result property="conversationName"    column="conversation_name"    />
        <result property="creatorId"    column="creator_id"    />
        <result property="creatorName"    column="creator_name"    />
        <result property="lastMessageId"    column="last_message_id"    />
        <result property="lastMessageTime"    column="last_message_time"    />
        <result property="status"    column="status"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
    </resultMap>

    <sql id="selectSysConversationVo">
        select conversation_id, conversation_type, conversation_name, creator_id, creator_name, last_message_id, last_message_time, status, create_time, update_time from sys_conversation
    </sql>

    <select id="selectSysConversationList" parameterType="SysConversation" resultMap="SysConversationResult">
        <include refid="selectSysConversationVo"/>
        <where>  
            <if test="conversationId != null  and conversationId != ''"> and conversation_id = #{conversationId}</if>
            <if test="conversationType != null  and conversationType != ''"> and conversation_type = #{conversationType}</if>
            <if test="conversationName != null  and conversationName != ''"> and conversation_name like concat('%', #{conversationName}, '%')</if>
            <if test="creatorId != null "> and creator_id = #{creatorId}</if>
            <if test="status != null  and status != ''"> and status = #{status}</if>
        </where>
        order by last_message_time desc
    </select>
    
    <select id="selectSysConversationByConversationId" parameterType="String" resultMap="SysConversationResult">
        <include refid="selectSysConversationVo"/>
        where conversation_id = #{conversationId}
    </select>

    <!-- 获取用户的会话列表 -->
    <select id="selectUserConversationList" parameterType="Long" resultType="java.util.Map">
        SELECT 
            c.conversation_id,
            c.conversation_type,
            c.conversation_name,
            c.last_message_time,
            cm.unread_count,
            cm.is_muted,
            cm.remark_name,
            -- 获取对方用户信息（私聊）
            (SELECT GROUP_CONCAT(
                CASE 
                    WHEN cm2.remark_name IS NOT NULL AND cm2.remark_name != '' THEN cm2.remark_name
                    WHEN cm2.nick_name IS NOT NULL AND cm2.nick_name != '' THEN cm2.nick_name
                    ELSE cm2.user_name
                END
                SEPARATOR ', '
            ) 
             FROM sys_conversation_member cm2 
             WHERE cm2.conversation_id = c.conversation_id 
             AND cm2.user_id != #{userId}
             AND cm2.is_deleted = '0') as other_members,
            -- 获取最后一条消息
            (SELECT content FROM sys_chat_message WHERE message_id = c.last_message_id) as last_message
        FROM sys_conversation c
        INNER JOIN sys_conversation_member cm ON c.conversation_id = cm.conversation_id
        WHERE cm.user_id = #{userId}
        AND cm.is_deleted = '0' 
        AND c.status = '1'
        ORDER BY c.last_message_time DESC
    </select>
        
    <insert id="insertSysConversation" parameterType="SysConversation">
        insert into sys_conversation
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="conversationId != null and conversationId != ''">conversation_id,</if>
            <if test="conversationType != null">conversation_type,</if>
            <if test="conversationName != null">conversation_name,</if>
            <if test="creatorId != null">creator_id,</if>
            <if test="creatorName != null">creator_name,</if>
            <if test="lastMessageId != null">last_message_id,</if>
            <if test="lastMessageTime != null">last_message_time,</if>
            <if test="status != null">status,</if>
            create_time
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="conversationId != null and conversationId != ''">#{conversationId},</if>
            <if test="conversationType != null">#{conversationType},</if>
            <if test="conversationName != null">#{conversationName},</if>
            <if test="creatorId != null">#{creatorId},</if>
            <if test="creatorName != null">#{creatorName},</if>
            <if test="lastMessageId != null">#{lastMessageId},</if>
            <if test="lastMessageTime != null">#{lastMessageTime},</if>
            <if test="status != null">#{status},</if>
            sysdate()
        </trim>
    </insert>

    <update id="updateSysConversation" parameterType="SysConversation">
        update sys_conversation
        <trim prefix="SET" suffixOverrides=",">
            <if test="conversationType != null">conversation_type = #{conversationType},</if>
            <if test="conversationName != null">conversation_name = #{conversationName},</if>
            <if test="creatorId != null">creator_id = #{creatorId},</if>
            <if test="creatorName != null">creator_name = #{creatorName},</if>
            <if test="lastMessageId != null">last_message_id = #{lastMessageId},</if>
            <if test="lastMessageTime != null">last_message_time = #{lastMessageTime},</if>
            <if test="status != null">status = #{status},</if>
            update_time = sysdate()
        </trim>
        where conversation_id = #{conversationId}
    </update>

    <delete id="deleteSysConversationByConversationId" parameterType="String">
        delete from sys_conversation where conversation_id = #{conversationId}
    </delete>

    <delete id="deleteSysConversationByConversationIds" parameterType="String">
        delete from sys_conversation where conversation_id in 
        <foreach item="conversationId" collection="array" open="(" separator="," close=")">
            #{conversationId}
        </foreach>
    </delete>

    <!-- 创建私聊会话 -->
    <select id="createPrivateConversation" resultType="String">
        SELECT CONCAT('conv_', LEAST(#{user1Id}, #{user2Id}), '_', GREATEST(#{user1Id}, #{user2Id}))
    </select>

    <!-- 添加会话成员 -->
    <insert id="addConversationMember">
        INSERT INTO sys_conversation_member (conversation_id, user_id, user_name, nick_name, unread_count)
        VALUES (#{conversationId}, #{userId}, #{userName}, #{nickName}, 0)
        ON DUPLICATE KEY UPDATE 
        user_name = #{userName}, 
        nick_name = #{nickName},
        unread_count = 0,
        is_deleted = '0'
    </insert>

    <!-- 更新会话成员备注 -->
    <update id="updateMemberRemark">
        UPDATE sys_conversation_member 
        SET remark_name = #{remarkName}
        WHERE conversation_id = #{conversationId} AND user_id = #{userId}
    </update>

    <!-- 更新会话最后消息 -->
    <update id="updateLastMessage">
        UPDATE sys_conversation 
        SET last_message_id = #{messageId}, last_message_time = NOW()
        WHERE conversation_id = #{conversationId}
    </update>

    <!-- 获取会话的所有成员ID -->
    <select id="selectConversationMemberIds" parameterType="String" resultType="Long">
        SELECT user_id FROM sys_conversation_member 
        WHERE conversation_id = #{conversationId} AND is_deleted = '0'
    </select>

</mapper>
