package cn.iocoder.yudao.module.config.task;

import cn.iocoder.yudao.module.config.entity.ReminderMessage;
import cn.iocoder.yudao.module.config.service.ReminderHandler;
import cn.iocoder.yudao.module.config.service.RedisDelayedQueueService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class AppointmentReminderTask {

    @Autowired
    private RedisDelayedQueueService queueService;

    @Autowired
    private ReminderHandler reminderHandler;

    @Scheduled(fixedRate = 60_000)
    public void checkReminderQueue() {
        long now = System.currentTimeMillis();
        Set<String> dueMessages = queueService.fetchDueMessages(now);

        for (String json : dueMessages) {
            try {
                ReminderMessage message = new ObjectMapper().readValue(json, ReminderMessage.class);

                // 执行提醒
                reminderHandler.handleReminder(message);
                log.info("处理提醒成功：{}", message);

                // 移除已处理任务
                queueService.removeMessage(json);
            } catch (Exception e) {
                log.error("解析或处理提醒失败", e);
            }
        }
    }
}

