package com.lutao.cloud.oil.runner;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lutao.cloud.oil.service.AtmosphereMonitorInfoService;
import com.lutao.entity.AtmosphereMonitorInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

@Component
public class RemoveAtmosphereMonitorInfoExecutor {

    @Resource
    private AtmosphereMonitorInfoService atmosphereMonitorInfoService;

    @Resource(name = "redisTemplateAlias")
    private RedisTemplate redisTemplate;

    private static final String LOCK_KEY = "scheduled_task_lock:RemoveAtmosphereMonitorInfoExecutor";

    /**
     * 删除气象信息旧数据
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void execute() {
        if (acquireLock()){
         try {
             // 获取当前的 LocalDateTime
             LocalDateTime now = LocalDateTime.now();
             // 设置时间部分为当天的最小时间
             LocalDateTime startOfDay = now.with(LocalTime.MIN);
             LocalDateTime minus = startOfDay.minusDays(1);

             //删除前一天以前的数据
             atmosphereMonitorInfoService.remove(Wrappers.lambdaQuery(AtmosphereMonitorInfo.class)
                     .lt(AtmosphereMonitorInfo::getCreateTime, minus));
         }finally {
             releaseLock();
         }
        }

    }


    private boolean acquireLock() {
        // 尝试获取锁，设置超时时间为 1 分钟
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, "locked", 1, TimeUnit.MINUTES));
    }

    private void releaseLock() {
        // 释放锁
        redisTemplate.delete(LOCK_KEY);
    }
}
