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.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.springframework.beans.factory.annotation.Autowired;
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
    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) {
            countryStatsVO.setTotalUsersProportion(
                    NumberUtil.formatPercentage(
                            totalUsersSum == 0
                                    ? 0
                                    : (double) countryStatsVO.getTotalUsers() / totalUsersSum,
                            2));
        }

        return countryStatsVOs;
    }
}
