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.report.service.IByteDanceHourlyAccountWarningService;
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.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 头条预警
 *
 * @author yumeng
 */
@Component
public class ByteDanceHourlyAccountWarningLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IByteDanceHourlyAccountWarningService byteDanceHourlyAccountWarningService;
    static ExecutorService executorService = Executors.newFixedThreadPool(3);

    @XxlJob("byteDanceHourlyAccountWarning")
    public void execute() throws Exception {
        XxlJobHelper.log("开始时段消耗预警定时任务");
        long startTime = System.currentTimeMillis();
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        if (null == tokens || tokens.isEmpty()) {
            XxlJobHelper.log("定时获取头条数据异常：未获取到可用的token");
            XxlJobHelper.handleFail();
            return ;
        }
        String statDate = DateUtils.formatDate();
        String anotherDay = DateUtils.getAnotherDay("yyyy-MM-dd", statDate, 1);
        tokens.forEach(token -> executorService.submit(() -> byteDanceHourlyAccountWarningService.byteDanceAccountWarning(token.getAccountId(), statDate, anotherDay)));
        XxlJobHelper.log("时段消耗预警定时任务执行完毕，耗时：{} ms", System.currentTimeMillis() - startTime);
    }
}
