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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProject;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProjectOpImage;
import com.ruoyi.web.modules.screen.domain.vo.ProjectTypeStatVo;
import com.ruoyi.web.modules.screen.domain.vo.ScreenProjectListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.ScreenProjectOpImageVo;

/**
 * 大屏共同富裕 — 项目筛选、分类统计、列表组装（纯逻辑，便于单测）。
 * <p>
 * 项目纳入规则由 Mapper SQL 保证：已发布 + 实施周期与统计年交集；
 * 本类负责类型名解析、三类占比、可选年份并集、列表 VO 与运营图分组排序。
 * </p>
 */
public final class CommonProsperityScreenSupport
{
    private static final String DATETIME_FMT = "yyyy-MM-dd HH:mm:ss";

    /** 下标 1～3 对应项目类型展示名 */
    private static final String[] TYPE_NAMES = {
            null, "和美乡村建设项目", "人居环境整治提升项目", "其他项目投入"
    };

    private CommonProsperityScreenSupport()
    {
    }

    /** 解析项目类型展示名；非法类型返回空串 */
    public static String resolveProjectTypeName(Integer projectType)
    {
        if (projectType == null || projectType < 1 || projectType > 3)
        {
            return "";
        }
        return TYPE_NAMES[projectType];
    }

    /**
     * 是否纳入大屏统计：已发布（publish_status=1）且实施年限等于统计年 Y。
     * <p>注：列表/分类实际筛选以 Mapper {@code selectPublishedForScreen} 的周期交集为准；
     * 本方法用于单测与 impl_year 精确匹配场景。</p>
     */
    public static boolean matchesStatYear(BizCommonProsperityProject project, int statYear)
    {
        if (project == null || project.getPublishStatus() == null || project.getPublishStatus() != 1)
        {
            return false;
        }
        return project.getImplYear() != null && project.getImplYear() == statYear;
    }

    /** @deprecated 使用 {@link #matchesStatYear}；保留别名避免旧测试编译失败时遗漏 */
    public static boolean intersectsStatYear(BizCommonProsperityProject project, int statYear)
    {
        return matchesStatYear(project, statYear);
    }

    /**
     * 项目分类占比：固定输出类型 1/2/3 三项；{@code ratio = count/total}（无项目时全 0）。
     */
    public static List<ProjectTypeStatVo> buildProjectTypeStats(List<BizCommonProsperityProject> projects)
    {
        int c1 = 0;
        int c2 = 0;
        int c3 = 0;
        if (projects != null)
        {
            for (BizCommonProsperityProject p : projects)
            {
                if (p.getProjectType() == null)
                {
                    continue;
                }
                switch (p.getProjectType())
                {
                    case 1:
                        c1++;
                        break;
                    case 2:
                        c2++;
                        break;
                    case 3:
                        c3++;
                        break;
                    default:
                        break;
                }
            }
        }
        int total = c1 + c2 + c3;
        List<ProjectTypeStatVo> stats = new ArrayList<>(3);
        int[] counts = { c1, c2, c3 };
        for (int type = 1; type <= 3; type++)
        {
            ProjectTypeStatVo vo = new ProjectTypeStatVo();
            vo.setProjectType(type);
            vo.setProjectTypeName(TYPE_NAMES[type]);
            int count = counts[type - 1];
            vo.setCount(count);
            if (total == 0)
            {
                vo.setRatio(BigDecimal.ZERO);
            }
            else
            {
                vo.setRatio(BigDecimal.valueOf(count)
                        .divide(BigDecimal.valueOf(total), 4, RoundingMode.HALF_UP));
            }
            stats.add(vo);
        }
        return stats;
    }

    /**
     * 可选年份并集：成果台账年 + 已发布项目实施年 + 当前自然年，降序。
     */
    public static List<Integer> buildAvailableYears(List<String> achievementYearStrs,
            List<String> projectYearStrs)
    {
        Set<Integer> set = new TreeSet<>(Comparator.reverseOrder());
        addYearStrings(set, achievementYearStrs);
        addYearStrings(set, projectYearStrs);
        Calendar cal = Calendar.getInstance();
        set.add(cal.get(Calendar.YEAR));
        return new ArrayList<>(set);
    }

    private static void addYearStrings(Set<Integer> set, List<String> yearStrs)
    {
        if (yearStrs == null)
        {
            return;
        }
        for (String y : yearStrs)
        {
            if (y != null && y.matches("^\\d{4}$"))
            {
                set.add(Integer.parseInt(y));
            }
        }
    }

    /** 项目主表 → 大屏列表行（含运营图 URL 列表） */
    public static List<ScreenProjectListItemVo> toListItems(List<BizCommonProsperityProject> projects,
            Map<Long, List<BizCommonProsperityProjectOpImage>> imagesByProjectId)
    {
        if (projects == null || projects.isEmpty())
        {
            return Collections.emptyList();
        }
        List<ScreenProjectListItemVo> list = new ArrayList<>(projects.size());
        SimpleDateFormat dateTimeFmt = new SimpleDateFormat(DATETIME_FMT);
        for (BizCommonProsperityProject p : projects)
        {
            ScreenProjectListItemVo vo = new ScreenProjectListItemVo();
            vo.setId(p.getId());
            vo.setProjectType(p.getProjectType());
            vo.setProjectTypeName(resolveProjectTypeName(p.getProjectType()));
            vo.setProjectName(p.getProjectName());
            vo.setIntroduction(p.getIntroduction());
            vo.setProjectContent(p.getProjectContent());
            vo.setInvestmentAmount(p.getInvestmentAmount());
            vo.setImplYear(p.getImplYear());
            vo.setImplStatus(p.getImplStatus());
            vo.setCoverFileUrl(p.getCoverFileUrl());
            vo.setVideoFileUrl(p.getVideoFileUrl());
            vo.setPublishTime(formatDate(p.getPublishTime(), dateTimeFmt));
            vo.setOperationImages(toOpImageVos(imagesByProjectId != null
                    ? imagesByProjectId.get(p.getId()) : null));
            list.add(vo);
        }
        return list;
    }

    /** 运营图按 projectId 分组，组内按 sortOrder 升序 */
    public static Map<Long, List<BizCommonProsperityProjectOpImage>> groupImagesByProjectId(
            List<BizCommonProsperityProjectOpImage> images)
    {
        Map<Long, List<BizCommonProsperityProjectOpImage>> map = new HashMap<>();
        if (images == null)
        {
            return map;
        }
        for (BizCommonProsperityProjectOpImage img : images)
        {
            if (img.getProjectId() == null)
            {
                continue;
            }
            map.computeIfAbsent(img.getProjectId(), k -> new ArrayList<>()).add(img);
        }
        for (List<BizCommonProsperityProjectOpImage> list : map.values())
        {
            list.sort(Comparator.comparing(BizCommonProsperityProjectOpImage::getSortOrder,
                    Comparator.nullsLast(Integer::compareTo)));
        }
        return map;
    }

    private static List<ScreenProjectOpImageVo> toOpImageVos(List<BizCommonProsperityProjectOpImage> images)
    {
        if (images == null || images.isEmpty())
        {
            return Collections.emptyList();
        }
        List<ScreenProjectOpImageVo> list = new ArrayList<>(images.size());
        for (BizCommonProsperityProjectOpImage img : images)
        {
            ScreenProjectOpImageVo vo = new ScreenProjectOpImageVo();
            vo.setFileUrl(img.getFileUrl());
            vo.setSortOrder(img.getSortOrder());
            list.add(vo);
        }
        return list;
    }

    private static String formatDate(Date date, SimpleDateFormat fmt)
    {
        return date == null ? null : fmt.format(date);
    }
}
