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

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

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.adweb.common.util.NumberUtil;
import org.jeecg.modules.adweb.dmp.entity.GACountryReport;
import org.jeecg.modules.adweb.dmp.mapper.GACountryReportMapper;
import org.jeecg.modules.adweb.dmp.service.IGACountryReportService;
import org.jeecg.modules.adweb.dmp.vo.report.CountryStatsVO;
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: dmp_ga_country_report @Author: jeecg-boot @Date: 2024-10-11 @Version: V1.0
 */
@Service
public class GACountryReportServiceImpl extends ServiceImpl<GACountryReportMapper, GACountryReport>
        implements IGACountryReportService {

    @Autowired private GACountryReportMapper gaCountryReportMapper;

    @Override
    @Cacheable(
            cacheManager = CacheConfig.TTL_CACHE_MANAGER,
            cacheNames =
                    "getCountryStats" + TTLCacheManager.TTL_SPLITTER + 60 * 30) // Redis TTL为半小时
    public List<CountryStatsVO> getCountryStats(String siteCode, Date start, Date end) {
        List<CountryStatsVO> countryStatsVOs =
                gaCountryReportMapper.getCountryStats(siteCode, start, end);
        if (CollectionUtils.isEmpty(countryStatsVOs)) {
            return Collections.EMPTY_LIST;
        }

        // 1. 时间区间内所有国家totalUsers总数
        int totalUsersSum = countryStatsVOs.stream().mapToInt(CountryStatsVO::getTotalUsers).sum();

        // 2. VO数据填充
        for (CountryStatsVO countryStatsVO : countryStatsVOs) {
            // adweb_country表无记录时，如CountryStatsVO.country = (not set)
            if (StringUtils.isBlank(countryStatsVO.getCountryName())
                    || StringUtils.isBlank(countryStatsVO.getCountryCode())) {
                countryStatsVO.setCountryName(countryStatsVO.getCountry());
                countryStatsVO.setCountryCode(countryStatsVO.getCountry());
            }

            countryStatsVO.setTotalUsersProportion(
                    NumberUtil.formatPercentage(
                            NumberUtil.safeDivide(countryStatsVO.getTotalUsers(), totalUsersSum),
                            2));
        }

        return countryStatsVOs;
    }
}
