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.HashSet;
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;

/**
 * 大屏共同富裕 — 项目筛选、分类统计、列表组装（纯逻辑，便于单测）。
 */
public final class CommonProsperityScreenSupport
{
    private static final String DATE_FMT = "yyyy-MM-dd";

    private static final String DATETIME_FMT = "yyyy-MM-dd HH:mm:ss";

    /** 1 合作共赢 → 共富项目；2 农文旅；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];
    }

    /**
     * 已发布且实施周期与统计年 Y 有交集。
     */
    public static boolean intersectsStatYear(BizCommonProsperityProject project, int statYear)
    {
        if (project == null || project.getPublishStatus() == null || project.getPublishStatus() != 1)
        {
            return false;
        }
        Date start = project.getImplStartDate();
        Date end = project.getImplEndDate();
        if (start == null || end == null)
        {
            return false;
        }
        Calendar yearStart = Calendar.getInstance();
        yearStart.clear();
        yearStart.set(statYear, Calendar.JANUARY, 1, 0, 0, 0);
        Calendar yearEnd = Calendar.getInstance();
        yearEnd.clear();
        yearEnd.set(statYear, Calendar.DECEMBER, 31, 23, 59, 59);
        return !start.after(yearEnd.getTime()) && !end.before(yearStart.getTime());
    }

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

    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 dateFmt = new SimpleDateFormat(DATE_FMT);
        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.setImplStartDate(formatDate(p.getImplStartDate(), dateFmt));
            vo.setImplEndDate(formatDate(p.getImplEndDate(), dateFmt));
            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;
    }

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