package org.jeecg.modules.ctop.job;


import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceReportService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

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

@Slf4j
public class ToutiaoMaterialsLoadJob implements Job {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IBytedanceReportService bytedanceReportService;

    static ExecutorService executorService = null;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                //增加接口的开始和结束日期
                String startDate = DateUtils.formatDate(DateUtils.addDay(new Date(), -1));
                String endDate = startDate;
                //获取头条token数据
                List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
                executorService = Executors.newFixedThreadPool(8);
                tokens.forEach(token -> {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //获取头条素材报表数据
                                bytedanceReportService.bytedanceMaterialReport(token,startDate,endDate);
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                            }
                        }
                    });
                });
                log.info("头条素材数据同步完成，"+ "开始时间：" + startDate + "，结束时间：" + endDate);
            }
        };
        thread.start();

    }
}
