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.kuaishou.modules.batch.service.IKuaiShouDailyReportTaskService;
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.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

/**
 * 获取文件状态并下载入库
 *
 * @author yumeng
 */
@Slf4j
public class KuaishouDailyLoadFileJob implements Job {
    @Autowired
    private ICtopOauthTokenService tokenService;
    static ExecutorService executorService = null;
    static CountDownLatch countDownLatch = null;
    @Autowired
    private IKuaiShouDailyReportTaskService dailyReportTaskService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                String nowDate = DateUtils.getDate("yyyy-MM-dd");
                String statDate = getAnotherDay("yyyy-MM-dd", nowDate, -1);
                //  查询快手token
                List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
                if (null == tokens || tokens.size() <= 0) {
                    log.info("定时获取快手数据异常：未获取到可用的token");
                    return;
                }
                executorService = Executors.newFixedThreadPool(3);
                countDownLatch = new CountDownLatch(tokens.size());
                for (CtopOauthToken token : tokens) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                dailyReportTaskService.getTaskList(token.getAccountId(), token.getAccessToken(), statDate);
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                countDownLatch.countDown();
                            }
                        }
                    });
                }
                executorService.shutdown();
            }
        };
        thread.start();

    }


}
