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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IRuleDataCreativeService;
import cn.com.ctop.common.module.service.IRuleDataPlanService;
import cn.com.ctop.common.module.service.IRuleDataTargetService;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.toutiao.modules.report.service.IReportService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class ByteDancePlanRuleDataJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IReportService reportService;
    @Autowired
    private IRuleDataPlanService ruleDataPlanService;
    @Autowired
    private IRuleDataCreativeService ruleDataCreativeService;
    @Autowired
    private IRuleDataTargetService ruleDataTargetService;
    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * 规则引擎计划数据任务
     * @throws Exception
     */
    @XxlJob("bytedancePlanRuleLoadJob")
    public void execute() throws Exception {
        Date date = new Date();
        List<CtopOauthToken> tokens = tokenService.queryTtValidRuleAccountsToken();
        tokens.forEach(token -> executorService.submit(()->{
            //1:删除历史数据
            Map<String,Object> params = new HashMap<>();
            params.put("account_id",token.getAccountId());
            ruleDataPlanService.removeByMap(params);
            ruleDataTargetService.removeByMap(params);
            ruleDataCreativeService.removeByMap(params);
            reportService.getAdvertiserPlanRuleData(token,date,date, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        }));
    }
}
