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.report.entity.BytedanceReportPlayableRetry;
import com.xxl.job.executor.report.service.IBytedanceInterfaceService;
import com.xxl.job.executor.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class BytedanceDailyPlayableReportRetryJob {
    static ExecutorService executorService = Executors.newFixedThreadPool(4);
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IBytedanceInterfaceService bytedanceInterfaceService;


    @XxlJob("bytedanceDailyPlayableReportRetryJob")
    public void execute() throws Exception {
        XxlJobHelper.log("头条试玩报表重试定时任务开始");

        List<BytedanceReportPlayableRetry> retryList = bytedanceInterfaceService.getRetryList();
        retryList.forEach(retry -> {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        String startDate = retry.getStartDate();
                        String endDate = retry.getEndDate();
                        Long accountId = retry.getAccountId();
                        Integer type = retry.getType();
                        CtopOauthToken token = tokenService.getOauthTokenByAccountId(String.valueOf(accountId));
                        XxlJobHelper.log("头条试玩报表重试定时任务开始，当前accountId为：" + token.getAccountId());
                        Long days = DateUtils.getDiscrepantDays(startDate, endDate); //间隔天数
                        String start = null;
                        String end = null;
                        for (int i = 0; i <= days; i++) {
                            start = DateUtils.addDay(startDate, i);
                            end = start;
                            //获取头条素材报表数据
                            int code = bytedanceInterfaceService.bytedancePlayableReportRetry(type, token, start, end);
                            XxlJobHelper.log("头条试玩报表重试定时任务完成，当前accountId为：" + token.getAccountId() + "code:" + code);

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
        });
    }
}
