package thyyxxk.webserver.dao.his.socketmessage;

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 thyyxxk.webserver.entity.socketmessage.MessageIndex;
import thyyxxk.webserver.entity.socketmessage.SocketMessage;
import thyyxxk.webserver.entity.socketmessage.SystemMessage;

import java.util.List;

@Mapper
public interface SocketMessageDao {

    @Select("select top 1 convert(varchar(10), send_datetime, 21) from " +
            "t_socket_message where sender='00000' order by send_datetime desc")
    String selectLatestDate();

    @Select("select top 1 convert(varchar(10), send_datetime, 21) from t_socket_message where sender='00000' " +
            "and send_datetime<#{date} order by send_datetime desc")
    String selectLastDate(@Param("date") String date);

    @Select("select id,type,sender,title,content,send_datetime as simpledate from " +
            "t_socket_message where sender='00000' and datediff(day, send_datetime, #{date})=0")
    List<SystemMessage> selectMessagesByDate(@Param("date") String date);



    @Select("<script>" +
            "select * from t_socket_message with(nolock) where level=1 and sender='00000' and " +
            "datediff(day, send_datetime, getdate())=0 and id not in " +
            "<foreach collection='excludes' item='itm' separator=',' open='(' close=')'>#{itm}</foreach> " +
            "</script>")
    List<SystemMessage> selectImportantSystemMessages(@Param("excludes") List<String> excludes);

    @Select("select count(1) from t_socket_message_consumer with(nolock) where receiver=#{receiver} and status=0")
    int selectUnreadCount(@Param("receiver") String receiver);

    @Select("select count(1) from t_socket_message where sender='00000'")
    int selectSystemMessageCount();

    @Select("select a.sender,unreadCount=(select count(1) from t_socket_message_consumer t where " +
            "t.receiver=#{receiver} and t.sender=a.sender and t.status=0) " +
            "from t_socket_message_consumer a where a.receiver=#{receiver} group by a.sender")
    List<MessageIndex> selectMessageIndex(@Param("receiver") String receiver);

    @Select("select * from t_socket_message where sender='00000'")
    List<SocketMessage> selectAllSystemMessages();

    @Select("select *, status=(select status from t_socket_message_consumer t where t.msg_id=a.id and t.receiver=#{receiver}) " +
            "from t_socket_message a where id in (select msg_id from t_socket_message_consumer t " +
            "where t.sender=#{sender} and t.receiver=#{receiver})")
    List<SocketMessage> selectNeededMessages(@Param("sender") String sender, @Param("receiver") String receiver);

    @Update("update t_socket_message_consumer set status=1 where sender=#{sender} and receiver=#{receiver}")
    Integer updateReadStatus(@Param("sender") String sender, @Param("receiver") String receiver);
}
