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.material.service.IByteDanceAdvertiserDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class BytedanceMaterialsLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    static ExecutorService executorService = Executors.newFixedThreadPool(4);
    //线程计数器
    static CountDownLatch countDownLatch = null;
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;

    @XxlJob("bytedanceMaterialsLoadJob")
    public void execute() throws Exception{
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        countDownLatch = new CountDownLatch(tokens.size());
        tokens.forEach(token -> {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        //获取全量视频素材数据
                        advertiserDataService.getMaterialList(token);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        XxlJobHelper.log("物料数据同步完成");
    }
}
