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

import java.time.LocalDate;
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.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.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;

/**
 * 大屏交易销售统计服务实现。
 */
@Service
public class TradeSalesScreenServiceImpl implements ITradeSalesScreenService
{
    @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);
        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;

        TradeSalesDashboardVo vo = new TradeSalesDashboardVo();
        vo.setStatYear(year);
        vo.setStatDate(HomeScreenSupport.formatStatDate(statDate));
        vo.setTradeOverview(TradeSalesScreenSupport.buildTradeOverview(
                overview, homeScreenStatsMapper.countSupplierForScreen()));
        vo.setTradeMonthlyTrend(TradeSalesScreenSupport.buildTradeMonthlyTrend(
                tradeSalesScreenMapper.selectMonthlyTradeByYear(yearStart, yearEnd), statDate));
        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));
        mergeMallStats(vo, year);
        return vo;
    }

    private void mergeMallStats(TradeSalesDashboardVo vo, int year)
    {
        MallStatsOverviewVo mall = mallStatsOpenApiClient.fetchOverview(year);
        if (mall != null)
        {
            TradeSalesScreenSupport.applyMallStats(vo, mall);
        }
        else
        {
            TradeSalesScreenSupport.applyEmptyMallStats(vo);
        }
    }

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