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;

/**
 * 年度报告 / 大屏共同富裕成果组装（口径一致）：
 * <ul>
 *   <li>按月序列：所选年 1～库中最大统计月，缺月补 0</li>
 *   <li>总览：最大统计月的单月指标</li>
 * </ul>
 */
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;
        }
    }

    /**
     * 所选年内台账的最大统计月；无有效行返回 0。
     */
    public static int resolveMaxMonth(int statYear, List<BizCommonProsperityAchievement> rows)
    {
        int maxMonth = 0;
        if (rows == null)
        {
            return 0;
        }
        String yearPrefix = String.valueOf(statYear) + "-";
        for (BizCommonProsperityAchievement row : rows)
        {
            if (row == null || StringUtils.isEmpty(row.getStatPeriod())
                    || !row.getStatPeriod().startsWith(yearPrefix))
            {
                continue;
            }
            int month = parseMonthFromStatPeriod(row.getStatPeriod());
            if (month >= 1 && month <= 12 && month > maxMonth)
            {
                maxMonth = month;
            }
        }
        return maxMonth;
    }

    /**
     * 组装年度报告 / 大屏成果节点。
     * <p>{@code summary} 取最大月单月；{@code monthly} 为 1～最大月；无数据时 summary=null、monthly=[]。</p>
     */
    public static AchievementAnnualReportVo buildReport(int statYear, List<BizCommonProsperityAchievement> rows)
    {
        AchievementAnnualReportVo report = new AchievementAnnualReportVo();
        report.setStatYear(statYear);
        boolean hasData = rows != null && !rows.isEmpty() && resolveMaxMonth(statYear, rows) > 0;
        report.setHasData(hasData);
        List<AchievementMonthlyVo> monthly = buildMonthly(statYear, rows);
        report.setMonthly(monthly);
        report.setSummary(hasData ? calcSummaryFromMaxMonth(statYear, rows) : null);
        return report;
    }

    /**
     * 所选年 1～库中最大月；无数据返回空列表。
     */
    public static List<AchievementMonthlyVo> buildMonthly(int statYear, List<BizCommonProsperityAchievement> rows)
    {
        Map<Integer, BizCommonProsperityAchievement> byMonth = indexByMonth(statYear, rows);
        int maxMonth = 0;
        for (Integer m : byMonth.keySet())
        {
            if (m != null && m > maxMonth)
            {
                maxMonth = m;
            }
        }
        if (maxMonth <= 0)
        {
            return new ArrayList<>();
        }
        List<AchievementMonthlyVo> monthly = new ArrayList<>(maxMonth);
        for (int m = 1; m <= maxMonth; 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;
    }

    /**
     * 取所选年内台账最大统计月的单月指标；无有效台账返回 {@code null}。
     */
    public static AchievementAnnualSummaryVo calcSummaryFromMaxMonth(
            int statYear, List<BizCommonProsperityAchievement> rows)
    {
        BizCommonProsperityAchievement latest = findMaxMonthRow(statYear, rows);
        if (latest == null)
        {
            return null;
        }
        AchievementAnnualSummaryVo summary = new AchievementAnnualSummaryVo();
        summary.setCollectiveEconomyIncome(nvl(latest.getCollectiveEconomyIncome()).setScale(2, RoundingMode.HALF_UP));
        summary.setEmploymentDrivenCount(nvlInt(latest.getEmploymentDrivenCount()));
        summary.setNewJobPositions(nvlInt(latest.getNewJobPositions()));
        summary.setEnvProjectCount(nvlInt(latest.getEnvProjectCount()));
        summary.setNewGreenArea(nvl(latest.getNewGreenArea()).setScale(2, RoundingMode.HALF_UP));
        summary.setCulturalHeritageCount(nvlInt(latest.getCulturalHeritageCount()));
        summary.setEthnicIntegrationProjectCount(nvlInt(latest.getEthnicIntegrationProjectCount()));
        summary.setEthnicUnityActivityCount(nvlInt(latest.getEthnicUnityActivityCount()));
        summary.setDigitalPlatformUsageRate(
                nvl(latest.getDigitalPlatformUsageRate()).setScale(RATE_SCALE, RoundingMode.HALF_UP));
        summary.setRegionalPublicBrandCount(nvlInt(latest.getRegionalPublicBrandCount()));
        summary.setBrandPremiumRate(nvl(latest.getBrandPremiumRate()).setScale(RATE_SCALE, RoundingMode.HALF_UP));
        return summary;
    }

    /**
     * @deprecated 使用 {@link #calcSummaryFromMaxMonth(int, List)}
     */
    @Deprecated
    public static AchievementAnnualSummaryVo calcSummaryFromMaxMonth(List<BizCommonProsperityAchievement> rows)
    {
        if (rows == null || rows.isEmpty())
        {
            return null;
        }
        for (BizCommonProsperityAchievement row : rows)
        {
            if (row != null && StringUtils.isNotEmpty(row.getStatPeriod()) && row.getStatPeriod().length() >= 4)
            {
                try
                {
                    int year = Integer.parseInt(row.getStatPeriod().substring(0, 4));
                    return calcSummaryFromMaxMonth(year, rows);
                }
                catch (NumberFormatException ignored)
                {
                    // try next
                }
            }
        }
        return null;
    }

    /**
     * 在所选年台账行中取最大统计月的一条。
     */
    public static BizCommonProsperityAchievement findMaxMonthRow(
            int statYear, List<BizCommonProsperityAchievement> rows)
    {
        BizCommonProsperityAchievement latest = null;
        int maxMonth = -1;
        if (rows == null)
        {
            return null;
        }
        String yearPrefix = String.valueOf(statYear) + "-";
        for (BizCommonProsperityAchievement row : rows)
        {
            if (row == null || StringUtils.isEmpty(row.getStatPeriod())
                    || !row.getStatPeriod().startsWith(yearPrefix))
            {
                continue;
            }
            int month = parseMonthFromStatPeriod(row.getStatPeriod());
            if (month >= 1 && month <= 12 && month >= maxMonth)
            {
                maxMonth = month;
                latest = row;
            }
        }
        return latest;
    }

    /** @deprecated 使用 {@link #findMaxMonthRow(int, List)} */
    @Deprecated
    public static BizCommonProsperityAchievement findMaxMonthRow(List<BizCommonProsperityAchievement> rows)
    {
        if (rows == null || rows.isEmpty())
        {
            return null;
        }
        for (BizCommonProsperityAchievement row : rows)
        {
            if (row != null && StringUtils.isNotEmpty(row.getStatPeriod()) && row.getStatPeriod().length() >= 4)
            {
                try
                {
                    int year = Integer.parseInt(row.getStatPeriod().substring(0, 4));
                    return findMaxMonthRow(year, rows);
                }
                catch (NumberFormatException ignored)
                {
                    // try next
                }
            }
        }
        return null;
    }

    private static Map<Integer, BizCommonProsperityAchievement> indexByMonth(
            int statYear, List<BizCommonProsperityAchievement> rows)
    {
        Map<Integer, BizCommonProsperityAchievement> byMonth = new HashMap<>();
        if (rows == null)
        {
            return byMonth;
        }
        String yearPrefix = String.valueOf(statYear) + "-";
        for (BizCommonProsperityAchievement row : rows)
        {
            if (row == null || StringUtils.isEmpty(row.getStatPeriod())
                    || !row.getStatPeriod().startsWith(yearPrefix))
            {
                continue;
            }
            int month = parseMonthFromStatPeriod(row.getStatPeriod());
            if (month >= 1 && month <= 12)
            {
                byMonth.put(month, row);
            }
        }
        return byMonth;
    }

    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;
    }
}
