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.common.module.utils.CtopAdConstant;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouHistoryReportTaskService;
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;

@Component
public class KuaishouDailyReportTaskJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaiShouHistoryReportTaskService reportTaskService;

    /**
     * 快手异步日报任务创建
     * @throws Exception
     */
    @XxlJob("kuaishouDailyReportTask")
    public void execute() throws Exception {
        XxlJobHelper.log("快手获取日报数据任务执行开始");
        Long start = System.currentTimeMillis();
        Date getDate = DateUtils.addDay(new Date(), -1);
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        if (null == tokens || tokens.isEmpty()) {
            XxlJobHelper.log("快手获取日报数据任务执行失败:未获取到可用的token");
            XxlJobHelper.handleFail();
            return ;
        }
        String getDateStr = DateUtils.formatDate(getDate);
        tokens.forEach(token -> reportTaskService.createTask(token.getAccountId(), token.getAccessToken(), getDateStr, getDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_DAILY));
        Long end = System.currentTimeMillis();
        XxlJobHelper.log("快手获取日报数据任务执行结束,执行耗时：{}秒", (end - start) / 1000);
    }
}
