<?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.wzj.soopin.content.mapper.repository.MessageRepository">

    <!-- 将数据库列映射到 MessageMO 属性 -->
    <resultMap id="MessageResultMap" type="com.wzj.soopin.content.domain.mo.MessageMO">
        <id     column="id"             property="id"/>
        <result column="from_user_id"   property="fromUserId"/>
        <result column="from_nickname"  property="fromNickname"/>
        <result column="from_face"      property="fromFace"/>
        <result column="to_user_id"     property="toUserId"/>
        <result column="msg_type"       property="msgType"/>
        <result column="msg_content"    property="msgContent"
                typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler"/>
        <result column="create_time"    property="createTime"/>
    </resultMap>

    <!-- 保存消息，如果未传 id 则使用 uuid 生成 -->
    <insert id="save" parameterType="com.wzj.soopin.content.domain.mo.MessageMO">
        INSERT INTO cont_message
        (
            id,
            from_user_id,
            from_nickname,
            from_face,
            to_user_id,
            msg_type,
            msg_content,
            create_time
        )
        VALUES
        (
            IFNULL(#{id}, REPLACE(UUID(),'-','')),
            #{fromUserId},
            #{fromNickname},
            #{fromFace},
            #{toUserId},
            #{msgType},
            #{msgContent, jdbcType=LONGVARCHAR, typeHandler=com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler},
            #{createTime}
        )
    </insert>

    <!-- 按接收人查询，按创建时间倒序，分页 -->
    <select id="findAllByToUserIdEqualsOrderByCreateTimeDesc" resultMap="MessageResultMap">
        SELECT
            id,
            from_user_id,
            from_nickname,
            from_face,
            to_user_id,
            msg_type,
            msg_content,
            create_time
        FROM cont_message
        WHERE to_user_id = #{toUserId}
        ORDER BY create_time DESC
        LIMIT #{pageable.offset}, #{pageable.pageSize}
    </select>

</mapper>


