package com.zhentao.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.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（MySQL）
 */
@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {

    /**
     * 根据消息ID查询消息
     */
    @Select("SELECT * FROM chat_message WHERE message_id = #{messageId} AND is_deleted = 0 LIMIT 1")
    ChatMessage selectByMessageId(@Param("messageId") String messageId);

    /**
     * 查询会话消息列表（分页，按时间倒序）
     */
    @Select("SELECT * FROM chat_message WHERE conversation_id = #{conversationId} AND is_deleted = 0 ORDER BY send_time DESC")
    IPage<ChatMessage> selectByConversationId(Page<?> page, @Param("conversationId") String conversationId);

    /**
     * 查询用户未读消息
     */
    @Select("SELECT * FROM chat_message WHERE to_user_id = #{toUserId} AND send_status IN (1, 2) AND is_deleted = 0 ORDER BY send_time ASC")
    List<ChatMessage> selectUnreadMessages(@Param("toUserId") Long toUserId);

    /**
     * 查询用户离线消息（限制数量）
     */
    @Select("SELECT * FROM chat_message WHERE to_user_id = #{toUserId} AND send_status IN (1, 2) AND is_deleted = 0 ORDER BY send_time ASC LIMIT #{limit}")
    List<ChatMessage> selectOfflineMessages(@Param("toUserId") Long toUserId, @Param("limit") Integer limit);

    /**
     * 查询会话最后一条消息
     */
    @Select("SELECT * FROM chat_message WHERE conversation_id = #{conversationId} AND is_deleted = 0 ORDER BY send_time DESC LIMIT 1")
    ChatMessage selectLastMessage(@Param("conversationId") String conversationId);

    /**
     * 统计会话未读消息数
     */
    @Select("SELECT COUNT(*) FROM chat_message WHERE to_user_id = #{toUserId} AND from_user_id = #{fromUserId} AND send_status IN (1, 2) AND is_deleted = 0")
    long countUnreadMessages(@Param("toUserId") Long toUserId, @Param("fromUserId") Long fromUserId);

    /**
     * 更新消息状态
     */
    @Update("UPDATE chat_message SET send_status = #{status}, update_time = NOW() WHERE message_id = #{messageId}")
    int updateStatusByMessageId(@Param("messageId") String messageId, @Param("status") Integer status);

    /**
     * 批量更新消息为已读
     */
    @Update("UPDATE chat_message SET send_status = 3, read_time = NOW(), update_time = NOW() WHERE to_user_id = #{toUserId} AND from_user_id = #{fromUserId} AND send_status IN (1, 2)")
    int updateMessagesToRead(@Param("toUserId") Long toUserId, @Param("fromUserId") Long fromUserId);

    /**
     * 撤回消息
     */
    @Update("UPDATE chat_message SET is_recalled = 1, recall_time = NOW(), update_time = NOW() WHERE message_id = #{messageId}")
    int recallMessage(@Param("messageId") String messageId);
}


