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.VppContractService;
import com.usky.vpp.service.VppContractTemplateService;
import com.usky.vpp.service.vo.VppContractExpireStatVO;
import com.usky.vpp.service.vo.VppContractOverviewVO;
import com.usky.vpp.service.vo.VppContractRequestVO;
import com.usky.vpp.service.vo.VppContractResponseVO;
import com.usky.vpp.service.vo.VppContractTemplateRequestVO;
import com.usky.vpp.service.vo.VppContractTemplateResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;

/**
 * 虚拟电厂 - Contract 接口
 * 网关前缀: /prod-api/service-vpp
 */
@RestController
@RequestMapping("/contract")
public class ContractController {

    @Autowired
    private VppContractTemplateService vppContractTemplateService;
    @Autowired
    private VppContractService vppContractService;

    // ==================== 合同模板 ====================

    /**
     * 新增合同模板
     */
    @PostMapping("/template")
    public ApiResult<Boolean> createTemplate(@RequestBody VppContractTemplateRequestVO vo) {
        return vppContractTemplateService.create(vo) ? ApiResult.success(true) : ApiResult.error("新增合同模板失败！请重试！");
    }

    /**
     * 修改合同模板
     */
    @PutMapping("/template")
    public ApiResult<Boolean> updateTemplate(@RequestBody VppContractTemplateRequestVO vo) {
        return vppContractTemplateService.update(vo) ? ApiResult.success(true) : ApiResult.error("修改或启用合同模板失败！请重试！");
    }

    /**
     * 分页查询合同模板
     * id           主键ID 精确匹配
     * templateName 模板名称 模糊匹配
     * contractType 合同类型
     * isEnabled    是否启用 0-禁用 1-启用
     * current      页码
     * size         页大小
     */
    @GetMapping("/template")
    public ApiResult<CommonPage<VppContractTemplateResponseVO>> pageTemplate(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "templateName", required = false) String templateName,
            @RequestParam(value = "contractType", required = false) Integer contractType,
            @RequestParam(value = "isEnabled", required = false) Integer isEnabled,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(vppContractTemplateService.page(id, templateName, contractType, isEnabled, current, size));
    }

    /**
     * 删除合同模板（软删除）
     */
    @DeleteMapping("/template/{id}")
    public ApiResult<Boolean> deleteTemplate(@PathVariable("id") Long id) {
        return vppContractTemplateService.delete(id) ? ApiResult.success(true) : ApiResult.error("删除合同模板失败！请重试！");
    }

    /**
     * 下载合同模板文件（单个文件流下载，不打包）
     */
    @GetMapping("/template/{id}/download")
    public void downloadTemplate(@PathVariable("id") Long id, HttpServletResponse response) {
        vppContractTemplateService.download(id, response);
    }

    // ==================== 合同 ====================

    /**
     * 新增合同
     * <p>合同状态根据生效/到期日期自动计算，无需手动传入生命周期状态。</p>
     */
    @PostMapping
    public ApiResult<Boolean> create(@RequestBody VppContractRequestVO vo) {
        return vppContractService.create(vo) ? ApiResult.success(true) : ApiResult.error("新增合同失败！请重试！");
    }

    /**
     * 修改合同
     * <p>合同状态根据生效/到期日期自动计算：未到生效时间为待生效，已过生效时间为已生效，已过到期时间为已到期；
     * 草稿、审核中、已驳回、已终止状态不受日期影响。</p>
     */
    @PutMapping
    public ApiResult<Boolean> update(@RequestBody VppContractRequestVO vo) {
        return vppContractService.update(vo) ? ApiResult.success(true) : ApiResult.error("修改合同失败！请重试！");
    }

    /**
     * 分页查询合同
     * id             主键ID 精确匹配
     * signDateStart  签约日期起始
     * signDateEnd    签约日期截止
     * templateId     模板ID
     * contractType   合同类型
     * customerId     客户ID
     * customerName   客户名称 模糊匹配
     * signDateStart  签订时间起始
     * signDateEnd    签订时间截止
     * contractStatus 合同状态 0草稿 1审核中 2待生效 3已生效 4已驳回 5已到期 6已终止 7即将到期（三月内过期）
     * current        页码
     * size           页大小
     */
    @GetMapping
    public ApiResult<CommonPage<VppContractResponseVO>> page(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(value = "templateId", required = false) Long templateId,
            @RequestParam(value = "contractType", required = false) Integer contractType,
            @RequestParam(value = "customerId", required = false) Long customerId,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "signDateStart", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate signDateStart,
            @RequestParam(value = "signDateEnd", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate signDateEnd,
            @RequestParam(value = "contractStatus", required = false) Integer contractStatus,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(vppContractService.page(id, startDate, endDate,
                templateId, contractType, customerId, customerName, signDateStart, signDateEnd, contractStatus, current, size));
    }

    /**
     * 按客户最新合同统计已到期 / 即将到期数量
     * <p>租户隔离；每个客户仅取创建时间最新的一份合同，返回已到期、即将到期（近三个月）两类数量。
     * 列表请调用分页接口：contractStatus=5 查已到期，contractStatus=7 查即将到期。</p>
     */
    @GetMapping("/expireStat")
    public ApiResult<VppContractExpireStatVO> expireStat() {
        return ApiResult.success(vppContractService.expireStat());
    }

    /**
     * 合同概况（甲方、乙方、签订日期、合同金额、起止时间、生效状态）
     */
    @GetMapping("/{id}/overview")
    public ApiResult<VppContractOverviewVO> overview(@PathVariable("id") Long id) {
        return ApiResult.success(vppContractService.overview(id));
    }

    /**
     * 删除合同（软删除）
     */
    @DeleteMapping("/{id}")
    public ApiResult<Boolean> delete(@PathVariable("id") Long id) {
        return vppContractService.delete(id) ? ApiResult.success(true) : ApiResult.error("删除合同失败！请重试！");
    }

    /**
     * 下载合同文件（单个文件流下载，不打包）
     */
    @GetMapping("/{id}/download")
    public void download(@PathVariable("id") Long id, HttpServletResponse response) {
        vppContractService.download(id, response);
    }
}
