package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {
    
    /**
     * 查询两个用户之间的聊天记录
     */
    @Select("SELECT * FROM chat_message WHERE " +
            "((sender_id = #{userId1} AND sender_type = #{userType1} AND receiver_id = #{userId2} AND receiver_type = #{userType2}) OR " +
            "(sender_id = #{userId2} AND sender_type = #{userType2} AND receiver_id = #{userId1} AND receiver_type = #{userType1})) " +
            "ORDER BY send_time ASC")
    List<ChatMessage> selectChatHistory(@Param("userId1") Integer userId1, @Param("userType1") String userType1,
                                      @Param("userId2") Integer userId2, @Param("userType2") String userType2);
    
    /**
     * 将消息标记为已读
     */
    @Update("UPDATE chat_message SET is_read = 1, read_time = NOW() " +
            "WHERE receiver_id = #{receiverId} AND receiver_type = #{receiverType} " +
            "AND sender_id = #{senderId} AND sender_type = #{senderType} AND is_read = 0")
    int markAsRead(@Param("receiverId") Integer receiverId, @Param("receiverType") String receiverType,
                 @Param("senderId") Integer senderId, @Param("senderType") String senderType);
    
    /**
     * 查询用户的聊天列表（最近联系人）
     */
    @Select("SELECT DISTINCT " +
            "CASE WHEN sender_id = #{userId} AND sender_type = #{userType} THEN receiver_id ELSE sender_id END AS contact_id, " +
            "CASE WHEN sender_id = #{userId} AND sender_type = #{userType} THEN receiver_type ELSE sender_type END AS contact_type " +
            "FROM chat_message " +
            "WHERE (sender_id = #{userId} AND sender_type = #{userType}) OR (receiver_id = #{userId} AND receiver_type = #{userType}) " +
            "ORDER BY MAX(send_time) DESC")
    List<Object[]> selectChatContacts(@Param("userId") Integer userId, @Param("userType") String userType);
    
    /**
     * 统计未读消息数
     */
    @Select("SELECT COUNT(*) FROM chat_message WHERE receiver_id = #{receiverId} AND receiver_type = #{receiverType} AND sender_id = #{senderId} AND sender_type = #{senderType} AND is_read = 0")
    int countUnreadMessages(@Param("receiverId") Integer receiverId, @Param("receiverType") String receiverType,
                          @Param("senderId") Integer senderId, @Param("senderType") String senderType);
} 