<?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.luojia_channel.modules.message.mapper.MessageMapper">

    <!-- 定义 ChatItemDTO 结果映射 -->
    <resultMap id="ChatItemDTOResultMap" type="com.luojia_channel.modules.interact.dto.ChatItemDTO">
        <id property="chatUserId" column="chat_user_id"/>
        <result property="avatar" column="avatar"/>
        <result property="username" column="username"/>
        <result property="latestMessage" column="latest_message"/>
        <result property="latestTime" column="create_time"/>
    </resultMap>

    <!-- 查询用户的所有聊天对象及最新消息 -->
    <select id="selectChatList" resultMap="ChatItemDTOResultMap">
        SELECT
            CASE
                WHEN m.sender_id = #{userId} THEN m.receiver_id
                ELSE m.sender_id
                END AS chat_user_id,
            u.avatar,
            u.username,
            m.content AS latest_message,
            m.create_time
        FROM message m
                 JOIN (
            -- 子查询：获取每个聊天对象的最新消息ID
            SELECT
                MAX(id) AS max_id
            FROM message
            WHERE sender_id = #{userId} OR receiver_id = #{userId}
            GROUP BY
                CASE
                    WHEN sender_id = #{userId} THEN receiver_id
                    ELSE sender_id
                    END
        ) latest ON m.id = latest.max_id
                 LEFT JOIN user u ON
            CASE
                WHEN m.sender_id = #{userId} THEN m.receiver_id
                ELSE m.sender_id
                END = u.id
        WHERE
            m.sender_id = #{userId} OR m.receiver_id = #{userId}
        GROUP BY
            CASE
                WHEN m.sender_id = #{userId} THEN m.receiver_id
                ELSE m.sender_id
                END
        ORDER BY
            m.create_time DESC
    </select>

    <select id="selectByIdsOrderByField" resultType="com.luojia_channel.modules.message.entity.MessageDO">
        SELECT * FROM message
        WHERE id IN
        <foreach item="id" collection="ids" open="(" separator="," close=")">#{id}</foreach>
        ORDER BY FIELD(id,
        <foreach item="id" collection="ids" separator="," open="" close="">#{id}</foreach>)
    </select>
</mapper>