package com.xxl.job.executor.jobhandler;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.common.service.ICtopOauthTokenService;
import com.xxl.job.executor.report.service.IReportService;
import com.xxl.job.executor.utils.CtopAdConstant;
import com.xxl.job.executor.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class BytedanceCampaignHourlyReportLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IReportService reportService;
    static ExecutorService executorService = Executors.newFixedThreadPool(4);

    @XxlJob("bytedanceCampaignHourlyReport")
    public void execute() throws Exception {
        XxlJobHelper.log("头条广告组时报数据获取开始");
        Date getDate = new Date();
        String hour = DateUtils.getNowHour(getDate);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        if (null == tokens || tokens.isEmpty()) {
            XxlJobHelper.log("定时获取头条小时数据异常：未获取到可用的token");
        }
        tokens.forEach(token -> executorService.submit(() -> {
            if ("00".equals(hour)) {
                Date finalGetDate = DateUtils.addDay(getDate, -1);
                //获取广告主信息数据
                reportService.getAdvertiserCampaignReport(token, finalGetDate, finalGetDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
            }
            reportService.getAdvertiserCampaignReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
        }));
        XxlJobHelper.log("头条广告组时报数据获取结束");
    }
}
