package com.weather.modules.weather.dailydata.task;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weather.common.redis.RedisKeys;
import com.weather.common.redis.RedisUtils;
import com.weather.modules.job.task.ITask;
import com.weather.modules.weather.dailydata.dao.WeatherDailyDataDao;
import com.weather.modules.weather.dailydata.dto.DailyWeatherSummarizeDto;
import com.weather.modules.weather.dailydata.entity.WeatherDailyDataEntity;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 天气汇总缓存预热任务
 * <p>
 * 每日凌晨 1:00 执行，将历年当月-当日的气象数据
 * 按站点分组写入 Redis，供 export-sum 接口查询。
 *
 * @author 2333 123
 * @since 1.0.0 2026-06-24
 */
@Slf4j
@Component("weatherSummarizeCacheTask")
public class WeatherSummarizeCacheTask implements ITask {

    @Resource
    private WeatherDailyDataDao weatherDailyDataDao;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public void run(String params) {
        LocalDate today = LocalDate.now();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();

        log.info("开始刷新天气汇总缓存，日期: {}-{}", month, day);

        try {
            LambdaQueryWrapper<WeatherDailyDataEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.apply("MONTH(observe_date) = {0} AND DAY(observe_date) = {1}", month, day);

            List<WeatherDailyDataEntity> list = weatherDailyDataDao.selectSummarizeList(wrapper);

            Map<String, List<DailyWeatherSummarizeDto>> grouped = list.stream()
                    .map(e -> BeanUtil.copyProperties(e, DailyWeatherSummarizeDto.class))
                    .collect(Collectors.groupingBy(dto -> String.valueOf(dto.getStationId())));

            String key = RedisKeys.getWeatherSummarizeKey(month, day);
            redisUtils.set(key, grouped, RedisUtils.HOUR_SIX_EXPIRE);

            log.info("天气汇总缓存刷新完成，共 {} 条记录，{} 个站点", list.size(), grouped.size());
        } catch (Exception e) {
            log.error("天气汇总缓存刷新失败", e);
        }
    }
}
