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.common.module.utils.CtopAdConstant;
import cn.com.ctop.toutiao.modules.report.service.IReportService;
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.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author syh
 * 头条创意时报获取任务
 */
@Component
public class BytedanceCreativeHourlyReportLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IReportService reportService;
    static ExecutorService executorService = Executors.newFixedThreadPool(4);

    /**
     * 头条创意时报
     * @throws Exception
     */
    @XxlJob("bytedanceCreativeHourlyReport")
    public void execute() throws Exception {
        XxlJobHelper.log("头条时报数据获取开始");
        Date now = new Date();
        String hour = DateUtils.getNowHour(now);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        if (null == tokens || tokens.isEmpty()) {
            XxlJobHelper.log("定时获取头条小时数据异常：未获取到可用的token");
            XxlJobHelper.handleFail();
            return ;
        }
        tokens.forEach(token -> executorService.submit(() -> {
            if ("00".equals(hour)) {
                Date finalGetDate = DateUtils.addDay(now, -1);
                //获取广告创意信息数据
                reportService.getAdvertiserCreativeReport(token, finalGetDate, finalGetDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
            }
            reportService.getAdvertiserCreativeReport(token, now, now, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
        }));
        XxlJobHelper.log("头条时报数据获取结束");
    }
}
