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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 获取广告计划分时报表
 *
 * @author syh
 */
@Component
public class KuaishouHourlyCampaignReportLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;

    static ExecutorService executorService = Executors.newFixedThreadPool(5);

    //TODO 待删除
    @XxlJob("kuaishouHourlyCampaignReport")
    public void execute() throws Exception {
        Date getDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");
        String hour = simpleDateFormat.format(getDate);
        if (null != hour && "00".equals(hour)) {
            getDate = DateUtils.addDay(getDate, -1);
        }
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        if (null == tokens || tokens.size() <= 0) {
            XxlJobHelper.log("定时获取快手数据异常：未获取到可用的token");
            XxlJobHelper.handleFail();
            return ;
        }
        Date finalGetDate = getDate;
        tokens.forEach(token -> executorService.submit(() -> kuaishouInterfaceService.getAdvertiserCampaignReportHourly(token, finalGetDate, finalGetDate)));
    }
}
