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.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouStrategyService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouAudienceReportDailyService;
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.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 快手广告主分天数据
 *
 * @author syh
 */
@Component
public class KuaishouDailyAudienceReportJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouAudienceReportDailyService kuaishouAudienceReportDailyService;
    @Autowired
    private IKuaiShouGroupService kuaiShouGroupService;
    @Autowired
    private IKuaishouStrategyService kuaishouStrategyService;

    static ExecutorService executorService = Executors.newFixedThreadPool(6);

    @XxlJob("kuaishouDailyAudienceReportJob")
    public void execute() throws Exception {
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        if (null == tokens || tokens.isEmpty()) {
            XxlJobHelper.log("定时获取人群分析报表数据异常：未获取到可用的token");
            XxlJobHelper.handleFail();
            return;
        }
        //查询有效策略的账户ID
        List<Long> accountIds = kuaishouStrategyService.queryActiveAccount();
        if (Check.isNull(accountIds) || accountIds.size() == 0) {
            XxlJobHelper.log("定时获取人群分析报表数据异常：未获取到有效策略账户信息");
            XxlJobHelper.handleFail();
            return;
        }
        //筛选出有效账户，获取该账户的组级人群报表数据
        List<CtopOauthToken> activeTokens = new ArrayList<>();
        for (Long accountId : accountIds) {
            for (CtopOauthToken token : tokens) {
                if (token.getAccountId() - accountId == 0) {
                    activeTokens.add(token);
                }
            }
        }
        if (!Check.isNull(activeTokens) && activeTokens.size() > 0) {
            int page = 1;
            int pageSize = 2000;
            //查询两天前日期
            String date = DateUtils.getLastDay(DateUtils.date2Str(), 2);
            activeTokens.forEach(token -> executorService.submit(() -> {
                getAudienceReportData(token, date, "province", page, pageSize);
                getAudienceReportData(token, date, "city", page, pageSize);
                getAudienceReportData(token, date, "gender", page, pageSize);
                getAudienceReportData(token, date, "ageSegment", page, pageSize);
                getAudienceReportData(token, date, "clientId", page, pageSize);
                getAudienceReportData(token, date, "businessInterestTags", page, pageSize);
            }));
        }
    }

    private void getAudienceReportData(CtopOauthToken token, String date, String type, Integer page, Integer pageSize) {
        try {
            List<KuaiShouGroup> kuaiShouGroups = kuaiShouGroupService.queryUnitInfoByAccountId(token.getAccountId());
            for (KuaiShouGroup kuaiShouGroup : kuaiShouGroups) {
                kuaishouAudienceReportDailyService.crowdAnalysisReport(token, date, type, kuaiShouGroup.getCampaignId(), kuaiShouGroup.getUnitId(), page, pageSize);
            }
        } catch (Exception e) {
            XxlJobHelper.log("定时获取人群分析报表数据异常", e);
        }
    }
}
