package com.common.mapper;

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

import java.util.List;

/**
 * 探针心跳状态 Mapper 接口
 */
@Mapper
public interface DeviceCollectHeartbeatMapper {

    /**
     * 根据探针ID查询
     */
    @Select("SELECT * FROM device_collect_heartbeat WHERE collect_id = #{collectId}")
    DeviceCollectHeartbeat selectByCollectId(@Param("collectId") String collectId);

    /**
     * 查询所有探针
     */
    @Select("SELECT * FROM device_collect_heartbeat ORDER BY update_time DESC")
    List<DeviceCollectHeartbeat> selectAll();

    /**
     * 查询所有在线探针
     */
    @Select("SELECT * FROM device_collect_heartbeat WHERE status = 'online' ORDER BY update_time DESC")
    List<DeviceCollectHeartbeat> selectAllOnline();

    /**
     * 查询所有离线探针
     */
    @Select("SELECT * FROM device_collect_heartbeat WHERE status = 'offline' ORDER BY update_time DESC")
    List<DeviceCollectHeartbeat> selectAllOffline();

    /**
     * 插入或更新（根据collect_id）
     */
    @Insert("INSERT INTO device_collect_heartbeat (" +
            "collect_id, collect_name, device_ip, app_version, last_heartbeat, " +
            "heartbeat_count, status, fail_count, update_time " +
            ") VALUES (" +
            "#{collectId}, #{collectName}, #{deviceIp}, #{appVersion}, #{lastHeartbeat}, " +
            "#{heartbeatCount}, #{status}, #{failCount}, #{updateTime} " +
            ") ON CONFLICT (collect_id) DO UPDATE SET " +
            "collect_name = EXCLUDED.collect_name, " +
            "device_ip = EXCLUDED.device_ip, " +
            "app_version = EXCLUDED.app_version, " +
            "last_heartbeat = EXCLUDED.last_heartbeat, " +
            "heartbeat_count = EXCLUDED.heartbeat_count, " +
            "status = EXCLUDED.status, " +
            "fail_count = EXCLUDED.fail_count, " +
            "update_time = EXCLUDED.update_time")
    int upsert(DeviceCollectHeartbeat heartbeat);

    /**
     * 更新探针状态
     */
    @Update("UPDATE device_collect_heartbeat SET " +
            "status = #{status}, fail_count = #{failCount}, update_time = #{updateTime} " +
            "WHERE collect_id = #{collectId}")
    int updateStatus(@Param("collectId") String collectId, 
                    @Param("status") String status, 
                    @Param("failCount") Integer failCount,
                    @Param("updateTime") java.time.LocalDateTime updateTime);

    /**
     * 查询超过指定时间未心跳的探针（用于检测离线）
     */
    @Select("SELECT * FROM device_collect_heartbeat " +
            "WHERE status = 'online' AND last_heartbeat < #{thresholdTime} " +
            "ORDER BY last_heartbeat ASC")
    List<DeviceCollectHeartbeat> selectOfflineCandidates(@Param("thresholdTime") java.time.LocalDateTime thresholdTime);

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