package com.hdkj.lt.bf.scheduler;

import com.hdkj.lt.bf.entity.FhzgSeVoltageEvent;
import com.hdkj.lt.bf.mapper.FhzgSeVoltageEventMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 电压事件兜底清扫
 * <p>
 * 关闭超过24小时仍未恢复的活跃事件，防止因断档/数据缺失导致的事件失联。
 * 正常恢复由断面处理时的状态机走，此任务仅做兜底。
 *
 * @author lsl
 * @since 2026-07-27
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SeVoltageCleanupScheduler {

    private final FhzgSeVoltageEventMapper voltageEventMapper;

    /**
     * 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanupStaleVoltageEvents() {
        LocalDateTime threshold = LocalDateTime.now().minusHours(24);
        FhzgSeVoltageEvent update = new FhzgSeVoltageEvent();
        update.setStatus(2);
        update.setRecoverTime(LocalDateTime.now());
        int updated = voltageEventMapper.update(update,
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FhzgSeVoltageEvent>()
                        .eq(FhzgSeVoltageEvent::getStatus, 1)
                        .lt(FhzgSeVoltageEvent::getTriggerTime, threshold));
        if (updated > 0) {
            log.info("[电压事件清扫] 关闭 {} 条超过24h未恢复的电压事件（triggerTime < {}）", updated, threshold);
        }
    }
}
