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

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.modules.industryservice.domain.BizLivestockProductOutput;
import com.ruoyi.web.modules.industryservice.domain.BizThreeAssetsProblemReport;
import com.ruoyi.web.modules.industryservice.domain.BizVaccinationData;
import com.ruoyi.web.modules.industryservice.mapper.BizLivestockProductOutputMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizThreeAssetsProblemReportMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizVaccinationDataMapper;
import com.ruoyi.web.modules.industryservice.support.BreedingIndustryRules;
import com.ruoyi.web.modules.prosperity.support.AchievementReportValidation;
import com.ruoyi.web.modules.screen.domain.dto.HomeScreenStatPeriodDto;
import com.ruoyi.web.modules.screen.domain.dto.LivestockResourceProductOutputSumDto;
import com.ruoyi.web.modules.screen.domain.dto.LivestockResourceTechPersonnelDto;
import com.ruoyi.web.modules.screen.domain.dto.LivestockResourceThreeAssetsSumDto;
import com.ruoyi.web.modules.screen.domain.dto.LivestockResourceVaccinationSumDto;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceOverviewVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceProductOutputListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceThreeAssetsProblemListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceVaccinationListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceVetCountListItemVo;
import com.ruoyi.web.modules.screen.mapper.HomeScreenStatsMapper;
import com.ruoyi.web.modules.screen.mapper.LivestockResourceScreenMapper;
import com.ruoyi.web.modules.screen.service.ILivestockResourceScreenService;
import com.ruoyi.web.modules.screen.support.HomeScreenSupport;
import com.ruoyi.web.modules.screen.support.LivestockResourceScreenSupport;

/**
 * 大屏畜牧资源统计服务实现。
 * <p>
 * <b>看板</b>：总览、三资、问题上报占比、产量趋势、疫苗、线下预约、特派员、事业单位、农技课堂、实战培训。<br>
 * <b>明细</b>：复用业务 Mapper 列表 SQL（或专用汇总 SQL），统一清空 dataScope 做全县口径。<br>
 * <b>已屏蔽</b>：AI 问诊活跃度 / 用户结构 / 分类 / 模型调用 / 分时 / 会话分布 / 状态 / 热门 / 关键词。
 * </p>
 */
@Service
public class LivestockResourceScreenServiceImpl implements ILivestockResourceScreenService
{
    @Autowired
    private LivestockResourceScreenMapper livestockResourceScreenMapper;

    /** 线下预约月度、农技课堂、培训趋势等与首页共用统计 */
    @Autowired
    private HomeScreenStatsMapper homeScreenStatsMapper;

    @Autowired
    private BizThreeAssetsProblemReportMapper bizThreeAssetsProblemReportMapper;

    @Autowired
    private BizLivestockProductOutputMapper bizLivestockProductOutputMapper;

    @Autowired
    private BizVaccinationDataMapper bizVaccinationDataMapper;

    @Override
    public LivestockResourceDashboardVo loadDashboard(String statYear)
    {
        int year = AchievementReportValidation.parseStatYear(statYear);
        LocalDate statDate = HomeScreenSupport.resolveStatDate(year);
        LocalDateTime statDateTime = LocalDateTime.now(ZoneId.of(BreedingIndustryRules.ZONE_SHANGHAI));

        Date yearStart = toDate(LocalDate.of(year, 1, 1));
        Date yearEnd = toDateEndOfDay(statDate);

        // —— 核心总览依赖的汇总 ——
        LivestockResourceThreeAssetsSumDto assetsSum = livestockResourceScreenMapper.sumRuralThreeAssetsFixed();
        LivestockResourceProductOutputSumDto productOutputSum = resolveProductOutputSum(year);
        HomeScreenStatPeriodDto vaccPeriod = livestockResourceScreenMapper.selectLatestVaccinationStatPeriodByYear(year);
        LivestockResourceVaccinationSumDto vaccinationSum = resolveVaccinationSum(vaccPeriod);
        LivestockResourceTechPersonnelDto techPersonnel =
                livestockResourceScreenMapper.selectTechServicePersonnelTotals();

        LivestockResourceOverviewVo overview = LivestockResourceScreenSupport.buildOverview(
                assetsSum,
                productOutputSum,
                vaccinationSum,
                livestockResourceScreenMapper.countVetMedicalResource(),
                techPersonnel);

        LivestockResourceDashboardVo vo = new LivestockResourceDashboardVo();
        vo.setStatYear(year);
        vo.setStatDate(HomeScreenSupport.formatStatDate(statDate));
        vo.setStatDateTime(LivestockResourceScreenSupport.formatStatDateTime(statDateTime));
        // availableYears 仍取 AI 会话年份并集，供前端年份下拉（与历史实现一致）
        vo.setAvailableYears(HomeScreenSupport.buildAvailableYears(
                livestockResourceScreenMapper.selectDistinctSessionYears()));
        vo.setOverview(overview);
        vo.setRuralThreeAssets(LivestockResourceScreenSupport.buildRuralThreeAssets(assetsSum));
        vo.setProblemReportShare(LivestockResourceScreenSupport.buildProblemReportShare(
                livestockResourceScreenMapper.countThreeAssetsProblemByLevel(yearStart, yearEnd)));
        vo.setProductOutputTrend(resolveProductOutputTrend(year));
        vo.setVaccinationOverview(LivestockResourceScreenSupport.buildVaccinationOverview(
                vaccPeriod != null ? vaccPeriod.getStatMonth() : null, vaccinationSum));
        // 线下预约：三项汇总为资源台账人数/机构数（不随年）；monthlyStacked 为所选年 1～最大月预约次数
        vo.setAppointment(HomeScreenSupport.buildAppointmentForStatYear(
                safeInt(livestockResourceScreenMapper.countVetMedicalResource()),
                safeInt(livestockResourceScreenMapper.countTechExpertResource()),
                safeInt(livestockResourceScreenMapper.countMedicalOrgResource()),
                homeScreenStatsMapper.selectAppointmentMonthlyByYear(year),
                year));
        vo.setTechEnvoyStructure(LivestockResourceScreenSupport.buildTechEnvoyStructure(techPersonnel));
        vo.setAgriUnitStructure(LivestockResourceScreenSupport.buildAgriUnitStructure(techPersonnel));
        int videoCount = homeScreenStatsMapper.countVideoCoursesPublishedInYear(yearStart, yearEnd);
        int trainingPublishCount = homeScreenStatsMapper.countTrainingsPublishedInYear(yearStart, yearEnd);
        vo.setAgriClassroom(HomeScreenSupport.buildAgriClassroom(videoCount, trainingPublishCount));
        vo.setTrainingTrend(HomeScreenSupport.buildTrainingTrendForStatYear(
                homeScreenStatsMapper.selectTrainingTrendByTrainingYear(year), year));
        return vo;
    }

    @Override
    public List<LivestockResourceThreeAssetsProblemListItemVo> listThreeAssetsProblemReports(
            Integer statYear, Long townDeptId, Long villageDeptId)
    {
        BizThreeAssetsProblemReport query = new BizThreeAssetsProblemReport();
        query.setTownDeptId(townDeptId);
        query.setVillageDeptId(villageDeptId);
        if (statYear != null)
        {
            LocalDate yearStart = LocalDate.of(statYear, 1, 1);
            LocalDate yearEnd = LocalDate.of(statYear, 12, 31);
            query.setBeginReportTime(toDate(yearStart));
            query.setEndReportTime(toDate(yearEnd));
        }
        // 大屏全县口径，清空 dataScope
        query.getParams().put("dataScope", "");
        List<BizThreeAssetsProblemReport> rows =
                bizThreeAssetsProblemReportMapper.selectBizThreeAssetsProblemReportList(query);
        return LivestockResourceScreenSupport.buildThreeAssetsProblemListItems(rows);
    }

    @Override
    public List<LivestockResourceProductOutputListItemVo> listProductOutputs(
            Integer statYear, Integer statMonth, Long townDeptId, Long villageDeptId)
    {
        BizLivestockProductOutput query = new BizLivestockProductOutput();
        query.setStatYear(statYear);
        query.setStatMonth(statMonth);
        query.setTownDeptId(townDeptId);
        query.setVillageDeptId(villageDeptId);
        // 大屏全县口径，清空 dataScope
        query.getParams().put("dataScope", "");
        List<BizLivestockProductOutput> rows =
                bizLivestockProductOutputMapper.selectBizLivestockProductOutputList(query);
        return LivestockResourceScreenSupport.buildProductOutputListItems(rows);
    }

    @Override
    public List<LivestockResourceVaccinationListItemVo> listVaccinationData(
            Integer statYear, Integer statMonth, Long townDeptId, Long villageDeptId)
    {
        BizVaccinationData query = new BizVaccinationData();
        query.setStatYear(statYear);
        query.setStatMonth(statMonth);
        query.setTownDeptId(townDeptId);
        query.setVillageDeptId(villageDeptId);
        // 大屏全县口径，清空 dataScope
        query.getParams().put("dataScope", "");
        List<BizVaccinationData> rows = bizVaccinationDataMapper.selectBizVaccinationDataList(query);
        return LivestockResourceScreenSupport.buildVaccinationListItems(rows);
    }

    @Override
    public List<LivestockResourceVetCountListItemVo> listVetCounts(Long townDeptId)
    {
        List<LivestockResourceVetCountListItemVo> rows =
                livestockResourceScreenMapper.selectVetCountByTown(townDeptId);
        return rows != null ? rows : Collections.emptyList();
    }

    /** 所选年产量：取该年最大填报月的全县肉/奶合计（供核心总览） */
    private LivestockResourceProductOutputSumDto resolveProductOutputSum(int year)
    {
        HomeScreenStatPeriodDto period =
                livestockResourceScreenMapper.selectLatestLivestockProductOutputStatPeriodByYear(year);
        if (period == null || period.getStatYear() == null || period.getStatMonth() == null)
        {
            return null;
        }
        return livestockResourceScreenMapper.sumLivestockProductOutputByStatYearMonth(
                period.getStatYear(), period.getStatMonth());
    }

    /** 产量趋势：1～最大填报月，缺月由 Support 补 0 */
    private com.ruoyi.web.modules.screen.domain.vo.LivestockResourceProductOutputTrendVo resolveProductOutputTrend(
            int year)
    {
        HomeScreenStatPeriodDto period =
                livestockResourceScreenMapper.selectLatestLivestockProductOutputStatPeriodByYear(year);
        if (period == null || period.getStatMonth() == null || period.getStatMonth() < 1)
        {
            return LivestockResourceScreenSupport.buildProductOutputTrend(null, null);
        }
        int maxMonth = period.getStatMonth();
        return LivestockResourceScreenSupport.buildProductOutputTrend(
                maxMonth,
                livestockResourceScreenMapper.sumLivestockProductOutputMonthlyUpTo(year, maxMonth));
    }

    /** 所选年疫苗：取该年最大填报月的全县应免/实免合计 */
    private LivestockResourceVaccinationSumDto resolveVaccinationSum(HomeScreenStatPeriodDto period)
    {
        if (period == null || period.getStatYear() == null || period.getStatMonth() == null)
        {
            return null;
        }
        return livestockResourceScreenMapper.sumVaccinationByStatYearMonth(
                period.getStatYear(), period.getStatMonth());
    }

    private static long safeLong(Long value)
    {
        return value != null ? value : 0L;
    }

    private static int safeInt(Long value)
    {
        long n = safeLong(value);
        if (n > Integer.MAX_VALUE)
        {
            return Integer.MAX_VALUE;
        }
        return (int) n;
    }

    private static Date toDate(LocalDate localDate)
    {
        return Date.from(localDate.atStartOfDay(ZoneId.of(BreedingIndustryRules.ZONE_SHANGHAI)).toInstant());
    }

    private static Date toDateEndOfDay(LocalDate localDate)
    {
        return Date.from(localDate.atTime(23, 59, 59)
                .atZone(ZoneId.of(BreedingIndustryRules.ZONE_SHANGHAI)).toInstant());
    }
}
