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

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.trading.domain.dto.AppDistributorAmountBucketDto;
import com.ruoyi.web.modules.trading.domain.dto.AppDistributorTradeSummaryDto;
import com.ruoyi.web.modules.trading.domain.vo.AppDistributorHomeDashboardVo;
import com.ruoyi.web.modules.trading.mapper.AppDistributorTradeMapper;
import com.ruoyi.web.modules.trading.service.IAppDistributorHomeService;
import com.ruoyi.web.modules.trading.support.AppDistributorHomeRules;
import com.ruoyi.web.modules.trading.support.AppDistributorHomeSupport;
import com.ruoyi.web.modules.trading.support.AppDistributorSessionSupport;

/**
 * 承销商小程序首页统计。
 */
@Service
public class AppDistributorHomeServiceImpl implements IAppDistributorHomeService
{
    @Autowired
    private AppDistributorSessionSupport appDistributorSessionSupport;

    @Autowired
    private AppDistributorTradeMapper appDistributorTradeMapper;

    @Override
    public AppDistributorHomeDashboardVo loadDashboard(String range)
    {
        String normalized = AppDistributorHomeSupport.normalizeRange(range);
        Long distributorId = appDistributorSessionSupport.requireDistributorId();
        AppDistributorHomeSupport.DateRange dateRange = AppDistributorHomeSupport.resolveRange(normalized);
        Date start = AppDistributorHomeSupport.toDayStart(dateRange.startDay);
        Date end = AppDistributorHomeSupport.toDayEnd(dateRange.endDay);

        AppDistributorTradeSummaryDto summary = appDistributorTradeMapper.selectTradeSummary(
                distributorId, start, end);
        List<AppDistributorAmountBucketDto> buckets;
        if (AppDistributorHomeRules.TREND_GRANULARITY_HOUR.equals(dateRange.trendGranularity))
        {
            buckets = appDistributorTradeMapper.selectHourlyAmountTrend(distributorId, start, end);
        }
        else
        {
            buckets = appDistributorTradeMapper.selectDailyAmountTrend(distributorId, start, end);
        }
        return AppDistributorHomeSupport.buildDashboard(normalized, summary, buckets, dateRange);
    }
}
