package com.zksy.web.controller.drainage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.WaterSupply.WaterPumpStation.domain.WaterPumpStation;
import com.zksy.WaterSupply.WaterPumpStation.service.IWaterPumpStationService;
import com.zksy.common.annotation.Anonymous;
import com.zksy.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 排水系统-泵站数据接口
 */
@Anonymous
@RestController
@RequestMapping("/api/drainage/pumpStation")
@Api(tags = "排水系统-泵站数据接口")
public class DrainagePumpStationController {

    @Autowired
    private IWaterPumpStationService waterPumpStationService;

    /**
     * 分页查询泵站列表
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询泵站列表")
    public AjaxResult page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("泵站名称") @RequestParam(required = false) String stationName,
            @ApiParam("泵站编号") @RequestParam(required = false) String stationCode,
            @ApiParam("运行状态") @RequestParam(required = false) String status) {

        Page<WaterPumpStation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<WaterPumpStation> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(stationName)) {
            wrapper.like(WaterPumpStation::getStationName, stationName);
        }
        if (StringUtils.hasText(stationCode)) {
            wrapper.eq(WaterPumpStation::getStationCode, stationCode);
        }
        if (StringUtils.hasText(status)) {
            wrapper.eq(WaterPumpStation::getStatus, status);
        }
        wrapper.eq(WaterPumpStation::getDelFlag, "0");
        wrapper.orderByDesc(WaterPumpStation::getCreateTime);

        Page<WaterPumpStation> result = waterPumpStationService.page(page, wrapper);
        return AjaxResult.success(result);
    }

    /**
     * 查询所有泵站（不分页）
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询所有泵站列表（不分页）")
    public AjaxResult list(
            @ApiParam("泵站名称") @RequestParam(required = false) String stationName,
            @ApiParam("运行状态") @RequestParam(required = false) String status) {

        LambdaQueryWrapper<WaterPumpStation> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(stationName)) {
            wrapper.like(WaterPumpStation::getStationName, stationName);
        }
        if (StringUtils.hasText(status)) {
            wrapper.eq(WaterPumpStation::getStatus, status);
        }
        wrapper.eq(WaterPumpStation::getDelFlag, "0");
        wrapper.orderByDesc(WaterPumpStation::getCreateTime);

        List<WaterPumpStation> list = waterPumpStationService.list(wrapper);
        return AjaxResult.success(list);
    }

    /**
     * 根据ID查询泵站详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询泵站详情")
    public AjaxResult getById(@PathVariable Long id) {
        WaterPumpStation station = waterPumpStationService.getById(id);
        if (station == null) {
            return AjaxResult.error("泵站不存在");
        }
        return AjaxResult.success(station);
    }

    /**
     * 泵站月度统计（近三个月），按泵站ID列表查询
     * 返回每个月内已关联的泵站的设计流量和设计扬程汇总
     * sinceDate: 关联起始日期（yyyy-MM-dd），只统计该日期所在月份及之后的数据
     */
    @GetMapping("/monthlyStats")
    @ApiOperation(value = "泵站近三个月月度统计")
    public AjaxResult monthlyStats(
            @ApiParam("泵站ID列表，逗号分隔") @RequestParam String ids,
            @ApiParam("关联起始日期yyyy-MM-dd") @RequestParam(required = false) String sinceDate) {

        if (!StringUtils.hasText(ids)) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 解析ID列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 查询这些泵站
        List<WaterPumpStation> stations = waterPumpStationService.listByIds(idList);

        // 解析关联起始月份
        YearMonth sinceMonth = null;
        if (StringUtils.hasText(sinceDate)) {
            try {
                LocalDate sd = LocalDate.parse(sinceDate);
                sinceMonth = YearMonth.from(sd);
            } catch (Exception e) {
                // 忽略解析失败
            }
        }

        // 计算近三个月
        YearMonth now = YearMonth.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
        List<Map<String, Object>> result = new ArrayList<>();

        for (int i = 2; i >= 0; i--) {
            YearMonth ym = now.minusMonths(i);
            String month = ym.format(fmt);

            double totalFlow = 0;
            double totalHead = 0;
            int count = 0;

            // 如果指定了sinceDate，该月份早于sinceDate所在月则数据为0
            if (sinceMonth == null || !ym.isBefore(sinceMonth)) {
                for (WaterPumpStation s : stations) {
                    totalFlow += s.getDesignFlow() != null ? s.getDesignFlow().doubleValue() : 0;
                    totalHead += s.getDesignHead() != null ? s.getDesignHead().doubleValue() : 0;
                    count++;
                }
            }

            Map<String, Object> item = new LinkedHashMap<>();
            item.put("month", month);
            item.put("designFlow", totalFlow);
            item.put("designHead", totalHead);
            item.put("stationCount", count);
            result.add(item);
        }

        return AjaxResult.success(result);
    }
}
