package cn.com.ctop.job.bytedance.handler;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceVideoReportService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.jeecg.common.util.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 BaseReportVideoDailyLoadJob {

    @Autowired
    ICtopOauthTokenService oauthTokenService;
    @Autowired
    IBytedanceVideoReportService bytedanceVideoReportService;
    private ExecutorService executorService = Executors.newFixedThreadPool(10);
    private CountDownLatch countDownLatch;
    //TODO --待废弃
    @XxlJob("baseReportVideoDailyLoadJob")
    public void execute() throws Exception {
        List<CtopOauthToken> tokens = oauthTokenService.selectToutiaoToken();
        countDownLatch = new CountDownLatch(tokens.size());
        String statDate= DateUtils.formatDate(DateUtils.addDay(new Date(), -1));
        tokens.forEach(token -> executorService.submit(() -> {
            try {
                bytedanceVideoReportService.pullVideoReport(token,statDate,statDate,1);
            } catch (Exception e) {
                XxlJobHelper.log("头条视频报表基础数据拉取异常：{}",e.getMessage());
            } finally {
                countDownLatch.countDown();
            }
        }));
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
