package com.usky.vpp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.vpp.client.VppUnClient;
import com.usky.vpp.config.VppUnProperties;
import com.usky.vpp.domain.VppResourcePoint;
import com.usky.vpp.domain.VppSite;
import com.usky.vpp.mapper.VppResourcePointMapper;
import com.usky.vpp.service.VppUnReportService;
import com.usky.vpp.util.VppAuditHelper;
import com.usky.vpp.util.VppSiteResourceHelper;
import com.usky.vpp.util.VppUnMessageBuilder;
import com.usky.vpp.util.VppUnPayloadHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

@Service
public class VppUnReportServiceImpl implements VppUnReportService {

    private static final Logger log = LoggerFactory.getLogger(VppUnReportServiceImpl.class);

    @Autowired
    private VppUnProperties properties;
    @Autowired
    private VppUnClient unClient;
    @Autowired
    private VppResourcePointMapper resourcePointMapper;
    @Autowired
    private VppSiteResourceHelper siteResourceHelper;

    @Override
    public void handleCreateReportRequest(Map<String, Object> createReportRequest) {
        if (!properties.isOutboundActive()) {
            return;
        }
        String reportRequestId = resolveReportRequestId(createReportRequest);
        log.info("处理 UN CreateReportRequest reportRequestID={}", reportRequestId);

        Map<String, Object> ack = VppUnMessageBuilder.buildCreateReportResponse(createReportRequest, properties);
        unClient.post("CreateReportResponse", ack, true);

        if (!StringUtils.hasText(reportRequestId)) {
            return;
        }
        switch (reportRequestId) {
            case "MetaDataReport":
                submitRegisterReport();
                break;
            case "IntervalDataReport":
                submitIntervalDataReport(createReportRequest);
                break;
            case "MomentDataReport":
                submitMomentDataReport(createReportRequest);
                break;
            default:
                log.info("暂不支持的报告类型: {}", reportRequestId);
                break;
        }
    }

    private void submitRegisterReport() {
        List<VppResourcePoint> resources = listActiveResources(false);
        Map<Long, VppSite> siteMap = siteResourceHelper.loadSiteMap(resources);
        Map<String, Object> request = VppUnMessageBuilder.buildRegisterReportRequest(resources, siteMap, properties);
        unClient.post("RegisterReportRequest", request, true);
        log.info("已提交 RegisterReportRequest");
    }

    private void submitIntervalDataReport(Map<String, Object> createReportRequest) {
        List<VppResourcePoint> resources = listActiveResources(true);
        Map<Long, VppSite> siteMap = siteResourceHelper.loadSiteMap(resources);
        Map<String, Object> request = VppUnMessageBuilder.buildIntervalDataReportRequest(
                createReportRequest, resources, siteMap, properties);
        unClient.post("IntervalDataReportRequest", request, true);
        log.info("已提交 IntervalDataReportRequest");
    }

    private void submitMomentDataReport(Map<String, Object> createReportRequest) {
        List<VppResourcePoint> resources = listActiveResources(true);
        Map<Long, VppSite> siteMap = siteResourceHelper.loadSiteMap(resources);
        Map<String, Object> request = VppUnMessageBuilder.buildMomentDataReportRequest(
                createReportRequest, resources, siteMap, properties);
        unClient.post("MomentDataReportRequest", request, true);
        log.info("已提交 MomentDataReportRequest");
    }

    private List<VppResourcePoint> listActiveResources(boolean controllableOnly) {
        LambdaQueryWrapper<VppResourcePoint> wrapper = new LambdaQueryWrapper<VppResourcePoint>()
                .eq(VppResourcePoint::getDeleteFlag, VppAuditHelper.NOT_DELETED)
                .orderByAsc(VppResourcePoint::getId);
        if (controllableOnly) {
            wrapper.eq(VppResourcePoint::getIsControl, 1);
        }
        return resourcePointMapper.selectList(wrapper);
    }

    @SuppressWarnings("unchecked")
    private String resolveReportRequestId(Map<String, Object> request) {
        String id = VppUnPayloadHelper.getString(request, "reportRequestID", "reportRequestId");
        if (StringUtils.hasText(id)) {
            return id;
        }
        Object reportRequest = request.get("reportRequest");
        if (reportRequest instanceof List && !((List<?>) reportRequest).isEmpty()) {
            Object first = ((List<?>) reportRequest).get(0);
            if (first instanceof Map) {
                return VppUnPayloadHelper.getString((Map<String, Object>) first,
                        "reportRequestID", "reportRequestId");
            }
        }
        return null;
    }
}
