package com.common.mapper;

import com.common.entity.DeviceCollectHeartbeatHistory;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 探针心跳历史 Mapper 接口
 */
@Mapper
public interface DeviceCollectHeartbeatHistoryMapper {

    /**
     * 插入心跳历史记录
     */
    @Insert("INSERT INTO device_collect_heartbeat_history (" +
            "collect_id, heartbeat_time, device_ip, app_version, created_at " +
            ") VALUES (" +
            "#{collectId}, #{heartbeatTime}, #{deviceIp}, #{appVersion}, #{createdAt} " +
            ")")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(DeviceCollectHeartbeatHistory history);

    /**
     * 批量插入心跳历史记录
     */
    @Insert("<script>" +
            "INSERT INTO device_collect_heartbeat_history " +
            "(collect_id, heartbeat_time, device_ip, app_version, created_at ) " +
            "VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.collectId}, #{item.heartbeatTime}, #{item.deviceIp}, #{item.appVersion}, " +
            "#{item.createdAt} )" +
            "</foreach>" +
            "</script>")
    int batchInsert(@Param("list") List<DeviceCollectHeartbeatHistory> histories);

    /**
     * 根据探针ID查询历史记录
     */
    @Select("SELECT * FROM device_collect_heartbeat_history " +
            "WHERE collect_id = #{collectId} ORDER BY heartbeat_time DESC LIMIT #{limit}")
    List<DeviceCollectHeartbeatHistory> selectByCollectId(@Param("collectId") String collectId, 
                                                         @Param("limit") Integer limit);

    /**
     * 删除指定日期之前的记录
     */
    @Delete("DELETE FROM device_collect_heartbeat_history WHERE created_at < #{beforeTime}")
    int deleteBeforeTime(@Param("beforeTime") LocalDateTime beforeTime);

    /**
     * 统计指定日期之前的记录数
     */
    @Select("SELECT COUNT(*) FROM device_collect_heartbeat_history WHERE created_at < #{beforeTime}")
    long countBeforeTime(@Param("beforeTime") LocalDateTime beforeTime);
}
