package org.jeecg.modules.adweb.dmp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.modules.adweb.common.util.NumberUtil;
import org.jeecg.modules.adweb.dmp.entity.GASourceMediumReport;
import org.jeecg.modules.adweb.dmp.mapper.GASourceMediumReportMapper;
import org.jeecg.modules.adweb.dmp.service.IGASourceMediumReportService;
import org.jeecg.modules.adweb.dmp.vo.report.SourceMediumStatsVO;
import org.jeecg.modules.redis.CacheConfig;
import org.jeecg.modules.redis.TTLCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Description: adweb_dmp_ga_source_medium_report @Author: jeecg-boot @Date: 2024-10-11 @Version: V1.0
 */
@Service
public class GASourceMediumReportServiceImpl
        extends ServiceImpl<GASourceMediumReportMapper, GASourceMediumReport>
        implements IGASourceMediumReportService {

    @Autowired private GASourceMediumReportMapper gaSourceMediumReportMapper;

    @Override
    @Cacheable(
            cacheManager = CacheConfig.TTL_CACHE_MANAGER,
            cacheNames =
                    "dmp:getSourceMediumStats"
                            + TTLCacheManager.TTL_SPLITTER
                            + 60 * 10) // Redis TTL为10分钟
    public List<SourceMediumStatsVO> getSourceMediumStats(String siteCode, Date start, Date end) {
        List<SourceMediumStatsVO> sourceMediumStatsVOs =
                gaSourceMediumReportMapper.getSourceMediumStats(siteCode, start, end);
        if (CollectionUtils.isEmpty(sourceMediumStatsVOs)) {
            return Collections.EMPTY_LIST;
        }

        // 1. 时间区间内所有媒介totalUsers总数
        int totalUsersSum =
                sourceMediumStatsVOs.stream().mapToInt(SourceMediumStatsVO::getTotalUsers).sum();

        // 2. VO数据填充
        for (SourceMediumStatsVO sourceMediumStatsVO : sourceMediumStatsVOs) {
            int totalUsers = sourceMediumStatsVO.getTotalUsers();
            sourceMediumStatsVO.setTotalUsersProportion(
                    NumberUtil.formatPercentage(
                            NumberUtil.safeDivide(totalUsers, totalUsersSum), 2));

            sourceMediumStatsVO.setNewUsersRatio(
                    NumberUtil.formatPercentage(
                            NumberUtil.safeDivide(sourceMediumStatsVO.getNewUsers(), totalUsers),
                            2));
        }

        return sourceMediumStatsVOs;
    }
}
