<?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.ylx.message.mapper.UserMessageMapper">

    <!-- 结果映射（可选，字段名与VO属性一致时可省略） -->
    <resultMap id="CategoryCardResultMap" type="com.ylx.message.domain.vo.MessageCategoryVO">
        <result column="category_code" property="categoryCode"/>
        <result column="title"         property="title"/>
        <result column="summary"       property="summary"/>
        <result column="create_time"   property="createTime"/>
        <result column="is_read"       property="isRead"/>
        <result column="jump_page"     property="jumpPage"/>
        <result column="msg_id"        property="latestMsgId"/>
    </resultMap>

    <!-- 核心查询：按分类取最新一条消息 -->
    <select id="selectLatestByCategory" resultMap="CategoryCardResultMap">
        SELECT
            t.category_code,
            t.title,
            t.summary,
            DATE_FORMAT(t.create_time, '%H:%i') AS create_time,
            t.is_read,
            t.jump_page,
            t.msg_id
        FROM (
             SELECT
                 mc.category_code,
                 d.dict_label AS title,
                 mc.jump_page,
                 SUBSTRING(um.personalized_content, 1, 50) AS summary,
                 um.create_time,
                 um.is_read,
                 um.id AS msg_id,
                 ROW_NUMBER() OVER (PARTITION BY mc.category_code ORDER BY um.create_time DESC) AS rn
             FROM user_message um
             INNER JOIN message_content mc ON um.message_content_id = mc.id
             LEFT JOIN sys_dict_data d ON d.dict_type = 'msg_category' AND d.dict_value = mc.category_code
             WHERE um.user_id = #{userId}
             AND um.is_delete = 0
             AND mc.is_delete = 0
         ) t
        WHERE t.rn = 1
        ORDER BY t.create_time DESC
    </select>

    <select id="selectMessageListByCategory" resultType="com.ylx.message.domain.vo.MessageDetailVO">
        SELECT
            um.id,
            um.personalized_content AS content, <!-- 渲染后的内容 -->
            DATE_FORMAT(um.create_time, '%H:%i') AS create_time,
            um.is_read AS isRead,
            um.personalized_jump_page AS jumpUrl      <!-- 点击跳转地址 -->
        FROM user_message um
        INNER JOIN message_content mc ON um.message_content_id = mc.id
        WHERE um.user_id = #{dto.userId}
        AND um.is_delete = 0
        AND mc.category_code = #{dto.categoryCode} <!-- 核心过滤条件 -->
        ORDER BY um.create_time DESC
    </select>
</mapper>

