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

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.TradeSalesOverviewDto;
import com.ruoyi.web.modules.screen.domain.vo.MallOrderTrendItemVo;
import com.ruoyi.web.modules.screen.domain.vo.MallOrderTrendVo;
import com.ruoyi.web.modules.screen.domain.vo.MallStatsOverviewVo;
import com.ruoyi.web.modules.screen.domain.vo.TradeSalesDashboardVo;
import com.ruoyi.web.modules.screen.mapper.HomeScreenStatsMapper;
import com.ruoyi.web.modules.screen.mapper.TradeSalesScreenMapper;
import com.ruoyi.web.modules.screen.mallstats.MallStatsOpenApiClient;
import com.ruoyi.web.modules.screen.service.ITradeSalesScreenService;
import com.ruoyi.web.modules.screen.support.HomeScreenSupport;
import com.ruoyi.web.modules.screen.support.TradeSalesScreenRules;
import com.ruoyi.web.modules.screen.support.TradeSalesScreenSupport;
import com.ruoyi.web.modules.trading.domain.BizGradeWeightConfig;
import com.ruoyi.web.modules.trading.mapper.BizGradeWeightConfigMapper;

/**
 * 大屏交易销售统计服务实现。
 * <p>
 * 编排本地交易 Mapper 与农资商城 Open API：牦牛区块按 {@code statYear} 内完成订单聚合；
 * 产地行情取默认交易市场近 7 日日报；商城六区块失败时不抛异常，由 Support 写入空态。
 */
@Service
public class TradeSalesScreenServiceImpl implements ITradeSalesScreenService
{
    /** 产地行情默认交易市场名称，可通过 {@code bigscreen.trade-sales.default-market-name} 覆盖 */
    @Value("${bigscreen.trade-sales.default-market-name:巴青牦牛交易市场}")
    private String defaultMarketName;

    @Autowired
    private TradeSalesScreenMapper tradeSalesScreenMapper;

    @Autowired
    private HomeScreenStatsMapper homeScreenStatsMapper;

    @Autowired
    private BizGradeWeightConfigMapper bizGradeWeightConfigMapper;

    @Autowired
    private MallStatsOpenApiClient mallStatsOpenApiClient;

    @Override
    public TradeSalesDashboardVo loadDashboard(String statYear)
    {
        int year = AchievementReportValidation.parseStatYear(statYear);
        LocalDate statDate = HomeScreenSupport.resolveStatDate(year);
        Date yearStart = toDate(LocalDate.of(year, 1, 1));
        Date yearEnd = toDateEndOfDay(statDate);
        // 产地行情窗口：statDate 往前共 7 个自然日（含当天）
        Date quoteStart = toDate(statDate.minusDays(6));
        Date quoteEnd = toDate(statDate);

        TradeSalesOverviewDto overview = tradeSalesScreenMapper.selectTradeOverview(yearStart, yearEnd);
        long totalHeads = overview != null && overview.getTradeHeads() != null ? overview.getTradeHeads() : 0L;

        YearMonth rollingAnchor = HomeScreenSupport.currentYearMonth();
        LocalDate rollingEnd = HomeScreenSupport.rolling12MonthWindowEnd(rollingAnchor);
        Date rollingStart = toDate(rollingAnchor.minusMonths(11).atDay(1));
        Date rollingEndDate = toDateEndOfDay(rollingEnd);

        TradeSalesDashboardVo vo = new TradeSalesDashboardVo();
        vo.setStatYear(year);
        vo.setStatDate(HomeScreenSupport.formatStatDate(statDate));
        // —— 本地牦牛交易 ——
        vo.setTradeOverview(TradeSalesScreenSupport.buildTradeOverview(
                overview, homeScreenStatsMapper.countSupplierForScreen()));
        vo.setTradeMonthlyTrend(TradeSalesScreenSupport.buildRolling12MonthTradeTrend(
                tradeSalesScreenMapper.selectMonthlyTradeByYear(rollingStart, rollingEndDate), rollingAnchor));
        vo.setSalesDestination(TradeSalesScreenSupport.buildSalesDestination(
                tradeSalesScreenMapper.selectSalesDestinationByYear(yearStart, yearEnd), totalHeads));
        long gradedLines = tradeSalesScreenMapper.countGradedLinesInYear(yearStart, yearEnd);
        List<BizGradeWeightConfig> gradeConfigs = bizGradeWeightConfigMapper.selectAllOrderBySort();
        vo.setQualityGrade(TradeSalesScreenSupport.buildQualityGrade(
                tradeSalesScreenMapper.selectQualityGradeByYear(yearStart, yearEnd),
                gradeConfigs != null ? gradeConfigs : Collections.emptyList(),
                gradedLines));
        vo.setOriginQuote(buildOriginQuote(statDate, quoteStart, quoteEnd));
        List<Integer> finishYears = tradeSalesScreenMapper.selectDistinctFinishYears();
        vo.setAvailableYears(TradeSalesScreenSupport.buildAvailableYears(finishYears));
        // —— 农资商城（HTTP，失败则 mallStatsAvailable=false）——
        mergeMallStats(vo, rollingAnchor);
        return vo;
    }

    /** 拉取商城 overview 并合并到看板；跨年时合并订单趋势后转为最近 12 个月。 */
    private void mergeMallStats(TradeSalesDashboardVo vo, YearMonth rollingAnchor)
    {
        int endYear = rollingAnchor.getYear();
        int startYear = rollingAnchor.minusMonths(11).getYear();
        MallStatsOverviewVo mall = mallStatsOpenApiClient.fetchOverview(endYear);
        if (mall == null)
        {
            TradeSalesScreenSupport.applyEmptyMallStats(vo);
            return;
        }
        List<MallOrderTrendItemVo> mergedItems = new ArrayList<>();
        TradeSalesScreenSupport.tagMallOrderTrendItems(mall.getMallOrderTrend(), endYear);
        if (mall.getMallOrderTrend() != null && mall.getMallOrderTrend().getItems() != null)
        {
            mergedItems.addAll(mall.getMallOrderTrend().getItems());
        }
        if (startYear != endYear)
        {
            MallStatsOverviewVo previous = mallStatsOpenApiClient.fetchOverview(startYear);
            if (previous != null)
            {
                TradeSalesScreenSupport.tagMallOrderTrendItems(previous.getMallOrderTrend(), startYear);
                if (previous.getMallOrderTrend() != null && previous.getMallOrderTrend().getItems() != null)
                {
                    mergedItems.addAll(0, previous.getMallOrderTrend().getItems());
                }
            }
        }
        TradeSalesScreenSupport.applyMallStats(vo, mall);
        MallOrderTrendVo rollingTrend = TradeSalesScreenSupport.buildRolling12MonthMallOrderTrend(
                mergedItems, rollingAnchor);
        vo.setMallOrderTrend(rollingTrend);
        if (vo.getTradeOverview() != null && rollingTrend.getItems() != null)
        {
            long orderCount = 0L;
            for (MallOrderTrendItemVo item : rollingTrend.getItems())
            {
                if (item != null)
                {
                    orderCount += item.getOrderCount();
                }
            }
            vo.getTradeOverview().setAgriOrderCount(orderCount);
        }
    }

    /** 按配置市场名查 ID，无数据则返回 hasQuoteData=false 的空行情。 */
    private com.ruoyi.web.modules.screen.domain.vo.TradeSalesOriginQuoteVo buildOriginQuote(
            LocalDate statDate, Date quoteStart, Date quoteEnd)
    {
        String marketName = defaultMarketName != null && !defaultMarketName.trim().isEmpty()
                ? defaultMarketName.trim()
                : TradeSalesScreenRules.DEFAULT_MARKET_NAME;
        Long marketId = tradeSalesScreenMapper.selectTradeMarketIdByName(marketName);
        if (marketId == null)
        {
            return TradeSalesScreenSupport.buildOriginQuote(Collections.emptyList(), statDate);
        }
        return TradeSalesScreenSupport.buildOriginQuote(
                tradeSalesScreenMapper.selectQuotesInWindow(marketId, quoteStart, quoteEnd),
                statDate);
    }

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