package com.hdkj.lt.bf.scheduler;

import com.hdkj.lt.base.constants.RedisKeyConstants;
import com.hdkj.lt.base.constants.RocketMQConstants;
import com.hdkj.lt.core.mq.client.RocketMQTemplate;
import com.hdkj.lt.core.mq.model.RocketMQMessageEntity;
import com.hdkj.lt.modle.dto.indicator.IndicatorCalcMessage;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 指标计算定时调度器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IndicatorScheduler {

    private final RocketMQTemplate rocketMQTemplate;

    /**
     * 每15分钟触发一次指标计算
     */
    //@Scheduled(cron = "0 */15 * * * ?")
    public void executeIndicatorCalc() {
        String batchId = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        log.info("指标计算定时任务启动, batchId: {}", batchId);

        List<CountyInfo> countyList = getCountyList();
        for (CountyInfo county : countyList) {
            try {
                IndicatorCalcMessage message = new IndicatorCalcMessage();
                message.setBatchId(batchId);
                message.setCountyId(county.getId());
                message.setCountySid(county.getSid());
                message.setCountyName(county.getName());

                RocketMQMessageEntity messageEntity = RocketMQMessageEntity.builder()
                        .topicId(RocketMQConstants.TOPIC_ID_INDICATOR_CALC)
                        .cacheKey(RedisKeyConstants.ASYNC_QUEUE_INDICATOR_CALC)
                        .tag(county.getSid())
                        .body(message)
                        .build();
                rocketMQTemplate.sendAsyncMessage(messageEntity);
                log.info("发送指标计算消息成功, countySid: {}, batchId: {}", county.getSid(), batchId);
            } catch (Exception e) {
                log.error("发送指标计算消息失败, countySid: {}, batchId: {}", county.getSid(), batchId, e);
            }
        }
        log.info("指标计算定时任务结束, batchId: {}", batchId);
    }

    /**
     * 获取区县列表 (TODO 待实现)
     *
     * @return 区县列表
     */
    private List<CountyInfo> getCountyList() {
        // TODO 待实现：从数据库或其他数据源获取区县列表
        return new ArrayList<>();
    }

    /**
     * 区县信息
     */
    @Getter
    public static class CountyInfo {
        private Integer id;
        private String sid;
        private String name;

        public CountyInfo(Integer id, String sid, String name) {
            this.id = id;
            this.sid = sid;
            this.name = name;
        }
    }
}
