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

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.service.IEnquiryReportService;
import org.jeecg.modules.adweb.dmp.vo.report.EnquiryCountryStatsVO;
import org.jeecg.modules.adweb.enquiry.mapper.AdwebEnquiryMapper;
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;

/**
 * @author wfansh
 */
@Service
public class EnquiryReportServiceImpl implements IEnquiryReportService {

    @Autowired private AdwebEnquiryMapper adwebEnquiryMapper;

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

        // 1. 时间区间内所有国家enquires总数
        int enquiresSum =
                enquiryCountryStatsVOs.stream().mapToInt(EnquiryCountryStatsVO::getEnquires).sum();

        // 2. VO数据填充
        for (EnquiryCountryStatsVO enquiryCountryStatsVO : enquiryCountryStatsVOs) {
            // adweb_country表无记录时，如EnquiryCountryStatsVO.countryCode为空或无效
            if (StringUtils.isBlank(enquiryCountryStatsVO.getCountry())
                    || StringUtils.isBlank(enquiryCountryStatsVO.getCountryName())) {
                enquiryCountryStatsVO.setCountry(enquiryCountryStatsVO.getCountryCode());
                enquiryCountryStatsVO.setCountryName(enquiryCountryStatsVO.getCountryCode());
            }

            enquiryCountryStatsVO.setEnquiresProportion(
                    NumberUtil.formatPercentage(
                            NumberUtil.safeDivide(enquiryCountryStatsVO.getEnquires(), enquiresSum),
                            2));
        }

        return enquiryCountryStatsVOs;
    }
}
