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.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

    @XxlJob("bytedanceCampaignDailyReport")
    public void execute() throws Exception {
        XxlJobHelper.log("头条广告组日报获取任务执行开始");
        Date getDate = DateUtils.addDay(new Date(), -1);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        CountDownLatch countDownLatch = new CountDownLatch(tokens.size());
        tokens.forEach(token -> executorService.submit(() -> {
            try {
                reportService.getAdvertiserCampaignReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }));
        countDownLatch.await();
        XxlJobHelper.log("头条广告组日报获取任务执行结束");
    }
}
