package com.usky.vpp.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.vpp.service.VppDrMonitorService;
import com.usky.vpp.service.vo.DrMonitorCurveVO;
import com.usky.vpp.service.vo.DrMonitorRecordVO;
import com.usky.vpp.service.vo.DrMonitorSiteResourceVO;
import com.usky.vpp.service.vo.DrMonitorSummaryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 需求响应监测（响应记录）
 * <p>网关前缀: /prod-api/service-vpp/dr-monitor</p>
 */
@RestController
@RequestMapping("/drMonitor")
public class DrMonitorController {

    @Autowired
    private VppDrMonitorService drMonitorService;

    /**
     * 顶部 KPI：响应次数 / 响应容量(kW) / 历史达标率
     * <p>时间区间内事件开始、结束均落在区间且状态为执行中/已结束，再关联参与且执行中/已结束的邀约。</p>
     */
    @GetMapping("/summary")
    public ApiResult<DrMonitorSummaryVO> summary(@RequestParam("startDate") String startDate,
                                                 @RequestParam("endDate") String endDate,
                                                 @RequestParam("siteIds") List<Long> siteIds) {
        return ApiResult.success(drMonitorService.getSummary(startDate, endDate, siteIds));
    }

    /**
     * 响应记录分页（口径与 summary 一致，按邀约展开）
     * <p>在事件字段基础上补充客户、站点；预估响应容量/预估完成率/实际出清取自邀约，并计算补贴金额预测。</p>
     */
    @GetMapping("/records")
    public ApiResult<CommonPage<DrMonitorRecordVO>> records(@RequestParam("startDate") String startDate,
                                                            @RequestParam("endDate") String endDate,
                                                            @RequestParam("siteIds") List<Long> siteIds,
                                                            @RequestParam(required = false) Map<String, Object> params) {
        return ApiResult.success(drMonitorService.pageRecords(startDate, endDate, siteIds, params));
    }

    /**
     * 折线图：基线负荷 + 实际负荷 + 实际响应容量
     * <p>id 为邀约表主键；时间范围为响应开始前 2 小时至响应结束后 1 小时零 1 分钟。</p>
     */
    @GetMapping("/records/curve")
    public ApiResult<DrMonitorCurveVO> curve(@RequestParam("id") Long id) {
        return ApiResult.success(drMonitorService.getCurve(id));
    }

    /**
     * 按响应事件查询邀约站点及其可调峰资源点
     * <p>id 为 vpp_dr_event 主键；先查事件下全部邀约站点（去重），再查各站点 is_support_peak=1 的资源点，按站点分组返回。</p>
     */
    @GetMapping("/site-resources")
    public ApiResult<List<DrMonitorSiteResourceVO>> siteResources(@RequestParam("id") Long id) {
        return ApiResult.success(drMonitorService.listEventSitePeakResources(id));
    }
}
