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

import static org.jeecg.common.util.DateUtils.getAnotherDay;

/**
 * DONE
 * 头条预警
 *
 * @author yumeng
 */
@Slf4j
public class ByteDanceHourlyAccountWarningLoadJob implements Job {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IByteDanceHourlyAccountWarningService byteDanceHourlyAccountWarningService;
    static ExecutorService executorService = null;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                log.info("开始时段消耗预警定时任务");
                long l = System.currentTimeMillis();
                try {
                    List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
                    if (null == tokens || tokens.size() <= 0) {
                        log.info("定时获取头条数据异常：未获取到可用的token");
                        return;
                    }
                    executorService = Executors.newFixedThreadPool(3);
                    String statDate = DateUtils.getDate("yyyy-MM-dd");
                    String anotherDay = getAnotherDay("yyyy-MM-dd", statDate, -1);
                    for (CtopOauthToken token : tokens) {
                        executorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                byteDanceHourlyAccountWarningService.byteDanceAccountWarning(token.getAccountId(), statDate, anotherDay);
                            }

                        });
                    }
                    log.info("时段消耗预警定时任务执行完毕，耗时：{} ms", System.currentTimeMillis() - l);

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

                }
            }
        };
        thread.start();
    }
}
