package com.sptg.ad.biz.quartz;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.ad.api.entity.DeviceAdvertStatistics;
import com.sptg.ad.biz.service.DeviceAdvertService;
import com.sptg.ad.biz.service.DeviceAdvertStatisticsService;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.interfaces.VoidInterface;
import com.sptg.common.core.util.DateUtil;
import com.sptg.statistics.api.dto.StatisticsAdPlayFreeTimeDto;
import com.sptg.statistics.api.dto.StatisticsAdWatchDto;
import com.sptg.statistics.api.feigns.StatisticsAdWatchFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 *            
 *               
 * description: 设备广告定时任务
 */
@Slf4j
@Component
@AllArgsConstructor
public class DeviceAdvertStatisticsQuartzTask {

    private final DeviceAdvertStatisticsService deviceAdvertStatisticsService;
    private final DeviceAdvertService deviceAdvertService;
    private final StatisticsAdWatchFeign statisticsAdWatchFeign;

    /**
     * 每月1号0时执行
     * 将上个月的统计记录复制到当月
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void monthly(){
        this.pagingQuery(statistics ->
                this.deviceAdvertStatisticsService.selectCurrentMonthAdvertStatistics(statistics.getDeviceId(),statistics.getTaskType()));
    }

    /**
     * 每天1时执行一次
     * 同步设备当前广告和预警的数量
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void onceDay(){
        this.pagingQuery2(statistics -> {
            //  获取设备的广告数量
            int advertCount = this.deviceAdvertService.selectDeviceAdvertCount(statistics.getDeviceSerialNumber(), statistics.getTaskType());
            statistics.setAdCount(advertCount);
            //  TODO 统计浏览量
            Integer taskType = statistics.getTaskType();
            Calendar calendar= Calendar.getInstance();
            calendar.setTime(new Date());
            if(null!=taskType&&taskType== OperationConstant.ONE){//人脸广告
                StatisticsAdWatchDto dto=new StatisticsAdWatchDto();
                dto.setSerialNumber(statistics.getDeviceSerialNumber());
                calendar.add(Calendar.MONTH,-1);
                dto.setSelectMonth(calendar.getTime());
                //上一个月观看次数
               Long lastMonthCount=statisticsAdWatchFeign.getAdWatchCount(dto);
               statistics.setLastMonthBrowse(lastMonthCount.intValue());
               //当前月
                calendar.add(Calendar.MONTH,1);
                dto.setSelectMonth(calendar.getTime());
                //获取当前时间是当月第几周
                calendar.setFirstDayOfWeek(Calendar.MONDAY);
                int currentWeek = calendar.get(Calendar.WEEK_OF_MONTH);
                if(currentWeek!=5){//没有第五周
                    for(int i = 1; currentWeek + i < 5; i++){
                        //获取当前周于其他周相差值
                        int preWeek = currentWeek - i;
                        //获取第几周统计次数
                        int yearWeek = DateUtil.getYearWeek(calendar.getTime(), Calendar.MONTH) - i;
                        dto.setYearWeek(yearWeek);
                        Long count=statisticsAdWatchFeign.getAdWatchCount(dto);
                        //获取当周数据
                        this.setWeekBrowse(statistics,preWeek, i,count.intValue());
                   }
                }
                StatisticsAdWatchDto dto1=new StatisticsAdWatchDto();
                dto1.setSerialNumber(statistics.getDeviceSerialNumber());
                Long countAll = this.statisticsAdWatchFeign.getAdWatchCount(dto1);
                statistics.setBrowseCount(countAll);
            }else if(null!=taskType&&taskType==OperationConstant.TWO){//闲时广告
                StatisticsAdPlayFreeTimeDto dto=new StatisticsAdPlayFreeTimeDto();
                //设备
                dto.setSerialNumber(statistics.getDeviceSerialNumber());
                calendar.add(Calendar.MONTH,-1);
                dto.setSelectMonth(calendar.getTime());
                //上一个月播放次数
                Long lastMonthCount=statisticsAdWatchFeign.getAdPlayCount(dto);
                statistics.setLastMonthBrowse(lastMonthCount.intValue());
                //当前月
                calendar.add(Calendar.MONTH,1);
                dto.setSelectMonth(calendar.getTime());
                //获取当前时间是当月第几周
                calendar.setFirstDayOfWeek(Calendar.MONDAY);
                int currentWeek = calendar.get(Calendar.WEEK_OF_MONTH);
                if(currentWeek!=5){//没有第五周
                    for(int i = 1; currentWeek + i < 5; i++){
                        //获取当前周于其他周相差值
                        int preWeek = currentWeek - i;
                        //获取第几周统计次数
                        int yearWeek = DateUtil.getYearWeek(calendar.getTime(), Calendar.MONTH) - i;
                        dto.setYearWeek(yearWeek);
                        Long count=statisticsAdWatchFeign.getAdPlayCount(dto);
                        //获取当周数据
                        this.setWeekBrowse(statistics, preWeek, i, count.intValue());
                    }
                }
                StatisticsAdPlayFreeTimeDto dto2 = new StatisticsAdPlayFreeTimeDto();
                dto2.setSerialNumber(statistics.getDeviceSerialNumber());
                Long countAll = this.statisticsAdWatchFeign.getAdPlayCount(dto2);
                statistics.setBrowseCount(countAll);
            }

            this.deviceAdvertStatisticsService.updateById(statistics);
        });
    }

    private void pagingQuery(VoidInterface<DeviceAdvertStatistics> voidInterface){
        //  分页查询上个月的设备统计记录
        DeviceAdvertStatistics dto = new DeviceAdvertStatistics();
        dto.setCreateTime(LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM")));
        PageBean<DeviceAdvertStatistics, DeviceAdvertStatistics> pageBean = new PageBean<>(dto);
        pageBean.setSize(100);
        int pageNo = 0;
        while (true){
            ++ pageNo;
            pageBean.setCurrent(pageNo);
            Page<DeviceAdvertStatistics> page = this.deviceAdvertStatisticsService.pagingQuery(pageBean);
            if (page.getRecords().size() == 0){
                break;
            }
            page.getRecords().forEach(voidInterface::run);
        }
    }

    private void pagingQuery2(VoidInterface<DeviceAdvertStatistics> voidInterface){
        DeviceAdvertStatistics dto = new DeviceAdvertStatistics();
        PageBean<DeviceAdvertStatistics, DeviceAdvertStatistics> pageBean = new PageBean<>(dto);
        pageBean.setSize(100);
        int pageNo = 0;
        while (true){
            ++ pageNo;
            pageBean.setCurrent(pageNo);
            Page<DeviceAdvertStatistics> page = this.deviceAdvertStatisticsService.pagingQuery(pageBean);
            if (page.getRecords().size() == 0){
                break;
            }
            page.getRecords().forEach(voidInterface::run);
        }
    }
    /**
     * 功能描述:获取当月第几周统计数据
     * @param statistics 统计实体
     * @param week 当前第几周
     * @param temp 统计周与当前周差值
     * @param count 数据值
     * @return void
     *                
     *                      
     */
    private void setWeekBrowse(DeviceAdvertStatistics statistics, int week, int temp, int count){
        switch (week){
            case 1:
                //第一周
                Integer week1Browse=statistics.getWeek1Browse();
                if(temp!=0&&(null==week1Browse||week1Browse==0)){
                    //不是当前周，且这周数据为空或者0的话，就可以更新
                    statistics.setWeek1Browse(count);
                }
                break;
            case 2:
                //第二周
                Integer week2Browse=statistics.getWeek2Browse();
                if(temp!=0&&(null==week2Browse||week2Browse==0)){
                    statistics.setWeek2Browse(count);
                }
                break;
            case 3:
                //第三周
                Integer week3Browse=statistics.getWeek3Browse();
                if(temp!=0&&(null==week3Browse||week3Browse==0)){
                    statistics.setWeek3Browse(count);
                }
                break;
            case 4:
                //第四周
                Integer week4Browse=statistics.getWeek4Browse();
                if(temp!=0&&(null==week4Browse||week4Browse==0)){
                    statistics.setWeek4Browse(count);
                }
                break;
            default:
                break;
        }
    }
}
