package com.hdkj.lt.bf.scheduler;

import com.alibaba.fastjson.JSON;
import com.hdkj.fhzg.optimization.request.MaintOrgRequest;
import com.hdkj.hussar.ApiResponse;
import com.hdkj.lt.bf.adapter.SiStateEstimationClient;
import com.hdkj.lt.bf.common.SeSnapshotConstants;
import com.hdkj.lt.bf.service.SeSnapshotService;
import com.hdkj.lt.core.bizms.modle.dto.StateEstimation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 状估断面定时拉取任务
 * <p>
 * 每15分钟调用同事的 queryEquipByCounty 接口，按县域串行拉取最新状估数据，
 * 聚合后喂给 SeSnapshotService.processSnapshot() 解析入库，
 * 完成状估数据→断面明细→状态机监测→告警事件的完整链路。
 *
 * @author lsl
 * @since 2026-07-26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SeSnapshotScheduler {

    private final SiStateEstimationClient siStateEstimationClient;
    private final SeSnapshotService seSnapshotService;

    @Scheduled(cron = "0 */15 * * * ?")
    public void pullStateEstimation() {
        log.info("【状估拉取】开始串行拉取状估数据");

        for (Map.Entry<String, String[]> county : SeSnapshotConstants.COUNTIES) {
            String maintOrg = county.getKey();
            String countySid = county.getValue()[0];
            String countyName = county.getValue()[1];
            pullByCounty(maintOrg, countySid, countyName);
        }
    }

    private void pullByCounty(String maintOrg, String countySid, String countyName) {
        try {
            MaintOrgRequest request = new MaintOrgRequest();
            request.setMaintOrg(maintOrg);

            ApiResponse<List<StateEstimation>> resp = siStateEstimationClient.queryEquipByCounty(request);
            if (resp == null || !resp.isSuccess() || resp.getData() == null || resp.getData().isEmpty()) {
                log.warn("【状估拉取】县域 {} 无数据或调用失败, resp={}, msg={}",
                        countyName, resp != null ? resp.isSuccess() : "null",
                        resp != null ? resp.getMsg() : "");
                return;
            }

            StateEstimation merged = mergeCountyResults(resp.getData());
            if (merged == null) return;

            String json = JSON.toJSONString(merged);
            seSnapshotService.processSnapshot(json);

            log.info("【状估拉取】县域 {} 状估数据拉取解析完成, 断面时刻={}", countyName, merged.getPointTime());
        } catch (Exception e) {
            log.error("【状估拉取】县域 {} 拉取异常: {}", countyName, e.getMessage(), e);
        }
    }

    private StateEstimation mergeCountyResults(List<StateEstimation> list) {
        if (list == null || list.isEmpty()) return null;

        StateEstimation merged = new StateEstimation();
        List<StateEstimation.StateEstimationCommonResult> allFeeders = new ArrayList<>();
        List<StateEstimation.StateEstimationTransResult> allMvtrans = new ArrayList<>();
        List<StateEstimation.StateEstimationSwitchResult> allSwitches = new ArrayList<>();
        List<StateEstimation.StateEstimationCommonResult> allEquips = new ArrayList<>();
        List<StateEstimation.StateEstimationSegmentResult> allSegments = new ArrayList<>();
        List<String> pointTime = null;

        for (StateEstimation se : list) {
            if (se == null) continue;
            if (pointTime == null && se.getPointTime() != null) pointTime = se.getPointTime();
            if (se.getPeriodFeederSeResult() != null) allFeeders.addAll(se.getPeriodFeederSeResult());
            if (se.getPeriodMVTransSeResult() != null) allMvtrans.addAll(se.getPeriodMVTransSeResult());
            if (se.getPeriodSwitchSeResult() != null) allSwitches.addAll(se.getPeriodSwitchSeResult());
            if (se.getPeriodEquipResult() != null) allEquips.addAll(se.getPeriodEquipResult());
            if (se.getPeriodSegmentSeResult() != null) allSegments.addAll(se.getPeriodSegmentSeResult());
        }

        if (allFeeders.isEmpty() && allMvtrans.isEmpty()) {
            log.warn("【状估拉取】聚合后无任何数据");
            return null;
        }

        merged.setPeriodFeederSeResult(allFeeders);
        merged.setPeriodMVTransSeResult(allMvtrans);
        merged.setPeriodSwitchSeResult(allSwitches);
        merged.setPeriodEquipResult(allEquips);
        merged.setPeriodSegmentSeResult(allSegments);
        merged.setPointTime(pointTime);
        return merged;
    }
}
