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.IKuaiShouCampaignService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import com.alibaba.fastjson.JSONArray;
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.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 获取创意分天报表
 *
 * @author jeecg-boot
 */
@Component
public class KuaishouDailyCreativeReportLoadJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;

    static ExecutorService executorService = Executors.newFixedThreadPool(4);

    @Autowired
    private IKuaiShouCampaignService campaignService;

    @XxlJob("kuaishouDailyCreativeReport")
    public void execute() throws Exception {
        Date getDate = DateUtils.addDay(new Date(), -1);
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        if (null == tokens || tokens.size() <= 0) {
            XxlJobHelper.log("定时获取快手数据异常：未获取到可用的token");
            XxlJobHelper.handleFail();
            return ;
        }
        tokens.forEach(token -> {
            XxlJobHelper.log("获取创意分天报表开始,accountId:{}", token.getAccountId());
            kuaishouInterfaceService.getCampaignList(token, null, null);
            try {
                Thread.sleep(5 * 100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            List<JSONArray> campaigns = campaignService.getJsonArrByAccount(token.getAccountId(), 50);
            if (null != campaigns && !campaigns.isEmpty()) {
                campaigns.forEach(campaign -> executorService.submit(() -> kuaishouInterfaceService.getAdvertiserCreativeReportDaily(token, getDate, getDate, campaign, null)));
            }
        });
    }

}
