package com.fs.app.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.ad.domain.AdHtmlClickLog;
import com.fs.ad.service.IAdHtmlClickLogService;
import com.fs.ad.service.impl.AdHtmlClickLogServiceImpl;
import com.fs.common.core.redis.RedisCacheT;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@AllArgsConstructor
public class Task {
    private RedisCacheT<AdHtmlClickLog> redisCache;
    private IAdHtmlClickLogService adHtmlClickLogService;

//    @Scheduled(cron = "0/30 * * * * ?")
    @Scheduled(cron = "0 0/30 * * * ?")
    public void saveLog() {
        List<AdHtmlClickLog> list = redisCache.getCacheListByPattern(AdHtmlClickLogServiceImpl.AD_LOG_KEY + "*");
        list.stream().filter(e -> e.getId() == null).forEach(e -> {
            String key = AdHtmlClickLogServiceImpl.genKey(e.getVid(), e.getType(), e.getClickType());
            adHtmlClickLogService.save(e);
            redisCache.setCacheObject(key, e, LocalDateTime.now().until(e.getLastTime(), ChronoUnit.MINUTES), TimeUnit.MINUTES);
        });
        list.stream().filter(e -> e.getId() != null).forEach(e -> adHtmlClickLogService.update(e, new QueryWrapper<AdHtmlClickLog>().eq("vid", e.getVid()).eq("click_type", e.getClickType())));
    }
}
