package com.ruoyi.web.modules.screen.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityAchievement;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProject;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProjectOpImage;
import com.ruoyi.web.modules.prosperity.mapper.BizCommonProsperityAchievementMapper;
import com.ruoyi.web.modules.prosperity.mapper.BizCommonProsperityProjectMapper;
import com.ruoyi.web.modules.prosperity.mapper.BizCommonProsperityProjectOpImageMapper;
import com.ruoyi.web.modules.prosperity.support.AchievementReportAggregator;
import com.ruoyi.web.modules.prosperity.support.AchievementReportValidation;
import com.ruoyi.web.modules.screen.domain.vo.CommonProsperityProjectTypeDetailVo;
import com.ruoyi.web.modules.screen.domain.vo.CommonProsperityScreenDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.ScreenProjectListItemVo;
import com.ruoyi.web.modules.screen.service.ICommonProsperityScreenService;
import com.ruoyi.web.modules.screen.support.CommonProsperityScreenSupport;

/**
 * 大屏共同富裕统计服务实现。
 * <p>
 * 成果口径（与管理端年度报告一致，见 {@link AchievementReportAggregator#buildReport}）：
 * <ul>
 *   <li>总览 / 数字赋能：所选年台账中<strong>最大统计月</strong>的单月指标</li>
 *   <li>按月图表：该年 <strong>1～最大月</strong>，区间内缺月补 0；无台账则 {@code monthly} 为空</li>
 * </ul>
 * 项目：仅已发布且实施周期与统计年有交集；分类占比固定三类（缺类 count=0）。
 * </p>
 */
@Service
public class CommonProsperityScreenServiceImpl implements ICommonProsperityScreenService
{
    @Autowired
    private BizCommonProsperityAchievementMapper achievementMapper;

    @Autowired
    private BizCommonProsperityProjectMapper projectMapper;

    @Autowired
    private BizCommonProsperityProjectOpImageMapper opImageMapper;

    /**
     * {@inheritDoc}
     * <p>步骤：校验年份 → 按年查成果并组装报告 → 查已发布项目做分类统计 → 合并可选年份。</p>
     */
    @Override
    public CommonProsperityScreenDashboardVo loadDashboard(String statYear)
    {
        int year = AchievementReportValidation.parseStatYear(statYear);
        CommonProsperityScreenDashboardVo vo = new CommonProsperityScreenDashboardVo();
        vo.setStatYear(year);
        // 成果：summary=最大月单月；monthly=1～最大月
        List<BizCommonProsperityAchievement> rows = safeAchievementsByYear(year);
        vo.setAchievement(AchievementReportAggregator.buildReport(year, rows));
        // 项目分类饼图 + 是否有项目数据
        List<BizCommonProsperityProject> projects = safePublishedForScreen(year);
        vo.setHasProjectData(!projects.isEmpty());
        vo.setProjectTypeStats(CommonProsperityScreenSupport.buildProjectTypeStats(projects));
        // 年份下拉：成果年 ∪ 已发布项目实施年 ∪ 当前自然年，降序
        vo.setAvailableYears(CommonProsperityScreenSupport.buildAvailableYears(
                achievementMapper.selectDistinctStatYears(),
                projectMapper.selectDistinctStatYearsFromPublished()));
        return vo;
    }

    /**
     * {@inheritDoc}
     * <p>先查项目主表，再按 ID 批量查运营图并按 {@code sort_order} 组装到行内。</p>
     */
    @Override
    public List<ScreenProjectListItemVo> listPublishedProjects(String statYear)
    {
        int year = AchievementReportValidation.parseStatYear(statYear);
        List<BizCommonProsperityProject> projects = safePublishedForScreen(year);
        if (projects.isEmpty())
        {
            return Collections.emptyList();
        }
        List<Long> ids = projects.stream().map(BizCommonProsperityProject::getId).collect(Collectors.toList());
        List<BizCommonProsperityProjectOpImage> images = opImageMapper.selectByProjectIds(ids);
        Map<Long, List<BizCommonProsperityProjectOpImage>> byProject =
                CommonProsperityScreenSupport.groupImagesByProjectId(images);
        return CommonProsperityScreenSupport.toListItems(projects, byProject);
    }

    /**
     * {@inheritDoc}
     * <p>口径：{@code publish_status=1}，按 {@code impl_year} 聚合；未传年份不过滤。</p>
     */
    @Override
    public List<CommonProsperityProjectTypeDetailVo> listProjectTypeDetails(Integer statYear)
    {
        List<CommonProsperityProjectTypeDetailVo> list =
                projectMapper.selectPublishedTypeDetailsByYear(statYear);
        return list != null ? list : new ArrayList<>();
    }

    /** 大屏已发布项目（实施周期与统计年交集）；Mapper 返回 null 时转空列表 */
    private List<BizCommonProsperityProject> safePublishedForScreen(int statYear)
    {
        List<BizCommonProsperityProject> list = projectMapper.selectPublishedForScreen(statYear);
        return list != null ? list : new ArrayList<>();
    }

    /** 所选年成果台账（{@code stat_period like 'Y-%'}）；null 转空列表 */
    private List<BizCommonProsperityAchievement> safeAchievementsByYear(int statYear)
    {
        List<BizCommonProsperityAchievement> list = achievementMapper.selectByStatYear(String.valueOf(statYear));
        return list != null ? list : new ArrayList<>();
    }
}
