package com.goldenwater.web.controller.yjjt;

import com.goldenwater.common.core.controller.BaseController;
import com.goldenwater.common.core.domain.AjaxResult;
import com.goldenwater.common.utils.DateUtils;
import com.goldenwater.common.utils.StringUtils;
import com.goldenwater.yjjt.domain.YjjtDailyStatistics;
import com.goldenwater.yjjt.domain.YjjtStatisticsDTO;
import com.goldenwater.yjjt.domain.YjjtYearlyDataStatistics;
import com.goldenwater.yjjt.service.IYjjtStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
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 jakarta.annotation.Resource;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 引江济太数据统计Controller
 */
@RestController
@RequestMapping("/yjjt/statistics")
@Tag(name = "引江济太数据统计", description = "引江济太数据统计接口")
public class YjjtStatisticsController extends BaseController {

    @Resource
    private IYjjtStatisticsService yjjtStatisticsService;

    /**
     * 获取实时统计（今日/本周/本月合并）
     */
    @GetMapping("/realtime")
    @Operation(summary = "实时统计", description = "获取江苏、无锡、上海今日/本周/本月上报数据条数")
    @PreAuthorize("@ss.hasPermi('yjjtgl:statistics:list')")
    public AjaxResult getRealtimeStatistics() {
        Map<String, Object> result = new HashMap<>();

        List<YjjtDailyStatistics> todayList = yjjtStatisticsService.getDailyStatistics();
        List<YjjtDailyStatistics> weekList = yjjtStatisticsService.getWeeklyStatistics();
        List<YjjtDailyStatistics> monthList = yjjtStatisticsService.getMonthlyStatistics();

        List<Map<String, Object>> units = List.of(
                buildUnitStat("无锡", "WX", todayList, weekList, monthList),
                buildUnitStat("江苏", "JS", todayList, weekList, monthList),
                buildUnitStat("上海", "SH", todayList, weekList, monthList)
        );

        result.put("units", units);
        return AjaxResult.success(result);
    }

    private Map<String, Object> buildUnitStat(String unitName, String unitCode,
                                              List<YjjtDailyStatistics> todayList,
                                              List<YjjtDailyStatistics> weekList,
                                              List<YjjtDailyStatistics> monthList) {
        Map<String, Object> stat = new HashMap<>();
        stat.put("unitName", unitName);
        stat.put("unitCode", unitCode);
        stat.put("todayCount", findCount(todayList, unitCode, "todayCount"));
        stat.put("weekCount", findCount(weekList, unitCode, "weekCount"));
        stat.put("monthCount", findCount(monthList, unitCode, "monthCount"));
        return stat;
    }

    private Integer findCount(List<YjjtDailyStatistics> list, String unitCode, String field) {
        for (YjjtDailyStatistics item : list) {
            if (unitCode.equals(item.getUnitCode())) {
                if ("todayCount".equals(field)) return item.getTodayCount();
                if ("weekCount".equals(field)) return item.getWeekCount();
                if ("monthCount".equals(field)) return item.getMonthCount();
            }
        }
        return 0;
    }

    /**
     * 获取年度合计统计数据
     */
    @GetMapping("/yearly")
    @Operation(summary = "年度合计统计", description = "获取各年份各单位上报数据量和监测次数（水量+水质合计）")
    @PreAuthorize("@ss.hasPermi('yjjtgl:statistics:list')")
    public AjaxResult getYearlyStatistics(
            @Parameter(description = "年份（可选）") @RequestParam(value = "year", required = false) String year) {
        if (StringUtils.isEmpty(year)) {
            year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        }
        List<YjjtYearlyDataStatistics> list = yjjtStatisticsService.getYearlyStatistics(year);
        return AjaxResult.success(list);
    }

    /**
     * 获取年度水量统计数据
     */
    @GetMapping("/yearly/sl")
    @Operation(summary = "年度水量统计", description = "获取各年份各单位水量上报数据量和监测次数")
    @PreAuthorize("@ss.hasPermi('yjjtgl:statistics:list')")
    public AjaxResult getYearlySlStatistics(
            @Parameter(description = "年份（可选）") @RequestParam(value = "year", required = false) String year) {
        if (StringUtils.isEmpty(year)) {
            year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        }
        List<YjjtYearlyDataStatistics> list = yjjtStatisticsService.getYearlySlStatistics(year);
        return AjaxResult.success(list);
    }

    /**
     * 获取年度水质统计数据
     */
    @GetMapping("/yearly/sz")
    @Operation(summary = "年度水质统计", description = "获取各年份各单位水质上报数据量和监测次数")
    @PreAuthorize("@ss.hasPermi('yjjtgl:statistics:list')")
    public AjaxResult getYearlySzStatistics(
            @Parameter(description = "年份（可选）") @RequestParam(value = "year", required = false) String year) {
        if (StringUtils.isEmpty(year)) {
            year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        }
        List<YjjtYearlyDataStatistics> list = yjjtStatisticsService.getYearlySzStatistics(year);
        return AjaxResult.success(list);
    }

    /**
     * 获取单位历年统计数据
     */
    @GetMapping("/unit")
    @Operation(summary = "单位历年统计", description = "获取指定单位历年测站数量、监测次数、数据量")
    @PreAuthorize("@ss.hasPermi('yjjtgl:statistics:list')")
    public AjaxResult getUnitStatistics(
            @Parameter(description = "单位编码(WX/JS/SH)") @RequestParam("unitCode") String unitCode) {

        List<YjjtStatisticsDTO> dataStats = yjjtStatisticsService.getUnitYearlyStatistics(unitCode);
        List<YjjtStatisticsDTO> stationStats = yjjtStatisticsService.getStationCountByYear(unitCode);

        Map<String, YjjtStatisticsDTO> dataMap = dataStats.stream()
                .collect(Collectors.toMap(YjjtStatisticsDTO::getYear, s -> s));

        Map<String, YjjtStatisticsDTO> stationMap = stationStats.stream()
                .collect(Collectors.toMap(YjjtStatisticsDTO::getYear, s -> s));

        List<Map<String, Object>> result = dataMap.keySet().stream()
                .sorted((a, b) -> b.compareTo(a))
                .map(year -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("year", year);

                    YjjtStatisticsDTO data = dataMap.get(year);
                    if (data != null) {
                        item.put("dataCount", data.getDataCount());
                        item.put("monitorCount", data.getMonitorCount());
                    } else {
                        item.put("dataCount", 0);
                        item.put("monitorCount", 0);
                    }

                    YjjtStatisticsDTO station = stationMap.get(year);
                    if (station != null) {
                        item.put("stationCount", station.getStationCount());
                    } else {
                        item.put("stationCount", 0);
                    }

                    return item;
                })
                .collect(Collectors.toList());

        return AjaxResult.success(result);
    }
}
