package cn.com.ctop.job.bytedance.handler;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.toutiao.modules.report.entity.BytedanceCheckReportTaskInfo;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceCheckReportTaskInfoService;
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 javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class BytedanceCheckAccountReportJob {
    private ExecutorService executorService = Executors.newFixedThreadPool(10);
    private CountDownLatch countDownLatch;
    @Autowired
    private IBytedanceCheckReportTaskInfoService checkReportTaskInfoService;


    /**
     * 头条数据检查任务
     * @throws Exception
     */
    @XxlJob("initCheckReportJob")
    public void initCheckReportJob() throws Exception {
        String date = DateUtils.addDay(DateUtils.formatDate(),-1);
        String param = XxlJobHelper.getJobParam();
        if (param==null || param.trim().length()==0) {
            param = date;
        }
        checkReportTaskInfoService.initTask(param);
        //查询初始化的任务
        List<BytedanceCheckReportTaskInfo>taskInfos = checkReportTaskInfoService.getListByParams(null,param,0);
        if(null!=taskInfos&&!taskInfos.isEmpty()){
            countDownLatch = new CountDownLatch(taskInfos.size());
            taskInfos.forEach(taskInfo ->executorService.submit(()->{
                try {
                    checkReportTaskInfoService.checkCost(taskInfo);
                }catch (Exception e){
                }finally {
                    countDownLatch.countDown();
                }
            }));
            countDownLatch.await();
            XxlJobHelper.log("{}数据初始化完成",date);
        }
    }

    /**
     * 头条数据重试
     * @throws Exception
     */
    @XxlJob("refreshCheckReportJob")
    public void refreshCheckReportJob() throws Exception {
        //1：查询异常任务数据
        List<BytedanceCheckReportTaskInfo>taskInfos = checkReportTaskInfoService.getListByParams(null,null,50001);
        if(null!=taskInfos&&!taskInfos.isEmpty()){
            countDownLatch = new CountDownLatch(taskInfos.size());
            taskInfos.forEach(taskInfo -> {
                try {
                    checkReportTaskInfoService.reloadData(taskInfo);
                    checkReportTaskInfoService.checkCost(taskInfo);
                }catch (Exception e){
                }finally {
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            XxlJobHelper.log("数据更新完成");
        }
    }
}
