package com.usky.vpp.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.vpp.domain.VppDrEvent;
import com.usky.vpp.domain.VppDrEvaluation;
import com.usky.vpp.domain.VppDrStrategy;
import com.usky.vpp.service.VppDrInvitationService;
import com.usky.vpp.service.VppDrService;
import com.usky.vpp.service.VppDrSubsidyPredictionService;
import com.usky.vpp.service.VppResponseDeviationPriceService;
import com.usky.vpp.service.vo.DrClearingRequest;
import com.usky.vpp.service.vo.DrEventDetailVO;
import com.usky.vpp.service.vo.DrEventRequest;
import com.usky.vpp.service.vo.DrEventStatusRequest;
import com.usky.vpp.service.vo.DrInterveneRequest;
import com.usky.vpp.service.vo.DrInvitationNotifyRequest;
import com.usky.vpp.service.vo.DrInvitationReplyRequest;
import com.usky.vpp.service.vo.DrInvitationRequest;
import com.usky.vpp.service.vo.DrInvitationVO;
import com.usky.vpp.service.vo.DrParticipateRequest;
import com.usky.vpp.service.vo.DrStrategyRequest;
import com.usky.vpp.service.vo.DrStrategyVO;
import com.usky.vpp.service.vo.DrSubsidyPredictionCalculateRequest;
import com.usky.vpp.service.vo.DrSubsidyPredictionRequest;
import com.usky.vpp.service.vo.DrSubsidyPredictionVO;
import com.usky.vpp.service.vo.ResponseDeviationPriceAdjustmentRequest;
import com.usky.vpp.service.vo.ResponseDeviationPriceAdjustmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 需求响应接口
 * 网关前缀: /prod-api/service-vpp/dr
 */
@RestController
@RequestMapping("/dr")
public class DrController {

    @Autowired
    private VppDrService vppDrService;
    @Autowired
    private VppDrInvitationService vppDrInvitationService;
    @Autowired
    private VppDrSubsidyPredictionService vppDrSubsidyPredictionService;
    @Autowired
    private VppResponseDeviationPriceService responseDeviationPriceService;

    @GetMapping(value = "/event")
    public ApiResult<CommonPage<VppDrEvent>> pageEvent(@RequestParam(required = false) Map<String, Object> params) {
        return ApiResult.success(vppDrService.pageEvent(params));
    }

    /**
     * 修改事件状态（独立接口，不修改事件其它字段）。
     * <p>校验租户后，仅允许从 0待参与 改为 1已申报。</p>
     * <p>事件状态：0待参与 1已申报 2申报完成 3执行中 4已结束 5已取消</p>
     */
    @PutMapping(value = "/event/status")
    public ApiResult<Void> updateEventStatus(@RequestBody DrEventStatusRequest body) {
        vppDrService.updateEventStatus(body);
        return ApiResult.success();
    }

    @GetMapping(value = "/event/{id}")
    public ApiResult<DrEventDetailVO> getEvent(@PathVariable("id") Long id) {
        return ApiResult.success(vppDrService.getEvent(id));
    }

    @PostMapping(value = "/event")
    public ApiResult<VppDrEvent> createEvent(@RequestBody DrEventRequest body) {
        return ApiResult.success(vppDrService.createEvent(body));
    }

    @PutMapping(value = "/event/{id}")
    public ApiResult<Void> updateEvent(@PathVariable("id") Long id, @RequestBody DrEventRequest body) {
        vppDrService.updateEvent(id, body);
        return ApiResult.success();
    }

    @DeleteMapping(value = "/event/{id}")
    public ApiResult<Void> deleteEvent(@PathVariable("id") Long id) {
        vppDrService.deleteEvent(id);
        return ApiResult.success();
    }

    @GetMapping(value = "/event/{id}/capability")
    public ApiResult<Object> assessCapability(@PathVariable("id") Long id) {
        return ApiResult.success(vppDrService.assessCapability(id));
    }

    @PostMapping(value = "/event/{id}/participate")
    public ApiResult<Void> participate(@PathVariable("id") Long id, @RequestBody DrParticipateRequest body) {
        vppDrService.participate(id, body);
        return ApiResult.success();
    }

    @PostMapping(value = "/event/{id}/clearing")
    public ApiResult<Void> clearing(@PathVariable("id") Long id, @RequestBody DrClearingRequest body) {
        vppDrService.clearing(id, body);
        return ApiResult.success();
    }

    @GetMapping(value = "/event/{id}/monitor")
    public ApiResult<Object> monitorExecution(@PathVariable("id") Long id) {
        return ApiResult.success(vppDrService.monitorExecution(id));
    }

    @PostMapping(value = "/event/{id}/intervene")
    public ApiResult<Void> intervene(@PathVariable("id") Long id, @RequestBody DrInterveneRequest body) {
        vppDrService.intervene(id, body);
        return ApiResult.success();
    }

    @PostMapping(value = "/event/{id}/ack-clearing")
    public ApiResult<Void> acknowledgeClearing(@PathVariable("id") Long id) {
        vppDrService.acknowledgeClearing(id);
        return ApiResult.success();
    }

    @PostMapping(value = "/event/{id}/complete")
    public ApiResult<Void> completeEvent(@PathVariable("id") Long id) {
        vppDrService.completeEvent(id);
        return ApiResult.success();
    }

    @GetMapping(value = "/event/{id}/evaluation")
    public ApiResult<VppDrEvaluation> getEvaluation(@PathVariable("id") Long id) {
        return ApiResult.success(vppDrService.getEvaluation(id));
    }

    @GetMapping(value = "/strategy")
    public ApiResult<CommonPage<VppDrStrategy>> pageStrategy(@RequestParam(required = false) Map<String, Object> params) {
        return ApiResult.success(vppDrService.pageStrategy(params));
    }

    @GetMapping(value = "/strategy/{id}")
    public ApiResult<DrStrategyVO> getStrategy(@PathVariable("id") Long id) {
        return ApiResult.success(vppDrService.getStrategy(id));
    }

    @PostMapping(value = "/strategy")
    public ApiResult<VppDrStrategy> createStrategy(@RequestBody DrStrategyRequest body) {
        return ApiResult.success(vppDrService.createStrategy(body));
    }

    @PutMapping(value = "/strategy/{id}")
    public ApiResult<Void> updateStrategy(@PathVariable("id") Long id, @RequestBody DrStrategyRequest body) {
        vppDrService.updateStrategy(id, body);
        return ApiResult.success();
    }

    @DeleteMapping(value = "/strategy/{id}")
    public ApiResult<Void> deleteStrategy(@PathVariable("id") Long id) {
        vppDrService.deleteStrategy(id);
        return ApiResult.success();
    }

    /**
     * 邀约响应状态：0待参与 1已申报 2申报完成 3执行中 4已结束 5已取消（与事件状态一致）
     */
    @GetMapping(value = "/invitation")
    public ApiResult<CommonPage<DrInvitationVO>> pageInvitation(@RequestParam(required = false) Map<String, Object> params) {
        return ApiResult.success(vppDrInvitationService.pageInvitation(params));
    }

    @GetMapping(value = "/invitation/{id}")
    public ApiResult<DrInvitationVO> getInvitation(@PathVariable("id") Long id) {
        return ApiResult.success(vppDrInvitationService.getInvitation(id));
    }

    @PostMapping(value = "/invitation")
    public ApiResult<DrInvitationVO> createInvitation(@RequestBody DrInvitationRequest body) {
        return ApiResult.success(vppDrInvitationService.createInvitation(body));
    }

    @PutMapping(value = "/invitation/{id}")
    public ApiResult<Void> updateInvitation(@PathVariable("id") Long id, @RequestBody DrInvitationRequest body) {
        vppDrInvitationService.updateInvitation(id, body);
        return ApiResult.success();
    }

    @DeleteMapping(value = "/invitation/{id}")
    public ApiResult<Void> deleteInvitation(@PathVariable("id") Long id) {
        vppDrInvitationService.deleteInvitation(id);
        return ApiResult.success();
    }

    @PostMapping(value = "/invitation/{id}/notify-sms")
    public ApiResult<DrInvitationVO> notifyInvitationSms(@PathVariable("id") Long id,
                                                         @RequestBody(required = false) DrInvitationNotifyRequest body) {
        return ApiResult.success(vppDrInvitationService.notifySms(id, body));
    }

    @PostMapping(value = "/invitation/{id}/reply")
    public ApiResult<DrInvitationVO> replyInvitation(@PathVariable("id") Long id,
                                                       @RequestBody DrInvitationReplyRequest body) {
        return ApiResult.success(vppDrInvitationService.replyInvitation(id, body));
    }

    // ==================== 补贴金额预测 ====================

    /**
     * 分页查询补贴金额预测
     * siteName     站点名称（模糊匹配）
     * customerName 企业名称（模糊匹配）
     * startTime    响应开始时间起始
     * endTime      响应开始时间截止
     * current      页码
     * size         页大小
     */
    @GetMapping(value = "/subsidyPrediction")
    public ApiResult<CommonPage<DrSubsidyPredictionVO>> pageSubsidyPrediction(
            @RequestParam(value = "siteName", required = false) String siteName,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(vppDrSubsidyPredictionService.page(
                siteName, customerName, startTime, endTime, current, size));
    }

    /**
     * 试算补贴金额预测（不落库）。
     * <p>入参：邀约编号、实际响应容量（电网）；其余计算字段由服务端按邀约/事件查询。
     * 前端拿到结果后再调用新增接口入库。</p>
     */
    @PostMapping(value = "/subsidyPrediction/calculate")
    public ApiResult<DrSubsidyPredictionVO> calculateSubsidyPrediction(
            @RequestBody DrSubsidyPredictionCalculateRequest request) {
        return ApiResult.success(vppDrSubsidyPredictionService.calculate(request));
    }

    /**
     * 新增补贴金额预测。
     * <p>按前端传参直接入库（通常携带试算结果），服务端不再重算。</p>
     */
    @PostMapping(value = "/subsidyPrediction")
    public ApiResult<Boolean> createSubsidyPrediction(@RequestBody DrSubsidyPredictionRequest request) {
        return vppDrSubsidyPredictionService.create(request)
                ? ApiResult.success(true) : ApiResult.error("新增补贴预测失败！请重试！");
    }

    /**
     * 修改补贴金额预测。
     * <p>按前端传参直接入库，服务端不再重算。</p>
     */
    @PutMapping(value = "/subsidyPrediction")
    public ApiResult<Boolean> updateSubsidyPrediction(@RequestBody DrSubsidyPredictionRequest request) {
        return vppDrSubsidyPredictionService.update(request)
                ? ApiResult.success(true) : ApiResult.error("修改补贴预测失败！请重试！");
    }

    /**
     * 删除补贴金额预测
     */
    @DeleteMapping(value = "/subsidyPrediction/{id}")
    public ApiResult<Boolean> deleteSubsidyPrediction(@PathVariable("id") Long id) {
        return vppDrSubsidyPredictionService.delete(id)
                ? ApiResult.success(true) : ApiResult.error("删除补贴预测失败！请重试！");
    }

    // ==================== 响应量偏差价格调整 ====================
    /**
     * 分页查询响应量偏差价格调整。
     * completionRate 可选，传入时按结构化区间匹配命中配置。
     * current   页码
     * size      页大小
     */
    @GetMapping(value = "/responseDeviationPrice")
    public ApiResult<CommonPage<ResponseDeviationPriceAdjustmentVO>> pageResponseDeviationPriceAdjustment(
            @RequestParam(value = "completionRate", required = false) BigDecimal completionRate,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(responseDeviationPriceService.page(completionRate, current, size));
    }

    @GetMapping(value = "/responseDeviationPrice/{id}")
    public ApiResult<ResponseDeviationPriceAdjustmentVO> getResponseDeviationPriceAdjustment(
            @PathVariable("id") Long id) {
        return ApiResult.success(responseDeviationPriceService.get(id));
    }

    @PostMapping(value = "/responseDeviationPrice")
    public ApiResult<Long> createResponseDeviationPriceAdjustment(
            @RequestBody ResponseDeviationPriceAdjustmentRequest request) {
        return ApiResult.success(responseDeviationPriceService.create(request));
    }

    @PutMapping(value = "/responseDeviationPrice/{id}")
    public ApiResult<Void> updateResponseDeviationPriceAdjustment(
            @PathVariable("id") Long id,
            @RequestBody ResponseDeviationPriceAdjustmentRequest request) {
        responseDeviationPriceService.update(id, request);
        return ApiResult.success();
    }

    @DeleteMapping(value = "/responseDeviationPrice/{id}")
    public ApiResult<Void> deleteResponseDeviationPriceAdjustment(@PathVariable("id") Long id) {
        responseDeviationPriceService.delete(id);
        return ApiResult.success();
    }
}
