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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;

import lombok.extern.slf4j.Slf4j;

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.GAPagePathReport;
import org.jeecg.modules.adweb.dmp.mapper.GAPagePathReportMapper;
import org.jeecg.modules.adweb.dmp.service.IGAPagePathReportService;
import org.jeecg.modules.adweb.dmp.vo.report.PagePathStatsVO;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
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_page_path_report @Author: jeecg-boot @Date: 2024-10-11 @Version: V1.0
 */
@Service
@Slf4j
public class GAPagePathReportServiceImpl
        extends ServiceImpl<GAPagePathReportMapper, GAPagePathReport>
        implements IGAPagePathReportService {

    @Autowired private GAPagePathReportMapper gaPagePathReportMapper;

    @Autowired private IAdwebSiteService adwebSiteService;

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

        // 1. 网站URL及格式化
        AdwebSite adwebSite = adwebSiteService.getSiteByCode(siteCode);
        String siteUrl = StringUtils.removeEnd(Strings.nullToEmpty(adwebSite.getDomain()), "/");

        // 2. 时间区间内PV总数
        int totalPVs = gaPagePathReportMapper.countTotalPVs(siteCode, start, end);

        // 3. VO数据填充
        for (PagePathStatsVO pagePathStatsVO : pagePathStatsVOs) {
            pagePathStatsVO.setPagePath(siteUrl + pagePathStatsVO.getPagePath());
            pagePathStatsVO.setPvProportion(
                    NumberUtil.formatPercentage(
                            NumberUtil.safeDivide(pagePathStatsVO.getPageViews(), totalPVs), 2));
        }

        return pagePathStatsVOs;
    }
}
