<?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.kym.mapper.MessageMapper">

    <!-- 消息结果映射 -->
    <resultMap id="MessageResultMap" type="com.kym.entity.Message">
        <id column="id" property="id"/>
        <result column="company_id" property="companyId"/>
        <result column="title" property="title"/>
        <result column="content" property="content"/>
        <result column="type" property="type"/>
        <result column="sender_id" property="senderId"/>
        <result column="sender_name" property="senderName"/>
        <result column="receiver_id" property="receiverId"/>
        <result column="receiver_name" property="receiverName"/>
        <result column="status" property="status"/>
        <result column="read_time" property="readTime"/>
        <result column="biz_type" property="bizType"/>
        <result column="biz_id" property="bizId"/>
        <result column="priority" property="priority"/>
        <result column="is_push" property="isPush"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
    </resultMap>

    <!-- 分页查询消息列表 -->
    <select id="selectMessagePage" resultMap="MessageResultMap">
        SELECT * FROM t_message
        <where>
            status != 2
            <if test="params.receiverId != null">
                AND receiver_id = #{params.receiverId}
            </if>
            <if test="params.senderId != null">
                AND sender_id = #{params.senderId}
            </if>
            <if test="params.type != null">
                AND type = #{params.type}
            </if>
            <if test="params.status != null">
                AND status = #{params.status}
            </if>
            <if test="params.title != null and params.title != ''">
                AND title LIKE CONCAT('%', #{params.title}, '%')
            </if>
            <if test="params.priority != null">
                AND priority = #{params.priority}
            </if>
        </where>
        ORDER BY priority DESC, create_time DESC
    </select>

    <!-- 统计未读消息数量 -->
    <select id="countUnread" resultType="int">
        SELECT COUNT(*) FROM t_message
        WHERE receiver_id = #{receiverId}
        AND status = 0
    </select>

    <!-- 按类型统计未读消息数量 -->
    <select id="countUnreadByType" resultType="int">
        SELECT COUNT(*) FROM t_message
        WHERE receiver_id = #{receiverId}
        AND status = 0
        AND type = #{type}
    </select>

    <!-- 批量标记已读 -->
    <update id="batchMarkRead">
        UPDATE t_message
        SET status = 1, read_time = NOW()
        WHERE receiver_id = #{receiverId}
        AND status = 0
        <if test="type != null">
            AND type = #{type}
        </if>
    </update>

</mapper>
