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.material.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCampaignService;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCreativeService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 头条广告物料数据获取任务
 * @author 宋英豪
 */
@Component
public class BytedanceAdvertisingDataLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    static ExecutorService executorService = Executors.newFixedThreadPool(5);
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;
    @Autowired
    private IByteDanceCampaignService campaignService;
    @Autowired
    private IByteDanceCreativeService creativeService;

    @XxlJob("bytedanceAdvertisingData")
    public void execute() throws Exception {
        Date getDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = dateFormat.format(getDate);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        tokens.forEach(token -> executorService.submit(() -> {
            try {
                //1：获取当日广告组数据
                campaignService.getAdvertiserCampaign(token, null, dateString);
                //2：获取当日广告计划数据
                advertiserDataService.getAdvertiserPlan(token, "", dateString, null);
                //3：获取当日创意数据
                creativeService.getAdvertiserCreative(token, "", dateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }));
        XxlJobHelper.log("物料数据同步完成");
    }
}
