package com.sptg.statistics.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.statistics.api.dto.StatisticsAdPushCountDto;
import com.sptg.statistics.api.dto.StatisticsAdPushDto;
import com.sptg.statistics.api.entity.StatisticsAdPush;
import com.sptg.statistics.api.entity.StatisticsAdPushCount;
import com.sptg.statistics.api.entity.StatisticsCount;
import com.sptg.statistics.biz.mapper.StatisticsAdPushMapper;
import com.sptg.statistics.biz.service.StatisticsAdPushCountServiceInterface;
import com.sptg.statistics.biz.service.StatisticsAdPushServiceInterface;
import com.sptg.statistics.biz.service.StatisticsCountServiceInterface;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * title: StatisticsAdPushServiceImpl
 * package: com.sptg.statistics.biz.security.impl
 * description: 统计广告发布-服务层实现类
 *
 *                
 *                 
 */
@Service
@AllArgsConstructor
public class StatisticsAdPushServiceImpl extends ServiceImpl<StatisticsAdPushMapper, StatisticsAdPush> implements StatisticsAdPushServiceInterface {

    private final StatisticsCountServiceInterface statisticsCountServiceInterface;
    private final StatisticsAdPushCountServiceInterface statisticsAdPushCountServiceInterface;

    @Override
    public Map<String,Object> statisticsAdPushTotal(StatisticsAdPushDto statisticsAdPushDto){
        EntityWrapper<StatisticsAdPush> wrapper=new EntityWrapper<StatisticsAdPush>();
        wrapper.setSqlSelect("COUNT(l_id) AS adExposureCount,COUNT(DISTINCT l_ad_content_id) AS adPushCount");
        //人脸广告类型
        wrapper.eq("i_task_type",OperationConstant.ONE);
        //根据机构
        if(StringUtils.isNotBlank(statisticsAdPushDto.getOrgPosition())) {
            wrapper.like("s_org_position", statisticsAdPushDto.getOrgPosition(), SqlLike.RIGHT);
        }
        return this.selectMap(wrapper);
    }

    @Override
    public Map<String,Object> statisticsCurrentMonthAdPushTotal(StatisticsAdPushDto statisticsAdPushDto){
        EntityWrapper<StatisticsAdPush> wrapper=new EntityWrapper<StatisticsAdPush>();
        wrapper.setSqlSelect("COUNT(l_id) AS adExposureCurrentMonthCount,COUNT(DISTINCT CONCAT(l_ad_push_task_id,l_ad_content_id)) AS adPushCurrentMonthCount");
        //任务广告类型
        Integer taskType=statisticsAdPushDto.getTaskType();
        if(null!=taskType){
            wrapper.eq("i_task_type",taskType);
        }
        //根据机构
        if(StringUtils.isNotBlank(statisticsAdPushDto.getOrgPosition())) {
            wrapper.like("s_org_position", statisticsAdPushDto.getOrgPosition(), SqlLike.RIGHT);
        }
        //查询当月时间
        wrapper.where("DATE_FORMAT(t_create_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m')");
        return this.selectMap(wrapper);
    }

    @Override
    public List<Map<String,Object>> statisticsAdPushAndExposure(StatisticsAdPushDto statisticsAdPushDto){
        EntityWrapper<StatisticsAdPush> wrapper=new EntityWrapper<StatisticsAdPush>();
        String sqlSelect="COUNT(l_id) AS adExposureCount,COUNT(DISTINCT CONCAT(l_ad_push_task_id,l_ad_content_id)) AS adPushCount";
        int dateType=statisticsAdPushDto.getDateType();
        //按某月的天数统计
        if(dateType==1){
            sqlSelect+=",DATE_FORMAT(t_create_date,'%d') AS day";
        }else{
            sqlSelect+=",DATE_FORMAT(t_create_date,'%m') AS month";
        }
        wrapper.setSqlSelect(sqlSelect);
        //省市区查询
        String province=statisticsAdPushDto.getDeviceRegionProvince();
        if(StringUtils.isNotBlank(province)){
            wrapper.eq("s_device_region_province", province);
        }
        String city=statisticsAdPushDto.getDeviceRegionCity();
        if(StringUtils.isNotBlank(city)){
            wrapper.eq("s_device_region_city", city);
        }
        String area=statisticsAdPushDto.getDeviceRegionArea();
        if(StringUtils.isNotBlank(area)){
            wrapper.eq("s_device_region_area", area);
        }

        //任务类型
        Integer taskType=statisticsAdPushDto.getTaskType();
        if(null!=taskType){
            wrapper.eq("i_task_type",taskType);
        }
        //时间查询
        Date date=statisticsAdPushDto.getStatisticsDate();
        //时间为空，就不统计
        if(date==null) {
            return null;
        }
        Calendar calendar= Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        if(dateType==1){
            wrapper.eq("DATE_FORMAT(t_create_date,'%Y%c')", year + ""+month);
            //按天分组
            wrapper.groupBy("day");
        }else{
            wrapper.eq("DATE_FORMAT(t_create_date,'%Y')", year + "");
            //按月分组
            wrapper.groupBy("month");
        }
        //根据机构
        if(StringUtils.isNotBlank(statisticsAdPushDto.getOrgPosition())) {
            wrapper.like("s_org_position", statisticsAdPushDto.getOrgPosition(), SqlLike.RIGHT);
        }
        return this.selectMaps(wrapper);
    }

    @Override
    public void updateOrgPosition(String oldPosition, String newPosition){
        this.baseMapper.updateOrgPosition(oldPosition,newPosition);
    }

    @Override
    @Async
    @Transactional(rollbackFor = {Exception.class})
    public void addAdPush(StatisticsAdPush statisticsAdPush){
        boolean result=this.insert(statisticsAdPush);
        if(result){
            //统计广告投放量,累计广告发布
            StatisticsCount statisticsCount=new StatisticsCount();
            statisticsCount.setAdExposureCount(OperationConstant.ONE);
            statisticsCount.setAdPushCount(statisticsAdPush.getAdPushCount());
            statisticsCount.setRootOrgId(statisticsAdPush.getRootOrgId());
            statisticsCount.setOrgPosition(statisticsAdPush.getOrgPosition());
            statisticsCountServiceInterface.addCount(statisticsCount);
        }
    }

    @Override
    @Async
    @Transactional(rollbackFor = {Exception.class})
    public void addAdPushList(List<StatisticsAdPush> statisticsAdPushList){
        for(StatisticsAdPush statisticsAdPush:statisticsAdPushList){
            //广告投放机构位置
            String orgPosition = statisticsAdPush.getOrgPosition();
            Long rootOrgId = statisticsAdPush.getRootOrgId();
            //获取推送中的广告条数
            StatisticsAdPushCountDto statisticsAdPushCountDto = new StatisticsAdPushCountDto();
            statisticsAdPushCountDto.setAdPushTaskId(statisticsAdPush.getAdPushTaskId());
            StatisticsAdPushCount statisticsAdPushCount = statisticsAdPushCountServiceInterface.getStatisticsAdPushCountByTaskId(statisticsAdPushCountDto);
            if(statisticsAdPushCount==null){
                continue;
            }
            //统计广告投放量
            StatisticsCount statisticsCount1=new StatisticsCount();
            Integer taskType = statisticsAdPush.getTaskType();
            if(null!=taskType&&taskType==2){
                //闲时广告发布
                statisticsCount1.setAdExposureFreeTimeCount(OperationConstant.ONE);
            }else{
                //人脸广告发布
                statisticsCount1.setAdExposureCount(OperationConstant.ONE);
            }
            statisticsCount1.setRootOrgId(rootOrgId);
            statisticsCount1.setOrgPosition(orgPosition);
            //统计广告发布数量累计
            Integer pushState = statisticsAdPushCount.getPushState();
            if(null!=pushState&&pushState==OperationConstant.ZERO){
                //0推送中状态增加发布数量
                if(null!=taskType&&taskType==2){
                    //闲时广告发布
                    statisticsCount1.setAdPushFreeTimeCount(statisticsAdPushCount.getCount());
                }else{
                    //人脸广告发布
                    statisticsCount1.setAdPushCount(statisticsAdPushCount.getCount());
                }

                //更新推送完成状态 1推送完成
                statisticsAdPushCountDto.setPushState(OperationConstant.ONE);
                statisticsAdPushCountServiceInterface.updateAdPushState(statisticsAdPushCountDto);
            }
            statisticsCountServiceInterface.addCount(statisticsCount1);
            //保存投放广告记录
            this.insert(statisticsAdPush);
        }
    }

    @Override
    public List<Map<String,Object>> statisticsAdPushAndExposureByArea(StatisticsAdPushDto statisticsAdPushDto){
        EntityWrapper<StatisticsAdPush> wrapper=new EntityWrapper<StatisticsAdPush>();
        String sqlSelect="COUNT(l_id) AS adExposureCount,s_device_region_province as regionProvince";
        wrapper.setSqlSelect(sqlSelect);
        //省市区查询
        String province=statisticsAdPushDto.getDeviceRegionProvince();
        if(StringUtils.isNotBlank(province)){
            wrapper.eq("s_device_region_province", province);
        }
        String city=statisticsAdPushDto.getDeviceRegionCity();
        if(StringUtils.isNotBlank(city)){
            wrapper.eq("s_device_region_city", city);
        }
        String area=statisticsAdPushDto.getDeviceRegionArea();
        if(StringUtils.isNotBlank(area)){
            wrapper.eq("s_device_region_area", area);
        }
        wrapper.groupBy("s_device_region_province");
        //根据机构
        if(StringUtils.isNotBlank(statisticsAdPushDto.getOrgPosition())) {
            wrapper.like("s_org_position", statisticsAdPushDto.getOrgPosition(), SqlLike.RIGHT);
        }
        //人脸广告类型
        wrapper.eq("i_task_type",OperationConstant.ONE);
        return this.selectMaps(wrapper);
    }

    @Override
    public long statisticsAdPushCount(StatisticsAdPushDto statisticsAdPushDto){
        EntityWrapper<StatisticsAdPush> wrapper=new EntityWrapper<StatisticsAdPush>();
        wrapper.setSqlSelect("COUNT(l_id)");

        String deviceRegionProvince = statisticsAdPushDto.getDeviceRegionProvince();
        if(StringUtils.isNotBlank(deviceRegionProvince)){
            wrapper.eq("s_device_region_province",deviceRegionProvince);
        }

        //当月新增
        if(OperationConstant.TWO == statisticsAdPushDto.getIsAllType()){
            wrapper.and("DATE_FORMAT(t_create_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m')");
        }
        //根据机构
        if(StringUtils.isNotBlank(statisticsAdPushDto.getOrgPosition())) {
            wrapper.like("s_org_position", statisticsAdPushDto.getOrgPosition(), SqlLike.RIGHT);
        }
        long count=(long)this.selectObj(wrapper);
        return count;
    }

}
