package org.jeecg.modules.ctop.job;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.toutiao.modules.report.service.IReportService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * DONE
 * @author syh
 * 头条广告主时报获取任务
 */
@Slf4j
public class BytedanceAdvertiserHourlyReportLoadJob implements Job {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IReportService reportService;
    static ExecutorService executorService = null;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("头条时报数据获取开始");
        Date getDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");
        String hour = simpleDateFormat.format(getDate);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
        if (null == tokens || tokens.size() <= 0) {
            log.info("定时获取头条小时数据异常：未获取到可用的token");
            return;
        }
        executorService = Executors.newFixedThreadPool(4);
        tokens.forEach(token -> {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    if (null != hour && "00".equals(hour)) {
                        Date  finalGetDate = DateUtils.addDay(getDate, -1);
                        //获取广告主信息数据
                        reportService.getAdvertiserReport(token, finalGetDate, finalGetDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
                    }
                    reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
                }

            });

        });
        log.info("头条时报数据获取结束");
    }
}
