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

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
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.support.BreedingIndustryRules;
import com.ruoyi.web.modules.prosperity.support.AchievementReportValidation;
import com.ruoyi.web.modules.screen.domain.dto.LivestockResourceOverviewDto;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceActivityTrendVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceCategoryItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceCategoryShareVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceHourlyHeatVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceOverviewVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceReplyStatusVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceUserStructureVo;
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.LivestockResourceScreenRules;
import com.ruoyi.web.modules.screen.support.LivestockResourceScreenSupport;

/**
 * 大屏畜牧资源（AI 问诊）统计服务实现。
 * <p>
 * 统计 AI 咨询会话与消息：年度概览、近 7 日活跃趋势、用户结构、问题分类、24 小时热力、
 * 回复成功率及提问文本本地分词 Top 关键词。当前统计年才展示「今日」四项实时指标。
 */
@Service
public class LivestockResourceScreenServiceImpl implements ILivestockResourceScreenService
{
    @Autowired
    private LivestockResourceScreenMapper livestockResourceScreenMapper;

    @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));
        // 仅当前年展示今日活跃/新增/会话/提问数
        boolean includeToday = LivestockResourceScreenSupport.isCurrentStatYear(year);

        Date yearStart = toDate(LocalDate.of(year, 1, 1));
        Date yearEnd = toDateEndOfDay(statDate);
        Date dayStart = toDate(statDate);
        Date dayEnd = toDateEndOfDay(statDate);
        // 活跃趋势：近 ACTIVITY_DAYS（7）日
        Date sevenStart = toDate(statDate.minusDays(LivestockResourceScreenRules.ACTIVITY_DAYS - 1));
        Date sevenEnd = yearEnd;
        LocalDateTime hourlyAnchor = statDateTime.truncatedTo(java.time.temporal.ChronoUnit.HOURS);
        Date hourlyWindowStart = toDateTime(hourlyAnchor.minusHours(LivestockResourceScreenRules.HOURLY_BUCKETS - 1));
        Date hourlyWindowEnd = toDateTime(hourlyAnchor.plusHours(1).minusSeconds(1));

        LivestockResourceOverviewDto yearMetrics = livestockResourceScreenMapper.selectYearOverviewMetrics(
                yearStart, yearEnd);
        Long todayActive = includeToday
                ? livestockResourceScreenMapper.countTodayActiveUsers(dayStart, dayEnd) : null;
        Long todayNew = includeToday
                ? livestockResourceScreenMapper.countTodayNewUsers(dayStart, dayEnd) : null;
        Long todaySessions = includeToday
                ? livestockResourceScreenMapper.countTodaySessions(dayStart, dayEnd) : null;
        Long todayQuestions = includeToday
                ? livestockResourceScreenMapper.countTodayQuestionCount(dayStart, dayEnd) : null;

        LivestockResourceOverviewVo overview = LivestockResourceScreenSupport.buildOverview(
                yearMetrics, todayActive, todayNew, todaySessions, todayQuestions, includeToday);

        LivestockResourceActivityTrendVo activityTrend = LivestockResourceScreenSupport.buildActivityTrend(
                livestockResourceScreenMapper.selectDailySessionCounts(sevenStart, sevenEnd),
                livestockResourceScreenMapper.selectDailyAiReplyCounts(sevenStart, sevenEnd),
                statDate);

        LivestockResourceUserStructureVo userStructure = LivestockResourceScreenSupport.buildUserStructure(
                livestockResourceScreenMapper.selectUserStructure());

        long totalAiMessages = safeLong(livestockResourceScreenMapper.countAskerMessagesInYear(yearStart, yearEnd));
        List<com.ruoyi.web.modules.screen.domain.dto.LivestockResourceCategoryCountDto> categoryRows =
                livestockResourceScreenMapper.selectAskerCategoryCounts(yearStart, yearEnd);
        LivestockResourceCategoryShareVo categoryShare = LivestockResourceScreenSupport.buildCategoryShare(
                categoryRows, totalAiMessages);
        List<LivestockResourceCategoryItemVo> categoryItems = categoryShare.getItems();

        LivestockResourceHourlyHeatVo hourlyHeat = LivestockResourceScreenSupport.buildHourlyHeat(
                livestockResourceScreenMapper.selectHourlySessionCounts(hourlyWindowStart, hourlyWindowEnd),
                livestockResourceScreenMapper.selectHourlyAiReplyCounts(hourlyWindowStart, hourlyWindowEnd),
                hourlyAnchor);

        long yearSessionTotal = safeLong(livestockResourceScreenMapper.countYearSessions(yearStart, yearEnd));

        long okCount = safeLong(livestockResourceScreenMapper.countAiRepliesOk(yearStart, yearEnd));
        long failCount = safeLong(livestockResourceScreenMapper.countAiRepliesFail(yearStart, yearEnd));
        LivestockResourceReplyStatusVo replyStatus = LivestockResourceScreenSupport.buildReplyStatus(okCount, failCount);

        LivestockResourceDashboardVo vo = new LivestockResourceDashboardVo();
        vo.setStatYear(year);
        vo.setStatDate(HomeScreenSupport.formatStatDate(statDate));
        vo.setStatDateTime(LivestockResourceScreenSupport.formatStatDateTime(statDateTime));
        vo.setAvailableYears(HomeScreenSupport.buildAvailableYears(
                livestockResourceScreenMapper.selectDistinctSessionYears()));
        vo.setOverview(overview);
        vo.setActivityTrend(activityTrend);
        vo.setUserStructure(userStructure);
        vo.setCategoryShare(categoryShare);
        vo.setModelCallAnalysis(LivestockResourceScreenSupport.buildModelCallAnalysis(categoryItems));
        vo.setHourlyHeat(hourlyHeat);
        vo.setSessionReplyDistribution(LivestockResourceScreenSupport.buildSessionReplyDistribution(
                livestockResourceScreenMapper.selectSessionReplyBuckets(yearStart, yearEnd),
                yearSessionTotal));
        vo.setReplyStatusDistribution(replyStatus);
        vo.setHotTopics(LivestockResourceScreenSupport.buildHotTopics(
                categoryRows, LivestockResourceScreenRules.HOT_TOPIC_TOP));
        // 对年度提问文本做本地分词（非商城 API），取 Top KEYWORD_TOP
        vo.setTopKeywords(LivestockResourceScreenSupport.extractTopKeywords(
                livestockResourceScreenMapper.selectTextAskerContents(yearStart, yearEnd),
                LivestockResourceScreenRules.KEYWORD_TOP));
        return vo;
    }

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

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

    private static Date toDateTime(LocalDateTime dateTime)
    {
        return Date.from(dateTime.atZone(ZoneId.of(BreedingIndustryRules.ZONE_SHANGHAI)).toInstant());
    }
}
