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.KuaishouBatchCampaignPreview;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouBatchCampaignPreviewService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class KuaishouBatchCampaignTimeStartJob {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouBatchCampaignPreviewService campaignPreviewService;
    @Autowired
    private IKuaiShouUpdateService kuaiShouUpdateService;
    static ExecutorService executorService = Executors.newFixedThreadPool(5);

    /**
     * 批量创建——定时启动广告计划
     * @throws Exception
     */
    @XxlJob("kuaishouBatchCampaignTimeStartJob")
    public void execute() throws Exception {
        List<KuaishouBatchCampaignPreview> campaignPreviewList = campaignPreviewService.queryListByTime();
        if (!Check.isNull(campaignPreviewList)) {
            campaignPreviewList.forEach(campaignPreview -> executorService.submit(() -> {
                CtopOauthToken token = tokenService.getTokenByAccountId(campaignPreview.getAccountId());
                if (!Check.isNull(token)) {
                    Map<String, Object> map = kuaiShouUpdateService.updateCampaignStatus(token.getAccessToken(), campaignPreview.getAccountId(), campaignPreview.getCampaignId(), 1, "timingStart");
                    if ((boolean) map.get("success")) {
                        QueryWrapper<KuaishouBatchCampaignPreview> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("id", campaignPreview.getId());
                        KuaishouBatchCampaignPreview campaign = new KuaishouBatchCampaignPreview();
                        campaign.setMessage("定时启动成功！");
                        campaignPreviewService.update(campaign, queryWrapper);
                    }
                }
            }));
            XxlJobHelper.log("计划定时启动完成");
        }
    }

}
