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.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_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
    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(
                            totalUsersSum == 0 ? 0 : (double) totalUsers / totalUsersSum, 2));

            sourceMediumStatsVO.setNewUsersRatio(
                    NumberUtil.formatPercentage(
                            totalUsers == 0
                                    ? 0
                                    : (double) sourceMediumStatsVO.getNewUsers() / totalUsers,
                            2));
        }

        return sourceMediumStatsVOs;
    }
}
