package com.zksy.web.controller.WaterSupply.PipeNetworkStatistics;

import com.zksy.WaterSupply.PipeNetworkStatistics.dto.PipeNetworkStatisticsDashboardDTO;
import com.zksy.WaterSupply.PipeNetworkStatistics.service.PipeNetworkStatisticsExportService;
import com.zksy.WaterSupply.PipeNetworkStatistics.service.PipeNetworkStatisticsService;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/waterSupply/pipeNetwork/statistics")
@Api(tags = "供水管网-管网数据统计分析")
public class PipeNetworkStatisticsController {
    @Resource private PipeNetworkStatisticsService statisticsService;
    @Resource private PipeNetworkStatisticsExportService exportService;

    @GetMapping("/dashboard")
    @ApiOperation(value = "供水管网-管网数据统计分析-综合统计仪表盘",
            notes = "请求参数为可选查询条件。响应 data 包含 facilityOverview、pipeNetwork、waterPlant、pumpStation、waterSource、waterUser 六个区块；分组项结构为 {name, value, unit}。")
    @PreAuthorize("@ss.hasPermi('waterSupply:pipeNetwork:statistics')")
    public AjaxResult dashboard(
            @ApiParam(value = "设施状态：0正常、1/2异常；不传查询全部", example = "0")
            @RequestParam(required = false) String status,
            @ApiParam(value = "设施类型，逗号分隔：source、plant、pumpStation、pipe、user；不传查询全部", example = "plant,pipe")
            @RequestParam(required = false) String facilityTypes) {
        try {
            validateStatus(status);
            return AjaxResult.success(statisticsService.getDashboard(status, parseTypes(facilityTypes)));
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/export")
    @ApiOperation(value = "供水管网-管网数据统计分析-导出统计 Excel",
            notes = "请求参数与综合统计仪表盘一致。响应为文件流，文件名为管网数据统计分析.xlsx，包含综合概览、管网统计、水厂统计、泵站统计、水源地统计、大用水户统计六个工作表。")
    @Log(title = "管网数据统计分析", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('waterSupply:pipeNetwork:statistics:export')")
    public void export(HttpServletResponse response,
                       @ApiParam(value = "设施状态：0正常、1/2异常；不传查询全部", example = "0")
                       @RequestParam(required = false) String status,
                       @ApiParam(value = "设施类型，逗号分隔：source、plant、pumpStation、pipe、user；不传查询全部", example = "source,user")
                       @RequestParam(required = false) String facilityTypes) throws IOException {
        validateStatus(status);
        PipeNetworkStatisticsDashboardDTO dashboard = statisticsService.getDashboard(status, parseTypes(facilityTypes));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("管网数据统计分析.xlsx", StandardCharsets.UTF_8.name()));
        exportService.write(response.getOutputStream(), dashboard);
    }

    private Set<String> parseTypes(String text) {
        if (text == null || text.trim().isEmpty()) return Collections.emptySet();
        return Arrays.stream(text.split(",")).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toSet());
    }

    private void validateStatus(String status) {
        if (status != null && !status.isEmpty() && !"0".equals(status) && !"1".equals(status) && !"2".equals(status)) throw new IllegalArgumentException("无效的设施状态：" + status);
    }
}
