package com.hdkj.lt.si.schedule;

import com.hdkj.lt.si.service.staticgrid.StaticIndicatorResultService;
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.Map;

/**
 * 静态网架指标月度定时任务
 * <p>
 * 每月1号凌晨2点触发，遍历所有区县调用算法服务，解析并入库。
 * 区县列表见 {@link StaticGridScheduleConstants#COUNTIES}。
 *
 * @author lsl
 * @since 2026-07-25
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StaticGridIndicatorScheduler {

    private final StaticIndicatorResultService staticIndicatorResultService;

    /**
     * 每月1号凌晨2点触发：遍历所有区县，逐个调用静态网架评估接口
     */
    @Scheduled(cron = "0 0 2 1 * ?")
    public void scheduledTrigger() {
        log.info("静态网架月度定时任务开始, topologyVersion={}", StaticGridScheduleConstants.TOPOLOGY_VERSION);

        if (StaticGridScheduleConstants.COUNTIES.isEmpty()) {
            log.warn("StaticGridScheduleConstants.COUNTIES 为空，跳过定时任务");
            return;
        }

        String batchId = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));

        for (Map.Entry<String, String[]> entry : StaticGridScheduleConstants.COUNTIES) {
            String countyId = entry.getKey();
            String countySid = entry.getValue()[0];
            String countyName = entry.getValue()[1];

            try {
                log.info("开始处理区县: countyId={}, countySid={}, countyName={}", countyId, countySid, countyName);
                Long resultId = staticIndicatorResultService.saveStaticGridResult(
                        batchId, countyId, countySid, countyName,
                        StaticGridScheduleConstants.TOPOLOGY_VERSION);
                log.info("区县处理完成: countyId={}, resultId={}", countyId, resultId);
            } catch (Exception e) {
                log.error("区县处理失败: countyId={}, error={}", countyId, e.getMessage(), e);
            }
        }

        log.info("静态网架月度定时任务结束");
    }
}
