package com.ruoyi.web.modules.prosperity.support;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityAchievement;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementAnnualReportVo;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementAnnualSummaryVo;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementMonthlyVo;

/**
 * 年度报告数据组装与汇总计算（纯逻辑，便于单测）。
 */
public final class AchievementReportAggregator
{
    private static final int MONTHS_IN_YEAR = 12;

    private static final int RATE_SCALE = 4;

    private AchievementReportAggregator()
    {
    }

    public static int parseMonthFromStatPeriod(String statPeriod)
    {
        if (StringUtils.isEmpty(statPeriod) || statPeriod.length() < 7)
        {
            return -1;
        }
        try
        {
            return Integer.parseInt(statPeriod.substring(5, 7));
        }
        catch (NumberFormatException ex)
        {
            return -1;
        }
    }

    public static AchievementAnnualReportVo buildReport(int statYear, List<BizCommonProsperityAchievement> rows)
    {
        AchievementAnnualReportVo report = new AchievementAnnualReportVo();
        report.setStatYear(statYear);
        boolean hasData = rows != null && !rows.isEmpty();
        report.setHasData(hasData);
        List<AchievementMonthlyVo> monthly = buildMonthly(statYear, rows);
        report.setMonthly(monthly);
        report.setSummary(hasData ? calcSummary(monthly) : null);
        return report;
    }

    public static List<AchievementMonthlyVo> buildMonthly(int statYear, List<BizCommonProsperityAchievement> rows)
    {
        Map<Integer, BizCommonProsperityAchievement> byMonth = new HashMap<>();
        if (rows != null)
        {
            for (BizCommonProsperityAchievement row : rows)
            {
                if (row == null || StringUtils.isEmpty(row.getStatPeriod()))
                {
                    continue;
                }
                if (!row.getStatPeriod().startsWith(String.valueOf(statYear) + "-"))
                {
                    continue;
                }
                int month = parseMonthFromStatPeriod(row.getStatPeriod());
                if (month >= 1 && month <= 12)
                {
                    byMonth.put(month, row);
                }
            }
        }
        List<AchievementMonthlyVo> monthly = new ArrayList<>(MONTHS_IN_YEAR);
        for (int m = 1; m <= MONTHS_IN_YEAR; m++)
        {
            BizCommonProsperityAchievement src = byMonth.get(m);
            if (src != null)
            {
                monthly.add(fromEntity(m, src));
            }
            else
            {
                monthly.add(zeroMonthly(m, statYear));
            }
        }
        return monthly;
    }

    /**
     * 最近 12 个月成果序列（按时间升序，含 statYear、month、statPeriod）。
     */
    public static List<AchievementMonthlyVo> buildRollingMonthly(
            java.time.YearMonth anchor, List<BizCommonProsperityAchievement> rows)
    {
        Map<Integer, BizCommonProsperityAchievement> byYm = new HashMap<>();
        if (rows != null)
        {
            for (BizCommonProsperityAchievement row : rows)
            {
                if (row == null || StringUtils.isEmpty(row.getStatPeriod()) || row.getStatPeriod().length() < 7)
                {
                    continue;
                }
                try
                {
                    int year = Integer.parseInt(row.getStatPeriod().substring(0, 4));
                    int month = parseMonthFromStatPeriod(row.getStatPeriod());
                    if (month >= 1 && month <= 12)
                    {
                        byYm.put(com.ruoyi.web.modules.screen.support.HomeScreenSupport.yearMonthKey(
                                java.time.YearMonth.of(year, month)), row);
                    }
                }
                catch (NumberFormatException ignored)
                {
                    // skip invalid stat_period
                }
            }
        }
        List<AchievementMonthlyVo> monthly = new ArrayList<>(MONTHS_IN_YEAR);
        java.time.YearMonth start = anchor.minusMonths(11);
        for (int slot = 0; slot < MONTHS_IN_YEAR; slot++)
        {
            java.time.YearMonth ym = start.plusMonths(slot);
            int key = com.ruoyi.web.modules.screen.support.HomeScreenSupport.yearMonthKey(ym);
            BizCommonProsperityAchievement src = byYm.get(key);
            if (src != null)
            {
                monthly.add(fromEntity(ym.getMonthValue(), src));
            }
            else
            {
                monthly.add(zeroMonthly(ym.getMonthValue(), ym.getYear()));
            }
        }
        return monthly;
    }

    public static AchievementAnnualSummaryVo calcSummary(List<AchievementMonthlyVo> monthly)
    {
        AchievementAnnualSummaryVo summary = new AchievementAnnualSummaryVo();
        BigDecimal incomeSum = BigDecimal.ZERO;
        int employmentSum = 0;
        int jobsSum = 0;
        int envSum = 0;
        BigDecimal greenSum = BigDecimal.ZERO;
        int heritageSum = 0;
        int integrationSum = 0;
        int unitySum = 0;
        BigDecimal digitalSum = BigDecimal.ZERO;
        int brandCountSum = 0;
        BigDecimal premiumSum = BigDecimal.ZERO;

        for (AchievementMonthlyVo item : monthly)
        {
            incomeSum = incomeSum.add(nvl(item.getCollectiveEconomyIncome()));
            employmentSum += nvlInt(item.getEmploymentDrivenCount());
            jobsSum += nvlInt(item.getNewJobPositions());
            envSum += nvlInt(item.getEnvProjectCount());
            greenSum = greenSum.add(nvl(item.getNewGreenArea()));
            heritageSum += nvlInt(item.getCulturalHeritageCount());
            integrationSum += nvlInt(item.getEthnicIntegrationProjectCount());
            unitySum += nvlInt(item.getEthnicUnityActivityCount());
            digitalSum = digitalSum.add(nvl(item.getDigitalPlatformUsageRate()));
            brandCountSum += nvlInt(item.getRegionalPublicBrandCount());
            premiumSum = premiumSum.add(nvl(item.getBrandPremiumRate()));
        }

        summary.setCollectiveEconomyIncome(incomeSum.setScale(2, RoundingMode.HALF_UP));
        summary.setEmploymentDrivenCount(employmentSum);
        summary.setNewJobPositions(jobsSum);
        summary.setEnvProjectCount(envSum);
        summary.setNewGreenArea(greenSum.setScale(2, RoundingMode.HALF_UP));
        summary.setCulturalHeritageCount(heritageSum);
        summary.setEthnicIntegrationProjectCount(integrationSum);
        summary.setEthnicUnityActivityCount(unitySum);
        summary.setDigitalPlatformUsageRate(
                digitalSum.divide(BigDecimal.valueOf(MONTHS_IN_YEAR), RATE_SCALE, RoundingMode.HALF_UP));
        summary.setRegionalPublicBrandCount(brandCountSum);
        summary.setBrandPremiumRate(
                premiumSum.divide(BigDecimal.valueOf(MONTHS_IN_YEAR), RATE_SCALE, RoundingMode.HALF_UP));
        return summary;
    }

    private static AchievementMonthlyVo fromEntity(int month, BizCommonProsperityAchievement src)
    {
        AchievementMonthlyVo vo = new AchievementMonthlyVo();
        vo.setMonth(month);
        if (src.getStatPeriod() != null && src.getStatPeriod().length() >= 4)
        {
            try
            {
                vo.setStatYear(Integer.parseInt(src.getStatPeriod().substring(0, 4)));
            }
            catch (NumberFormatException ignored)
            {
                // leave statYear null
            }
        }
        vo.setStatPeriod(src.getStatPeriod());
        vo.setCollectiveEconomyIncome(src.getCollectiveEconomyIncome());
        vo.setEmploymentDrivenCount(src.getEmploymentDrivenCount());
        vo.setNewJobPositions(src.getNewJobPositions());
        vo.setEnvProjectCount(src.getEnvProjectCount());
        vo.setNewGreenArea(src.getNewGreenArea());
        vo.setCulturalHeritageCount(src.getCulturalHeritageCount());
        vo.setEthnicIntegrationProjectCount(src.getEthnicIntegrationProjectCount());
        vo.setEthnicUnityActivityCount(src.getEthnicUnityActivityCount());
        vo.setDigitalPlatformUsageRate(src.getDigitalPlatformUsageRate());
        vo.setRegionalPublicBrandCount(src.getRegionalPublicBrandCount());
        vo.setBrandPremiumRate(src.getBrandPremiumRate());
        return vo;
    }

    private static AchievementMonthlyVo zeroMonthly(int month, int statYear)
    {
        AchievementMonthlyVo vo = new AchievementMonthlyVo();
        vo.setStatYear(statYear);
        vo.setMonth(month);
        vo.setStatPeriod(com.ruoyi.web.modules.screen.support.HomeScreenSupport.formatStatPeriod(
                java.time.YearMonth.of(statYear, month)));
        vo.setCollectiveEconomyIncome(BigDecimal.ZERO.setScale(2, RoundingMode.UNNECESSARY));
        vo.setEmploymentDrivenCount(0);
        vo.setNewJobPositions(0);
        vo.setEnvProjectCount(0);
        vo.setNewGreenArea(BigDecimal.ZERO.setScale(2, RoundingMode.UNNECESSARY));
        vo.setCulturalHeritageCount(0);
        vo.setEthnicIntegrationProjectCount(0);
        vo.setEthnicUnityActivityCount(0);
        vo.setDigitalPlatformUsageRate(BigDecimal.ZERO.setScale(RATE_SCALE, RoundingMode.UNNECESSARY));
        vo.setRegionalPublicBrandCount(0);
        vo.setBrandPremiumRate(BigDecimal.ZERO.setScale(RATE_SCALE, RoundingMode.UNNECESSARY));
        return vo;
    }

    private static BigDecimal nvl(BigDecimal value)
    {
        return value == null ? BigDecimal.ZERO : value;
    }

    private static int nvlInt(Integer value)
    {
        return value == null ? 0 : value;
    }
}
