package cn.com.ctop.kuaishou.modules.ai.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.MaterialCutFrame;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.ai.entity.*;
import cn.com.ctop.kuaishou.modules.ai.enums.KuaishouCreativeAdsenceTypeEnum;
import cn.com.ctop.kuaishou.modules.ai.enums.KuaishouCreativeMatTypeEnum;
import cn.com.ctop.kuaishou.modules.ai.service.*;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouAppList;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Slf4j
@Service
public class AiKuaishouCreateCreativeServiceImpl implements IAiKuaishouCreateCreativeService {
    @Autowired
    private IKuaiShouGroupService groupService;
    @Autowired
    private IKuaiShouGroupTemplateService groupTemplateService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;
    @Autowired
    private IMaterialCutFrameService materialCutFrameService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService materialUploadService;
    @Autowired
    private IKuaishouAccountCreativeOverrunInfoService overrunInfoService;
    @Autowired
    private IAiKuaishouCampaignLevelOperationRecordService aiKuaishouCampaignLevelOperationRecordService;
    @Autowired
    private IAiKuaiShouAppInfoService appInfoService;
    @Autowired
    private IAiKuaishouUnitLevelOperationRecordService unitLevelOperationRecordService;
    @Autowired
    private IAiKuaishouCreativeLevelOperationRecordService creativeLevelOperationRecordService;
    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;
    @Autowired
    private IKuaiShouAppMultipleBidsService kuaiShouAppMultipleBidsService;


    /**
     * 创建自定义创意
     *
     * @param strategy   账户配置信息
     * @param createType 创意创建类型 1:素材上新 2：历史高质量 3:历史遗漏素材 4:历史打捞
     * @param videoCnt   视频数量
     */
    @Override
    public Long autoCreateCreative(AiKuaishouAdvertiserStrategy strategy, Integer createType, Long videoCnt) {
        String strategyUuid = UUID.randomUUID().toString();
        strategy.setUnitType(4);
        Long accountId = strategy.getAccountId();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId.toString());
        if (null == token) {
            log.info("token获取失败=>accountId:{}", accountId);
            return videoCnt;
        }
        //1:获取视频信息
        kuaishouInterfaceService.getVideoList(token, DateUtils.date2Str(), DateUtils.date2Str());
        Long timeStart = KuaishouCreativeMatTypeEnum.getStartTimeByType(strategy.getUnitType().toString() + createType.toString());
        Long timeEnd = KuaishouCreativeMatTypeEnum.getEndTimeByType(strategy.getUnitType().toString() + createType.toString());
        Long now = System.currentTimeMillis();
        String startTime = DateUtils.formatDateTime(now + timeStart * 60 * 1000L);
        String endTime = DateUtils.formatDateTime(now + timeEnd * 60 * 1000L);

        //2:判定账户是否单一应用
        Integer singleAppid = strategy.getSingleAppid();
        if (null != singleAppid && singleAppid == 0) {
            //多应用
            JSONArray appIdArray = JSONArray.parseArray(strategy.getAppIdArray());
            if (strategy.getMultipleBids() == 0) { // 非多应用多出价
                if (null != appIdArray && !appIdArray.isEmpty()) {
                    for (int i = 0; i < appIdArray.size(); i++) {
                        String replaceString = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());

                        AiKuaiShouAppInfo appInfo = appInfoService.getByParams(strategy.getAccountId(), appIdArray.getLong(i));
                        if (null == appInfo) {
                            log.info("账户：{}，appid({}) 数据不存在", accountId, appIdArray.getLong(i));
                            continue;
                        }
                        if (null != strategy.getGeneralTrack() && strategy.getGeneralTrack() == 0) {
                            strategy.setClickTrackUrl(appInfo.getTrackUrl());
                            strategy.setImpressionUrl(appInfo.getTrackUrl());
                        }
                        replaceString = appInfo.getAppVersion() + "-" + replaceString;
                        //1:查询素材
                        List<KuaiShouVideoGet> allVideos = getVideosByParams(strategy, startTime, endTime, appInfo, createType, videoCnt);
                        if (null == allVideos || allVideos.isEmpty()) {
                            log.info("账户：{}，{} 到 {} 未获取到相应素材({})", accountId, startTime, endTime, replaceString);
                            continue;
                        }
                        Long newCampaignId = getCampaignId(strategy, token, replaceString, "ALL_CAMPAIGN", createType, appInfo.getAppId(), strategyUuid);
                        for (KuaiShouVideoGet videoItem : allVideos) {
                            Boolean unitOverrun = getUnitOverrun(accountId);
                            if (unitOverrun) {
                                log.error("组创建超限,accountId:{}", accountId);
                                return 0L;
                            }

                            KuaishouAccountCreativeOverrunInfo overrunInfo = overrunInfoService.getByParams(accountId, DateUtils.formatDate(new Date()));
                            if (null != overrunInfo) {
                                log.info("该账户创意创建已超限=>accountId:{}", accountId);
                                return 0L;
                            }
                            // 获取视频封面数据
                            List<MaterialCutFrame> cutFrameList = materialCutFrameService.getListByVideoSignature(videoItem.getSignature());
                            if ((null == cutFrameList || cutFrameList.isEmpty())) {
                                log.info("未获取到视频封面=>videoSignature:{}", videoItem.getSignature());
                                continue;
                            }
                            //开始创建组+创意
                            String unitName = getName(strategy.getGroupName(), strategy, createType, videoItem.getPhotoName(), "unit", newCampaignId, appInfo.getAppId());
                            JSONObject unitParams = createUnitParams(token, newCampaignId, strategy, unitName, appInfo.getAppId());
                            log.info("创建广告组入参：{}", unitParams);
                            Map<String, Object> unitCreateResult = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitParams, 1);
                            Integer unitCode = (Integer) unitCreateResult.get("code");
                            String unitMessage = (String) unitCreateResult.get("message");
                            AiKuaishouUnitLevelOperationRecord unitLevelOperationRecord = new AiKuaishouUnitLevelOperationRecord();
                            BeanUtils.copyProperties(strategy, unitLevelOperationRecord);
                            unitLevelOperationRecord.setGroupName(unitName);
                            unitLevelOperationRecord.setCreateTime(new Date());
                            unitLevelOperationRecord.setStatus(unitCode);
                            unitLevelOperationRecord.setCampaignId(newCampaignId);
                            unitLevelOperationRecord.setCpaBid(unitParams.getInteger("cpa_bid"));
                            unitLevelOperationRecord.setBid(unitParams.getInteger("bid"));
                            unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));
                            unitLevelOperationRecord.setMessage(unitMessage);
                            unitLevelOperationRecord.setCampaignId(newCampaignId);
                            unitLevelOperationRecord.setAiStrategyUuid(strategyUuid);
                            if (unitCode != 0) {
                                log.info("组创建失败=>accountId:{};message:{}", accountId, unitMessage);
                                unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                                continue;
                            }
                            Long unitId = (Long) unitCreateResult.get("unitId");
                            unitLevelOperationRecord.setUnitId(unitId);
                            unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                            videoCnt--;
                            JSONObject creativeParams = creativeParams(token, unitId, videoItem, strategy);
                            createCreativeByImage(cutFrameList, token, creativeParams, newCampaignId, unitId, videoItem, strategy.getImageCnt(), strategy, strategyUuid, appInfo.getAppVersion());
                            if (videoCnt <= 0) {
                                return videoCnt;
                            }
                        }
                    }
                }
            } else if (strategy.getMultipleBids() == 1) { //  多应用多出价
                String replaceString = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());
                List<KuaiShouVideoGet> allVideos = getVideosByParams(strategy, startTime, endTime, null, createType, videoCnt);
                if (Check.isNull(allVideos)) {
                    return videoCnt;
                }
                for (KuaiShouVideoGet videoItem : allVideos) {
                    // 获取视频封面数据
                    List<MaterialCutFrame> cutFrameList = materialCutFrameService.getListByVideoSignature(videoItem.getSignature());
                    if ((null == cutFrameList || cutFrameList.isEmpty())) {
                        log.info("未获取到视频封面=>videoSignature:{}", videoItem.getSignature());
                        continue;
                    }
                    for (int i = 0; i < appIdArray.size(); i++) {

                        Boolean unitOverrun = getUnitOverrun(accountId);
                        if (unitOverrun) {
                            log.error("组创建超限,accountId:{}", accountId);
                            return 0L;
                        }

                        Long appId = appIdArray.getLong(i);
                        if (Check.isNull(appId)) {
                            continue;
                        }
                        KuaiShouAppMultipleBids multipleBids = kuaiShouAppMultipleBidsService.getInfoByAccountAndAppId(accountId, appId);
                        if (Check.isNull(multipleBids)) {
                            continue;
                        }
                        if (!Check.isNull(multipleBids.getTrackUrl())) {
                            strategy.setClickTrackUrl(multipleBids.getTrackUrl());
                        }
                        KuaishouAccountCreativeOverrunInfo overrunInfo = overrunInfoService.getByParams(accountId, DateUtils.formatDate(new Date()));
                        if (null != overrunInfo) {
                            log.info("该账户创意创建已超限=>accountId:{}", accountId);
                            return 0L;
                        }
                        Long newCampaignId = getCampaignId(strategy, token, replaceString, "TODAY", createType, appId, strategyUuid);
                        //开始创建组+创意
                        String unitName = getName(strategy.getGroupName(), strategy, createType, videoItem.getPhotoName(), "unit", newCampaignId, appId);
                        JSONObject unitParams = createUnitParams(token, newCampaignId, strategy, unitName, appId);
                        unitParams.remove("cpa_bid");
                        unitParams.put("cpa_bid", multipleBids.getCpaBid());
                        if (!Check.isNull(multipleBids.getDeepConversionBid())) {
                            unitParams.remove("deep_conversion_bid");
                            unitParams.put("deep_conversion_bid", multipleBids.getDeepConversionBid());
                        }
                        strategy.setCpaBid(multipleBids.getCpaBid() + "");
                        log.info("创建广告组入参：{}", unitParams);
                        Map<String, Object> unitCreateResult = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitParams, 1);
                        Integer unitCode = (Integer) unitCreateResult.get("code");
                        String unitMessage = (String) unitCreateResult.get("message");
                        AiKuaishouUnitLevelOperationRecord unitLevelOperationRecord = new AiKuaishouUnitLevelOperationRecord();
                        BeanUtils.copyProperties(strategy, unitLevelOperationRecord);
                        unitLevelOperationRecord.setCampaignId(newCampaignId);
                        unitLevelOperationRecord.setCpaBid(unitParams.getInteger("cpa_bid"));
                        unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));
                        unitLevelOperationRecord.setBid(unitParams.getInteger("bid"));
                        unitLevelOperationRecord.setGroupName(unitName);
                        unitLevelOperationRecord.setCreateTime(new Date());
                        unitLevelOperationRecord.setStatus(unitCode);
                        unitLevelOperationRecord.setMessage(unitMessage);
                        unitLevelOperationRecord.setCampaignId(newCampaignId);
                        unitLevelOperationRecord.setAiStrategyUuid(strategyUuid);
                        if (unitCode != 0) {
                            log.info("组创建失败=>accountId:{};message:{}", accountId, unitMessage);
                            unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                            continue;
                        }
                        Long unitId = (Long) unitCreateResult.get("unitId");
                        unitLevelOperationRecord.setUnitId(unitId);
                        unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                        videoCnt--;
                        JSONObject creativeParams = creativeParams(token, unitId, videoItem, strategy);
                        createCreativeByImage(cutFrameList, token, creativeParams, newCampaignId, unitId, videoItem, strategy.getImageCnt(), strategy, strategyUuid, null);
                        if (videoCnt <= 0) {
                            return videoCnt;
                        }
                    }
                }
            }
        } else {
            //单一应用
            String replaceString = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());
            List<KuaiShouVideoGet> newVideos = getVideosByParams(strategy, startTime, endTime, null, createType, videoCnt);
            if (null == newVideos || newVideos.isEmpty()) {
                log.info("账户：{}，{} 到 {} 未获取到相应素材({})", accountId, startTime, endTime, replaceString);
                return videoCnt;
            }
            Long appId = null;
            if (strategy.getCampaignType() == 2 || strategy.getCampaignType() == 7) {
                appId = JSONArray.parseArray(strategy.getAppIdArray()).getLong(0);
                if (Check.isNull(appId)) {
                    return videoCnt;
                }
            }
            Long newCampaignId = getCampaignId(strategy, token, replaceString, "TODAY", createType, appId, strategyUuid);
            if (null == newCampaignId) {
                return videoCnt;
            }
            //3、在“上新”计划中新增广告组，一个素材搭配n张封面，组成一个广告组
            for (KuaiShouVideoGet videoItem : newVideos) {

                Boolean unitOverrun = getUnitOverrun(accountId);
                if (unitOverrun) {
                    log.error("组创建超限,accountId:{}", accountId);
                    return 0L;
                }

                KuaishouAccountCreativeOverrunInfo overrunInfo = overrunInfoService.getByParams(accountId, DateUtils.formatDate(new Date()));
                if (null != overrunInfo) {
                    return 0L;
                }
                // 每个组，搭配5个创意
                List<MaterialCutFrame> cutFrameList = materialCutFrameService.getListByVideoSignature(videoItem.getSignature());
                if ((null == cutFrameList || cutFrameList.isEmpty())) {
                    log.info("未获取到视频封面=>videoSignature:{}", videoItem.getSignature());
                    continue;
                }
                String unitName = getName(strategy.getGroupName(), strategy, createType, videoItem.getPhotoName(), "unit", newCampaignId, appId);
                JSONObject unitParams = createUnitParams(token, newCampaignId, strategy, unitName, appId);
                log.info("创建广告组入参：{}", unitParams);
                Map<String, Object> unitCreateResult = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitParams, 1);
                Integer unitCode = (Integer) unitCreateResult.get("code");
                String unitMessage = (String) unitCreateResult.get("message");
                AiKuaishouUnitLevelOperationRecord unitLevelOperationRecord = new AiKuaishouUnitLevelOperationRecord();
                BeanUtils.copyProperties(strategy, unitLevelOperationRecord);
                unitLevelOperationRecord.setGroupName(unitName);
                unitLevelOperationRecord.setCampaignId(newCampaignId);
                unitLevelOperationRecord.setCpaBid(unitParams.getInteger("cpa_bid"));
                unitLevelOperationRecord.setBid(unitParams.getInteger("bid"));
                unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));
                unitLevelOperationRecord.setCreateTime(new Date());
                unitLevelOperationRecord.setStatus(unitCode);
                unitLevelOperationRecord.setMessage(unitMessage);
                unitLevelOperationRecord.setCampaignId(newCampaignId);
                unitLevelOperationRecord.setAiStrategyUuid(strategyUuid);
                if (unitCode != 0) {
                    log.info("组创建失败=>accountId:{};message:{}", accountId, unitMessage);
                    unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                    continue;
                }
                Long unitId = (Long) unitCreateResult.get("unitId");
                unitLevelOperationRecord.setUnitId(unitId);
                unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                videoCnt--;
                JSONObject creativeParams = creativeParams(token, unitId, videoItem, strategy);
                createCreativeByImage(cutFrameList, token, creativeParams, newCampaignId, unitId, videoItem, strategy.getImageCnt(), strategy, strategyUuid, null);
                if (videoCnt <= 0) {
                    return 0L;
                }
            }
        }
        return videoCnt;
    }


    /**
     * 创建程序化创意
     *
     * @param strategy
     */
    @Override
    public void autoCreateProgramCreative(AiKuaishouAdvertiserStrategy strategy, Integer createType, Long videoCnt) {
        String strategyUuid = UUID.randomUUID().toString();
        strategy.setUnitType(7);
        Long accountId = strategy.getAccountId();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId.toString());
        if (null == token) {
            log.info("token获取失败=>accountId:{}", accountId);
            return;
        }
        //1:获取视频信息
        kuaishouInterfaceService.getVideoList(token, DateUtils.date2Str(), DateUtils.date2Str());
        //2:判定账户是否单一应用
        Long timeStart = null;
        Long timeEnd = null;
        Integer singleAppid = strategy.getSingleAppid();
        if (null != singleAppid && singleAppid == 0) {
            timeStart = -7 * 60 * 24L;
            timeEnd = -5L;
        } else {
            if (strategy.getMultipleBids() == 0) {
                timeStart = KuaishouCreativeMatTypeEnum.getStartTimeByType(strategy.getUnitType().toString() + createType.toString());
                timeEnd = KuaishouCreativeMatTypeEnum.getEndTimeByType(strategy.getUnitType().toString() + createType.toString());
            } else if (strategy.getMultipleBids() == 1) {
                if (createType == 1) {
                    timeStart = -1 * 60 * 24L;
                    timeEnd = -5L;
                } else {
                    timeStart = KuaishouCreativeMatTypeEnum.getStartTimeByType(strategy.getUnitType().toString() + createType.toString());
                    timeEnd = KuaishouCreativeMatTypeEnum.getEndTimeByType(strategy.getUnitType().toString() + createType.toString());
                }
            }
        }
        Long now = System.currentTimeMillis();
        String startTime = DateUtils.formatDateTime(now + timeStart * 60 * 1000L);
        String endTime = DateUtils.formatDateTime(now + timeEnd * 60 * 1000L);
        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
        String key = token.getAccountId() + "_ProgramCreative" + "_" + nowDate;
        JSONArray appIdArray = JSON.parseArray(strategy.getAppIdArray());
        if (null != singleAppid && singleAppid == 0) {
            if (strategy.getMultipleBids() == 0) { //  非多应用多出价
                //多应用
                if (null != appIdArray && !appIdArray.isEmpty()) {
                    for (int i = 0; i < appIdArray.size(); i++) {
                        AiKuaiShouAppInfo appInfo = appInfoService.getByParams(strategy.getAccountId(), appIdArray.getLong(i));
                        if (null == appInfo) {
                            log.info("账户：{}，appid({}) 数据不存在", accountId, appIdArray.getLong(i));
                            continue;
                        }
                        String replaceString = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());

                        //判定是否通用监测链接
                        if (null != strategy.getGeneralTrack() && strategy.getGeneralTrack() == 0) {
                            strategy.setClickTrackUrl(appInfo.getTrackUrl());
                            strategy.setImpressionUrl(appInfo.getTrackUrl());
                        }
                        replaceString = appInfo.getAppVersion() + "-" + replaceString;
                        //1:查询可用素材
                        List<KuaiShouVideoGet> allVideos = getVideosByParams(strategy, startTime, endTime, appInfo, createType, videoCnt);
                        if (null == allVideos || allVideos.isEmpty()) {
                            continue;
                        }
                        Boolean unitOverrun = getUnitOverrun(accountId);
                        if (unitOverrun) {
                            log.error("组创建超限,accountId:{}", accountId);
                            return;
                        }

                        //判定创意创建是否超限
                        KuaishouAccountCreativeOverrunInfo overrunInfo = overrunInfoService.getByParams(accountId, DateUtils.formatDate(new Date()));
                        if (null != overrunInfo) {
                            log.info("该账户创意创建已超限=>accountId:{}", accountId);
                            return;
                        }
                        Long newCampaignId = getCampaignId(strategy, token, replaceString, "ALL_CAMPAIGN", createType, appInfo.getAppId(), strategyUuid);
                        //创建组+创意
                        List<List<KuaiShouVideoGet>> splitVideos = Lists.partition(allVideos, 5);
                        for (int j = 1; j < splitVideos.size() + 1; j++) {
                            Object redisObj = redisUtil.get(key);
                            if (!Check.isNull(redisObj)) {
                                Integer value = (Integer) redisObj;
                                if (value == 1) {
                                    log.error("程序化创意创建超限,accountId:{}", strategy.getAccountId());
                                    return;
                                }
                            }
                            //创建组
                            String unitName = getName(strategy.getGroupName(), strategy, createType, null, "unit", newCampaignId, appInfo.getAppId());
                            JSONObject unitParams = createUnitParams(token, newCampaignId, strategy, unitName, appInfo.getAppId());
                            log.info("创建广告组入参：{}", unitParams);
                            Map<String, Object> unitCreateResult = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitParams, 1);
                            Integer unitCode = (Integer) unitCreateResult.get("code");
                            String unitMessage = (String) unitCreateResult.get("message");
                            AiKuaishouUnitLevelOperationRecord unitLevelOperationRecord = new AiKuaishouUnitLevelOperationRecord();
                            BeanUtils.copyProperties(strategy, unitLevelOperationRecord);
                            unitLevelOperationRecord.setGroupName(unitName);
                            unitLevelOperationRecord.setCampaignId(newCampaignId);
                            unitLevelOperationRecord.setCpaBid(unitParams.getInteger("cpa_bid"));
                            unitLevelOperationRecord.setBid(unitParams.getInteger("bid"));
                            unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));
                            unitLevelOperationRecord.setCreateTime(new Date());
                            unitLevelOperationRecord.setStatus(unitCode);
                            unitLevelOperationRecord.setMessage(unitMessage);
                            unitLevelOperationRecord.setCampaignId(newCampaignId);
                            unitLevelOperationRecord.setAiStrategyUuid(strategyUuid);
                            if (unitCode != 0) {
                                log.info("组创建失败=>accountId:{};message:{}", accountId, unitMessage);
                                unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                                continue;
                            }
                            Long unitId = (Long) unitCreateResult.get("unitId");
                            unitLevelOperationRecord.setUnitId(unitId);
                            unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                            JSONObject creativeParams = programCreativeParams(token, unitId, splitVideos.get(j - 1), strategy, j, appInfo.getAppVersion());
                            createProgramCreative(token, creativeParams, strategy);
                        }
                    }
                }
            } else if (strategy.getMultipleBids() == 1) { // 多应用多出价
                List<KuaiShouVideoGet> allVideos = getVideosByParams(strategy, startTime, endTime, null, createType, videoCnt);
                if (Check.isNull(allVideos)) {
                    return;
                }
                String replaceString = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());
                List<List<KuaiShouVideoGet>> splitVideos = Lists.partition(allVideos, 1);
                for (int j = 1; j < splitVideos.size() + 1; j++) {
                    List<KuaiShouVideoGet> kuaiShouVideoGets = splitVideos.get(j);
                    if (Check.isNull(kuaiShouVideoGets)) {
                        continue;
                    }
                    for (KuaiShouVideoGet videoGet : kuaiShouVideoGets) {
                        for (int i = 0; i < appIdArray.size(); i++) {
                            Boolean unitOverrun = getUnitOverrun(accountId);
                            if (unitOverrun) {
                                log.error("组创建超限,accountId:{}", accountId);
                                return;
                            }

                            Object redisObj = redisUtil.get(key);
                            if (!Check.isNull(redisObj)) {
                                Integer value = (Integer) redisObj;
                                if (value == 1) {
                                    log.error("程序化创意创建超限,accountId:{}", strategy.getAccountId());
                                    return;
                                }
                            }
                            Long appId = appIdArray.getLong(i);
                            if (Check.isNull(appId)) {
                                continue;
                            }
                            KuaiShouAppMultipleBids multipleBids = kuaiShouAppMultipleBidsService.getInfoByAccountAndAppId(accountId, appId);
                            if (Check.isNull(multipleBids)) {
                                continue;
                            }
                            if (!Check.isNull(multipleBids.getTrackUrl())) {
                                strategy.setClickTrackUrl(multipleBids.getTrackUrl());
                            }
                            Long newCampaignId = getCampaignId(strategy, token, replaceString, "TODAY", createType, appId, strategyUuid);
                            //创建组
                            String unitName = getName(strategy.getGroupName(), strategy, createType, videoGet.getPhotoName(), "unit", newCampaignId, appId);
                            JSONObject unitParams = createUnitParams(token, newCampaignId, strategy, unitName, appId);
                            unitParams.remove("cpa_bid");
                            unitParams.put("cpa_bid", multipleBids.getCpaBid());
                            if (!Check.isNull(multipleBids.getDeepConversionBid())) {
                                unitParams.remove("deep_conversion_bid");
                                unitParams.put("deep_conversion_bid", multipleBids.getDeepConversionBid());
                            }
                            log.info("创建广告组入参：{}", unitParams);
                            Map<String, Object> unitCreateResult = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitParams, 1);
                            Integer unitCode = (Integer) unitCreateResult.get("code");
                            String unitMessage = (String) unitCreateResult.get("message");
                            AiKuaishouUnitLevelOperationRecord unitLevelOperationRecord = new AiKuaishouUnitLevelOperationRecord();
                            BeanUtils.copyProperties(strategy, unitLevelOperationRecord);
                            unitLevelOperationRecord.setGroupName(unitName);
                            unitLevelOperationRecord.setCampaignId(newCampaignId);
                            unitLevelOperationRecord.setCpaBid(unitParams.getInteger("cpa_bid"));
                            unitLevelOperationRecord.setBid(unitParams.getInteger("bid"));
                            unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));
                            unitLevelOperationRecord.setCreateTime(new Date());
                            unitLevelOperationRecord.setStatus(unitCode);
                            unitLevelOperationRecord.setMessage(unitMessage);
                            unitLevelOperationRecord.setCampaignId(newCampaignId);
                            unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));

                            unitLevelOperationRecord.setAiStrategyUuid(strategyUuid);
                            if (unitCode != 0) {
                                log.info("组创建失败=>accountId:{};message:{}", accountId, unitMessage);
                                unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                                continue;
                            }
                            Long unitId = (Long) unitCreateResult.get("unitId");
                            unitLevelOperationRecord.setUnitId(unitId);
                            unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                            JSONObject creativeParams = programCreativeParams(token, unitId, splitVideos.get(j - 1), strategy, j, null);
                            createProgramCreative(token, creativeParams, strategy);
                        }
                    }
                }
            }
        } else {
            String replaceString = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());
            //单一应用
            List<KuaiShouVideoGet> allVideos = getVideosByParams(strategy, startTime, endTime, null, createType, videoCnt);
            if (null == allVideos) {
                return;
            }
            Long appId = null;
            String appIdString = strategy.getAppIdArray();
            if (strategy.getCampaignType() == 2 || strategy.getCampaignType() == 7) {
                if (!Check.isNull(appIdString) && !Check.isNull(JSON.parseArray(appIdString))) {
                    appId = JSON.parseArray(appIdString).getLong(0);
                    if (Check.isNull(appId)) {
                        return;
                    }
                }
            }
            Long newCampaignId = getCampaignId(strategy, token, replaceString, "TODAY", createType, appId, strategyUuid);
            if (null == newCampaignId) {
                return;
            }
            //创意
            List<List<KuaiShouVideoGet>> splitVideos = Lists.partition(allVideos, 5);
            for (int j = 1; j < splitVideos.size() + 1; j++) {
                Boolean unitOverrun = getUnitOverrun(accountId);
                if (unitOverrun) {
                    log.error("组创建超限,accountId:{}", accountId);
                    return;
                }

                Object redisObj = redisUtil.get(key);
                if (!Check.isNull(redisObj)) {
                    Integer value = (Integer) redisObj;
                    if (value == 1) {
                        log.error("程序化创意创建超限,accountId:{}", strategy.getAccountId());
                        return;
                    }
                }
                //创建组
                String unitName = getName(strategy.getGroupName(), strategy, createType, null, "unit", newCampaignId, appId);
                JSONObject unitParams = createUnitParams(token, newCampaignId, strategy, unitName, appId);
                log.info("创建广告组入参：{}", unitParams);
                Map<String, Object> unitCreateResult = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitParams, 1);
                Integer unitCode = (Integer) unitCreateResult.get("code");
                String unitMessage = (String) unitCreateResult.get("message");
                AiKuaishouUnitLevelOperationRecord unitLevelOperationRecord = new AiKuaishouUnitLevelOperationRecord();
                BeanUtils.copyProperties(strategy, unitLevelOperationRecord);
                unitLevelOperationRecord.setGroupName(unitName);
                unitLevelOperationRecord.setCampaignId(newCampaignId);
                unitLevelOperationRecord.setCpaBid(unitParams.getInteger("cpa_bid"));
                unitLevelOperationRecord.setBid(unitParams.getInteger("bid"));
                unitLevelOperationRecord.setDeepConversionBid(unitParams.getInteger("deep_conversion_bid"));
                unitLevelOperationRecord.setCreateTime(new Date());
                unitLevelOperationRecord.setStatus(unitCode);
                unitLevelOperationRecord.setMessage(unitMessage);
                unitLevelOperationRecord.setCampaignId(newCampaignId);
                unitLevelOperationRecord.setAiStrategyUuid(strategyUuid);
                if (unitCode != 0) {
                    log.info("组创建失败=>accountId:{};message:{}", accountId, unitMessage);
                    unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                    return;
                }
                Long unitId = (Long) unitCreateResult.get("unitId");
                unitLevelOperationRecord.setUnitId(unitId);
                unitLevelOperationRecordService.saveOrUpdate(unitLevelOperationRecord);
                JSONObject creativeParams = programCreativeParams(token, unitId, splitVideos.get(j - 1), strategy, j, null);
                createProgramCreative(token, creativeParams, strategy);
            }
        }

    }

    @Override
    public void customCreativeSupplement(AiKuaishouAdvertiserStrategy strategy, Integer hour) throws ParseException {
        Long customUnitCnt = strategy.getCustomUnitCnt();
        if (Check.isNull(customUnitCnt)) {
            Integer imageCnt = strategy.getImageCnt();
            if (imageCnt <= 1) {
                customUnitCnt = 600L;
            } else {
                customUnitCnt = 2000L / imageCnt;
            }
        }

        Long unitNum = customUnitCnt * hour / 20;
        log.info("{}当前时间内需要创建组总数：{}", strategy.getAccountId(), unitNum);
        //查询当前账户创建自定义类型组数量
        int unitCreateCnt = groupService.queryToDayBuiltCount(strategy.getAccountId());
        log.info("{}截止目前创建组总数：{}", strategy.getAccountId(), unitCreateCnt);
        long remindCnt = unitNum - unitCreateCnt;
        if (remindCnt >= 1) {
            log.info("{}组创建不足，剩余需要创建个数{},使用历史遗漏素材创建", strategy.getAccountId(), remindCnt);
            //优先创建历史遗漏素材
            remindCnt = this.autoCreateCreative(strategy, 3, remindCnt);
        }
        if (remindCnt >= 1) {
            log.info("{}组创建不足，剩余需要创建个数{},使用高质量素材创建", strategy.getAccountId(), remindCnt);
            //高质量素材
            remindCnt = this.autoCreateCreative(strategy, 2, remindCnt);
        }
        if (remindCnt >= 1) {
            //历史打捞素材
            log.info("{}组创建不足，剩余需要创建个数{},使用历史打捞素材创建", strategy.getAccountId(), remindCnt);
            this.autoCreateCreative(strategy, 4, remindCnt);
        }
    }

    @Override
    public void customCreativeLimit(AiKuaishouAdvertiserStrategy strategy) {
        Long unitNum = strategy.getCustomUnitCnt();
        if (Check.isNull(unitNum)) {
            Integer imageCnt = strategy.getImageCnt();
            if (imageCnt <= 1) {
                unitNum = 600L;
            } else {
                unitNum = 2000L / imageCnt;
            }
        }
        log.info("{}当天可创建组总数：{}", strategy.getAccountId(), unitNum);
        //查询当前账户创建自定义类型组数量
        int unitCreateCnt = groupService.queryToDayBuiltCount(strategy.getAccountId());
        log.info("{}截止目前创建组总数：{}", strategy.getAccountId(), unitCreateCnt);
        long remindCnt = unitNum - unitCreateCnt;
        if (remindCnt >= 1) {
            log.info("{}组创建不足，剩余需要创建个数{},开始上新素材创建", strategy.getAccountId(), remindCnt);
            this.autoCreateCreative(strategy, 1, remindCnt);
        }
    }

    @Autowired
    private IKuaiShouUpdateService updateService;

    private void createProgramCreative(CtopOauthToken token, JSONObject creativeParams, AiKuaishouAdvertiserStrategy strategy) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PROGRAM_CREATE;
        String result = HttpUtils.kuaiShouhttpPostRequest(url, creativeParams.toJSONString(), headers);
        JSONObject resultJson = JSON.parseObject(result);
        log.info("创建程序化创意返回结果：{}", resultJson);
        if (Check.isNull(resultJson)) {
            log.error("程序化创意创意异常：api接口返回为空");
            return;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        Long unitId = creativeParams.getLong("unit_id");
        if (code == 0) {
            createLandPageAndUnit(creativeParams, resultJson.getJSONObject("data"));
            log.info("创建程序化创意成功，accountId：{}，unit：{}", token.getAccountId(), unitId);
        } else {
            log.error("快手创建程序化创意失败，accountId:{},unitId:{}，返回信息:{}", token.getAccountId(), unitId, message);
            if (code == 400001 && "/rest/openapi/v2/creative/advanced/program/create调用已超日限，次日可恢复调用".equals(message)) {
                String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                String key = token.getAccountId() + "_ProgramCreative" + "_" + nowDate;
                redisUtil.set(key, 1, 100000L);
                updateService.updateUnitStatus(token.getAccessToken(), token.getAccountId(), unitId, 3, "e9ca23d68d884d4ebb19d07889727dae");
            }
        }
    }

    //绑定落地页与广告组、创意的关系
    private void createLandPageAndUnit(JSONObject programJson, JSONObject data) {
        if (!Check.isNull(data) && !Check.isNull(programJson.getLong("site_id"))) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    landpagePackageService.createLandPageAndUnit(programJson.getLong("site_id"), data.getLong("creative_id"), programJson.getLong("unit_id"), programJson.getLong("advertiser_id"));
                }
            };
            thread.start();
        }
    }

    private JSONObject programCreativeParams(CtopOauthToken token, Long unitId, List<KuaiShouVideoGet> list, AiKuaishouAdvertiserStrategy strategy, Integer creativeCnt, String appVersion) {
        JSONObject programJson = new JSONObject();
        programJson.put("advertiser_id", token.getAccountId());
        programJson.put("unit_id", unitId);
        if (strategy.getSingleAppid() != null && strategy.getSingleAppid() == 0) {  // 多应用情况下 创意名称已app-versionMI命名
            if (!Check.isNull(appVersion)) {
                programJson.put("package_name", appVersion);
            } else {
                programJson.put("package_name", "程序化创意" + creativeCnt);
            }

        } else {
            programJson.put("package_name", "程序化创意" + creativeCnt);
        }

        JSONArray horizontalPhotoIds = new JSONArray();
        JSONArray verticalPhotoIds = new JSONArray();
        JSONArray coverImageTokens = new JSONArray();
        for (KuaiShouVideoGet videoGet : list) {
            List<MaterialCutFrame> cutFrameList = materialCutFrameService.getListByVideoSignature(videoGet.getSignature());
            if (!Check.isNull(cutFrameList)) {
                MaterialCutFrame cutFrame = cutFrameList.get(0);
                String imageToken = getImageToken(cutFrame.getUrl(), cutFrame.getSignature(), token.getAccountId(), token.getAccessToken());
                if (!Check.isNull(imageToken)) {
                    coverImageTokens.add(imageToken);
                }
            }
            if (videoGet.getMaterialType() == 2) {
                horizontalPhotoIds.add(videoGet.getPhotoId());
            }
            if (videoGet.getMaterialType() == 1) {
                verticalPhotoIds.add(videoGet.getPhotoId());
            }
        }
        programJson.put("horizontal_photo_ids", horizontalPhotoIds);
        programJson.put("vertical_photo_ids", verticalPhotoIds);
        if (coverImageTokens.size() >= 5) {
            coverImageTokens.remove(0);
        }
        programJson.put("cover_image_tokens", coverImageTokens);

        if (!Check.isNull(strategy.getSiteId())) {
            programJson.put("site_id", strategy.getSiteId());
        }
        if (!Check.isNull(strategy.getStickerTitle())) {
            programJson.put("sticker_styles", strategy.getStickerTitle());
        }

        if (!Check.isNull(strategy.getActionBarText())) {
            programJson.put("action_bar", strategy.getActionBarText());
        }
        if (!Check.isNull(strategy.getClickTrackUrl())) {
            programJson.put("click_url", strategy.getClickTrackUrl());
        }
        if (!Check.isNull(strategy.getActionbarClickUrl())) {
            programJson.put("actionbar_click_url", strategy.getActionbarClickUrl());
        }

        JSONArray captions = getCaptions(strategy.getDescription());
        programJson.put("captions", captions);
        if (!Check.isNull(strategy.getCreativeCategory())) {
            programJson.put("creative_category", strategy.getCreativeCategory());
            programJson.put("creative_tag", JSON.parseArray(strategy.getCreativeTag()));
        }
        return programJson;
    }

    private JSONArray getCaptions(String description) {
        JSONArray jsonArray = JSONArray.parseArray(description);
        if (jsonArray.size() <= 3) {
            return jsonArray;
        }
        Collections.shuffle(jsonArray);
        JSONArray captions = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            captions.add(jsonArray.getString(i));
            if (captions.size() == 3) {
                break;
            }
        }
        return captions;
    }

    private List<KuaiShouVideoGet> getNewVideoListByParams(AiKuaishouAdvertiserStrategy strategy, String startTime, String endTime, AiKuaiShouAppInfo appInfo) {
        if (null == appInfo) {
            if (Check.isNull(strategy.getMaterialKeyword())) { // 素材名称为空 不需要标注特殊素材
                return videoGetService.getNewVideoBetweenTime(strategy.getAccountId(), startTime, endTime, strategy.getChannelType(), null, null);
            } else {//  tt语音特殊素材查询
                return videoGetService.getNewVideoBetweenTime(strategy.getAccountId(), startTime, endTime, strategy.getChannelType(), strategy.getMaterialKeyword(), null);
            }
        } else {
            //查询通用素材
            List<KuaiShouVideoGet> generalVideos = new ArrayList<>();
            List<KuaiShouVideoGet> customVideos = new ArrayList<>();

            if (Check.isNull(strategy.getMaterialKeyword())) {
                customVideos = videoGetService.getNewVideoBetweenTime(strategy.getAccountId(), startTime, endTime, strategy.getChannelType(), "all", null);
                //2:查询特定素材
                String appVersion = appInfo.getAppVersion();
                if (!Check.isNull(appVersion)) {
                    String[] split = appVersion.split("-");
                    if (split.length > 1) {
                        String version = split[1];
                        generalVideos = videoGetService.getNewVideoBetweenTime(strategy.getAccountId(), startTime, endTime, strategy.getChannelType(), version, null);
                    }
                }

            } else { //  tt语音特殊素材查询
                generalVideos = videoGetService.getNewVideoBetweenTime(strategy.getAccountId(), startTime, endTime, strategy.getChannelType(), strategy.getMaterialKeyword(), null);

            }
            if (Check.isNull(generalVideos) && Check.isNull(customVideos)) {
                log.info("账户：{}，appId({}){}到{}这段时间没有上新素材", strategy.getAccountId(), appInfo.getAppId(), startTime, endTime);
                return new ArrayList<>();
            }
            //合并
            if (null == generalVideos || generalVideos.isEmpty()) {
                return customVideos;
            } else if (null == customVideos || customVideos.isEmpty()) {
                return generalVideos;
            } else {
                generalVideos.addAll(customVideos);
                return generalVideos;
            }
        }
    }


    private List<KuaiShouVideoGet> getRelateZeroVideoList(AiKuaishouAdvertiserStrategy strategy, String startTime, String endTime, AiKuaiShouAppInfo appInfo, Integer relativeCnt, Long videoCnt) {
        Integer channelType = null;
        if (null != strategy.getChannelType() && strategy.getChannelType() != 2) {
            channelType = strategy.getChannelType();
        }
        String appVersion = null;
        if (Check.isNull(strategy.getMaterialKeyword())) {
            if (null != appInfo && null != appInfo.getAppVersion()) {
                String[] split = appInfo.getAppVersion().split("-");
                if (split.length > 1) {
                    appVersion = split[1];
                } else {
                    return null;
                }
            }
        } else { //  tt语音特殊素材查询
            appVersion = strategy.getMaterialKeyword();
        }

        return videoGetService.getZeroVideoByParams(strategy.getAccountId(), startTime, endTime, videoCnt, appVersion, channelType, relativeCnt);
    }

    private List<KuaiShouVideoGet> getHistoryTopVideoListByParams(AiKuaishouAdvertiserStrategy strategy, String startTime, String endTime, AiKuaiShouAppInfo appInfo, Long videoCnt) {
        Integer channelType = null;
        if (null != strategy.getChannelType() && strategy.getChannelType() != 2) {
            channelType = strategy.getChannelType();
        }
        String appVersion = null;
        if (Check.isNull(strategy.getMaterialKeyword())) {
            if (!Check.isNull(appInfo.getAppVersion())) {
                String[] split = appInfo.getAppVersion().split("-");
                if (split.length > 1) {
                    appVersion = split[1];
                } else {
                    return null;
                }
            }
        } else { //  tt语音 特殊素材查询
            appVersion = strategy.getMaterialKeyword();
        }

        return videoGetService.getHistoryTopVideoByParams(strategy.getAccountId(), startTime, endTime, videoCnt, appVersion, channelType);
    }

    /**
     * 创建自定义创意
     *
     * @param strategy   账户配置信息
     * @param createType 创意创建类型 1:素材上新 2：历史高质量 3:历史遗漏素材 4：历史素材打捞
     * @param startTime  开始时间
     * @param endTime    结束时间
     */
    @Autowired
    private IKuaiShouCampaignService campaignService;


    private List<KuaiShouVideoGet> getVideosByParams(AiKuaishouAdvertiserStrategy strategy, String startTime, String endTime, AiKuaiShouAppInfo appInfo, Integer createType, Long videoCnt) {
        if (createType == 1) {
            return getNewVideoListByParams(strategy, startTime, endTime, appInfo);
        } else if (createType == 2) {
            return getHistoryTopVideoListByParams(strategy, startTime, endTime, appInfo, videoCnt);
        } else if (createType == 3) {
            return getRelateZeroVideoList(strategy, startTime, endTime, appInfo, 0, videoCnt);
        } else {  //  type == 4 历史素材打捞
            return getRelateZeroVideoList(strategy, startTime, endTime, appInfo, 20, videoCnt);
        }
    }


    private Long getCampaignId(AiKuaishouAdvertiserStrategy strategy, CtopOauthToken token, String replaceString, String checkType, Integer createType, Long appId, String uuid) {
        Long campaignId = null;
        if ("ALL_CAMPAIGN".equals(checkType)) {
            campaignId = campaignService.getCampaignIdByAccountAndName(strategy.getAccountId(), replaceString);
        } else if ("TODAY".equals(checkType)) {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd") + " 00:00:01";
            campaignId = campaignService.getCampaignIdByAccountAndNameAndDate(strategy.getAccountId(), replaceString, nowDate);
        }
        if (!Check.isNull(campaignId)) {
            return campaignId;
        }

        // 不存在“上新”计划，则创建一个计划
        JSONObject campaignParams = new JSONObject();
        campaignParams.put("advertiser_id", token.getAccountId());
        String campaignName = getName(strategy.getCampaignName(), strategy, createType, null, "plan", null, appId);
        campaignParams.put("campaign_name", campaignName);
        campaignParams.put("type", strategy.getCampaignType());
        if (null != strategy.getCampaignDayBudget() && strategy.getCampaignDayBudget() != 0) {
            campaignParams.put("day_budget", strategy.getCampaignDayBudget());
        }
        Map<String, Object> campaignCreateResult = kuaishouInterfaceService.campaignCreate(token.getAccessToken(), token.getAccountId(), campaignParams);
        Integer code = (Integer) campaignCreateResult.get("code");
        String message = (String) campaignCreateResult.get("message");
        AiKuaishouCampaignLevelOperationRecord record = new AiKuaishouCampaignLevelOperationRecord(strategy, null, code, message);
        record.setAiStrategyUuid(uuid);
        record.setCampaignName(campaignName);
        if (code != 0) {
            log.info("计划创建失败=>message:{}", message);
            record.setCampaignId(0L);
            aiKuaishouCampaignLevelOperationRecordService.saveOrUpdate(record);
            return null;
        }

        campaignId = (Long) campaignCreateResult.get("campaignId");
        record.setCampaignId(campaignId);
        aiKuaishouCampaignLevelOperationRecordService.saveOrUpdate(record);
        Integer campaignStatus = strategy.getCampaignStatus();
        if (!Check.isNull(campaignStatus) && campaignStatus == 2) {
            updateService.updateCampaignStatus(token.getAccessToken(), token.getAccountId(), campaignId, campaignStatus, "yumeng");
        }

        return campaignId;
    }

    private JSONObject createUnitParams(CtopOauthToken token, Long campaignId, AiKuaishouAdvertiserStrategy strategy,
                                        String unitName, Long appId) {
        // 拼装创建组的入参 json
        JSONObject unitParams = new JSONObject();
        Integer unitType = strategy.getUnitType();
        //创意制作方式
        unitParams.put("unit_type", unitType);
        unitParams.put("advertiser_id", token.getAccountId());
        unitParams.put("campaign_id", campaignId);
        unitParams.put("unit_name", unitName);
        //出价类型
        unitParams.put("bid_type", strategy.getBidType());
        if (!Check.isNull(strategy.getGroupStatus()) && strategy.getGroupStatus() == 2) {
            unitParams.put("put_status", strategy.getGroupStatus());

        }

        //组单日预算
        if (null != strategy.getUnitDayBudget() && strategy.getUnitDayBudget() != 0) {
            unitParams.put("day_budget", strategy.getUnitDayBudget());
        } else {
            unitParams.put("day_budget", 0);
        }
        //应用商店列表
        unitParams.put("ocpx_action_type", strategy.getOcpxActionType());
        //出价
        if (null != strategy.getBid() && strategy.getBid() != 0) {
            unitParams.put("bid", strategy.getBid());
        }
        if (!Check.isNull(strategy.getCpaBid()) && !"0".equals((strategy.getCpaBid()))) {
            Long cpdBid = getBidByString(strategy.getCpaBid());
            unitParams.put("cpa_bid", cpdBid);
        }
        //优先低成本
        if (null != strategy.getSmartBid() && strategy.getSmartBid() != 0) {
            unitParams.put("smart_bid", strategy.getSmartBid());
        }
        //优化目标
        if (!Check.isNull(strategy.getOcpxActionType())) {
            unitParams.put("ocpx_action_type", strategy.getOcpxActionType());
        }
        //深度转化目标
        if (!Check.isNull(strategy.getDeepConversionType())) {
            unitParams.put("deep_conversion_type", strategy.getDeepConversionType());
        }
        //付费ROI系数
        if (!Check.isNull(strategy.getRoiRatio())) {
            unitParams.put("roi_ratio", strategy.getRoiRatio());
        }
        //深度转化目标出价
        if (!Check.isNull(strategy.getDeepConversionBid())) {
            unitParams.put("deep_conversion_bid", strategy.getDeepConversionBid());
        }
        Integer sceneId = null;
        String scenceIdString = strategy.getSceneId();

        if (!Check.isNull(scenceIdString) && !Check.isNull(JSON.parseArray(scenceIdString))) {
            JSONArray scenceArray = JSON.parseArray(scenceIdString);
            sceneId = scenceArray.getInteger(0);
            unitParams.put("scene_id", scenceArray);
        }
        Integer campaignType = strategy.getCampaignType();
        if (campaignType == 2) { // 提升应用安装
            //应用ID
            if (!Check.isNull(appId)) {
                unitParams.put("app_id", appId);
            }
            // 直达链接
            if (!Check.isNull(strategy.getSchemaUri())) {
                unitParams.put("schema_uri", strategy.getSchemaUri());
            }
            // 优先从系统应用商店下载
            if (null != strategy.getUseAppMarket()) {
                unitParams.put("use_app_market", strategy.getUseAppMarket());
            }
            if (null != strategy.getAppStore() && !"".equals(strategy.getAppStore())) {
                unitParams.put("app_store", JSON.parseArray(strategy.getAppStore()));
            }
        } else if (campaignType == 3) { //  获取电商下单
            //url类型
            if (!Check.isNull(strategy.getUrlType())) {
                unitParams.put("url_type", strategy.getUrlType());
            }
            if (!Check.isNull(strategy.getUrl())) {
                unitParams.put("url", strategy.getUrl());
            }
        } else if (campaignType == 5) { //收集销售线索
            //url类型
            if (!Check.isNull(strategy.getWebUriType())) {
                unitParams.put("web_uri_type", strategy.getWebUriType());
            }
            //url
            if (!Check.isNull(strategy.getUrl())) {
                unitParams.put("url", strategy.getUrl());
            }
        } else if (campaignType == 7) { //  提高应用活跃
            //  appId
            if (!Check.isNull(appId)) {
                unitParams.put("app_id", appId);
            }

            //  url
            if (!Check.isNull(strategy.getUrl())) {
                unitParams.put("url", strategy.getUrl());
            }
            //调起链接
            if (!Check.isNull(strategy.getSchemaUri())) {
                unitParams.put("schema_uri", strategy.getSchemaUri());
            }
        }
        //投放开始时间
        if (!Check.isNull(strategy.getBeginTime())) {
            unitParams.put("begin_time", strategy.getBeginTime());
        } else {
            unitParams.put("begin_time", DateUtils.formatDate());
        }
        //投放结束时间
        if (!Check.isNull(strategy.getEndTime())) {
            unitParams.put("end_time", strategy.getEndTime());
        }
        //投放时间段
        if (!Check.isNull(strategy.getScheduleTime())) {
            unitParams.put("schedule_time", strategy.getScheduleTime());
        }
        //转化id
        if (!Check.isNull(strategy.getConvertId())) {
            unitParams.put("convert_id", strategy.getConvertId());
        }
        //创意展现方式
        if (!Check.isNull(strategy.getShowMode())) {
            unitParams.put("show_mode", strategy.getShowMode());
        }
        //投放方式
        if (!Check.isNull(strategy.getSpeed())) {
            unitParams.put("speed", strategy.getSpeed());
        }
        //预约广告
        if (!Check.isNull(strategy.getSiteType())) {
            unitParams.put("site_type", strategy.getSiteType());
        }
        //智能定向
        if (!Check.isNull(strategy.getAutoTarget())) {
            unitParams.put("auto_target", strategy.getAutoTarget());
        }
        //是否开启自动生成视频
        if (!Check.isNull(strategy.getAutoCreatePhoto())) {
            unitParams.put("auto_create_photo", strategy.getAutoCreatePhoto());
        }
        if (unitType == 7) {
            //是否开启智能抽帧
            if (!Check.isNull(strategy.getSmartCover())) {
                unitParams.put("smart_cover", strategy.getSmartCover());
            }
            //程序化创意2.0素材挖掘
            if (!Check.isNull(strategy.getAssetMining())) {
                if (strategy.getAssetMining() == 1) {
                    unitParams.put("asset_mining", true);
                } else if (strategy.getAssetMining() == 0) {
                    unitParams.put("asset_mining", false);
                }

            }
        }
        if (!Check.isNull(strategy.getTemplateId())) {
            if (sceneId != 5) {
                unitParams.put("template_id", strategy.getTemplateId()); //定向模板id
            } else { // 联盟广告位 需要根据模板id 获取定向数据
                JSONObject unionJson = groupTemplateService.getUnionJson(Long.parseLong(strategy.getTemplateId() + ""));
                Integer code = unionJson.getInteger("code");
                if (code == 0) {
                    JSONObject target = unionJson.getJSONObject("target");
                    unitParams.put("target", target);
                } else {
                    log.info("组创建异常=》accountId({})联盟广告位定向模板错误", strategy.getAccountId());
                    return null;
                }
            }
        } else {
            JSONObject target = getTarget(sceneId, strategy);
            // 定向数据
            unitParams.put("target", target);
        }
        // 设置定向内容
        JSONObject targetJsonObject = new JSONObject();
        if (null != strategy.getRegion() && !"".equals(strategy.getRegion())) {
            targetJsonObject.put("region", JSON.parseArray(strategy.getRegion()));
        }
        if (null != strategy.getAgesRange() && !"".equals(strategy.getAgesRange())) {
            JSONArray agesRange = JSON.parseArray(strategy.getAgesRange());
            if (null != agesRange && !agesRange.isEmpty()) {
                targetJsonObject.put("ages_range", JSON.parseArray(strategy.getAgesRange()));
            }
        }
        if (null != strategy.getGender()) {
            targetJsonObject.put("gender", strategy.getGender());
        }
        if (null != strategy.getPlatformOs()) {
            targetJsonObject.put("platform_os", strategy.getPlatformOs());
        }
        if (null != strategy.getAndroidOsv()) {
            targetJsonObject.put("android_osv", strategy.getAndroidOsv());
        }
        if (null != strategy.getIosOsv()) {
            targetJsonObject.put("ios_osv", strategy.getIosOsv());
        }
        if (null != strategy.getDeviceBrand() && !"".equals(strategy.getDeviceBrand()) && !"[]".equals(strategy.getDeviceBrand())) {
            targetJsonObject.put("device_brand", JSON.parseArray(strategy.getDeviceBrand()));
        }
        if (null != strategy.getDevicePrice() && !"".equals(strategy.getDevicePrice()) && !"[]".equals(strategy.getDevicePrice())) {
            targetJsonObject.put("device_price", JSON.parseArray(strategy.getDevicePrice()));
        }
        if (sceneId != 5) {
            if (null != strategy.getFilterConvertedLevel() && strategy.getFilterConvertedLevel() != 0) {
                targetJsonObject.put("filter_converted_level", strategy.getFilterConvertedLevel());
            }
        }

        // APP行为-按APP名称
        if (sceneId != 5) {
            JSONArray appIds = JSONArray.parseArray(strategy.getAppIds());
            if (!Check.isNull(appIds)) {
                targetJsonObject.put("app_ids", appIds);
            }
            JSONArray appInterest = JSONArray.parseArray(strategy.getAppInterest());
            if (!Check.isNull(appInterest)) {
                targetJsonObject.put("app_interest", appInterest);
            }
        }
        // 人群包定向
        JSONArray populationString = JSONArray.parseArray(strategy.getPopulation());
        if (!Check.isNull(populationString)) {
            targetJsonObject.put("population", populationString);
        }
        // 人群包排除
        JSONArray excludePopulationString = JSONArray.parseArray(strategy.getExcludePopulation());
        if (!Check.isNull(excludePopulationString)) {
            targetJsonObject.put("exclude_population", excludePopulationString);
        }
        // 付费人群包id
        JSONArray paidAudienceString = JSONArray.parseArray(strategy.getPaidAudience());
        if (!Check.isNull(paidAudienceString)) {
            targetJsonObject.put("paid_audience", paidAudienceString);
        }

        //是否开启智能扩量
        if (sceneId != 5) {
            if (null != strategy.getIsOpen() && strategy.getIsOpen().equals(1)) {
                JSONObject intelliExtend = new JSONObject();
                intelliExtend.put("is_open", 1);
                if (null != strategy.getNoAgeBreak() && strategy.getNoAgeBreak().equals(1)) {
                    intelliExtend.put("no_age_break", 1);
                }
                if (null != strategy.getNoGenderBreak() && strategy.getNoGenderBreak().equals(1)) {
                    intelliExtend.put("no_gender_break", 1);
                }
                if (null != strategy.getNoAreaBreak() && strategy.getNoAreaBreak().equals(1)) {
                    intelliExtend.put("no_area_break", 1);
                }
                targetJsonObject.put("intelli_extend", intelliExtend);
            }
        }
        unitParams.put("target", targetJsonObject);
        return unitParams;
    }

    private Long getBidByString(String cpaBid) {
        if (Check.isNull(cpaBid)) {
            return null;
        }
        String bidString = null;
        if (cpaBid.contains("/")) { // 阶梯出价
            String[] split = cpaBid.split("/");
            int random = new Random().nextInt(split.length);
            bidString = split[random];

        } else if (cpaBid.contains("-")) { // 随机出价
            String[] split = cpaBid.split("-");
            Double min = Double.valueOf(split[0]) / 1000;
            Double max = Double.valueOf(split[1]) / 1000;
            Double randomNumber = new BigDecimal(min + Math.random() * (max - min)).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            bidString = String.valueOf(new Double(randomNumber * 1000).longValue());

        } else {
            bidString = cpaBid;
        }

        return Long.valueOf(bidString);
    }

    private JSONArray cleanPramgramErrorScence(JSONArray scenceArray) {
        JSONArray result = new JSONArray();
        if (null == scenceArray || scenceArray.isEmpty()) {
            return result;
        }
        for (int i = 0; i < scenceArray.size(); i++) {
            Integer senceId = scenceArray.getInteger(i);
            if (senceId != 5 && senceId != 3) {
                result.add(senceId);
            }
        }
        return result;
    }

    /**
     * 获取定向包
     *
     * @param sceneId
     * @param strategy
     * @return
     */
    private JSONObject getTarget(Integer sceneId, AiKuaishouAdvertiserStrategy strategy) {
        JSONObject target = new JSONObject();
        // 地域
        String regionString = strategy.getRegion();
        if (null != regionString && !"".equals(regionString.trim())) {
            target.put("region", JSON.parseArray(regionString));
        }
        String districtIdString = strategy.getDistrictIds();
        // 商圈定向
        if (null != districtIdString && !"".equals(districtIdString.trim())) {
            target.put("district_ids", JSON.parseArray(districtIdString));
        }
        // 用户类型
        if (null != strategy.getUserType()) {
            target.put("user_type", strategy.getUserType());
        }
        //自定义年龄段
        if (null != strategy.getAgeMin() || null != strategy.getAgeMax()) {
            JSONObject age = new JSONObject();
            age.put("min", strategy.getAgeMin());
            age.put("max", strategy.getAgeMax());
            target.put("age", age);
        }
        // 固定年龄段
        String ageRangeString = strategy.getAgesRange();
        if (null != ageRangeString && !"".equals(ageRangeString.trim())) {
            target.put("ages_range", JSON.parseArray(ageRangeString));
        }
        // 性别
        if (null != strategy.getGender()) {
            target.put("gender", strategy.getGender());
        }
        // 操作系统
        if (null != strategy.getPlatformOs()) {
            target.put("platform_os", strategy.getPlatformOs());
        }
        // Android版本
        if (null != strategy.getAndroidOsv()) {
            target.put("android_osv", strategy.getAndroidOsv());
        }
        // Android版本
        if (null != strategy.getIosOsv()) {
            target.put("ios_osv", strategy.getIosOsv());
        }
        // 网络环境
        if (null != strategy.getNetwork()) {
            target.put("network", strategy.getNetwork());
        }
        // 设备品牌
        String deviceBrandString = strategy.getDeviceBrand();
        if (null != deviceBrandString && !"".equals(deviceBrandString.trim())) {
            target.put("device_brand", JSON.parseArray(deviceBrandString));
        }
        // 设备价格
        String devicePriceString = strategy.getDevicePrice();
        if (null != devicePriceString && !"".equals(devicePriceString.trim())) {
            target.put("device_price", JSON.parseArray(devicePriceString));
        }
        if (sceneId != 5) {
            // 商业兴趣类型
            if (null != strategy.getBusinessInterestType()) {
                target.put("business_interest_type", strategy.getBusinessInterestType());
            }
            // 商业兴趣
            String businessInterestString = strategy.getBusinessInterest();
            if (null != businessInterestString && !"".equals(businessInterestString.trim())) {
                target.put("business_interest", JSON.parseArray(businessInterestString));
            }
            // 网红粉丝
            String fansStarString = strategy.getFansStar();
            if (null != fansStarString && !"".equals(fansStarString.trim())) {
                target.put("fans_star", JSON.parseArray(fansStarString));
            }
            // 兴趣视频用户
            String interestVideoString = strategy.getInterestVideo();
            if (null != interestVideoString && !"".equals(interestVideoString.trim())) {
                target.put("interest_video", JSON.parseArray(interestVideoString));
            }
            // 过滤已转化人群
            if (null != strategy.getFilterConvertedLevel()) {
                target.put("filter_converted_level", strategy.getFilterConvertedLevel());
            }

            // 开启智能扩量
            if (null != strategy.getIsOpen() && strategy.getIsOpen() == 1) {
                JSONObject intelliExtend = new JSONObject();
                intelliExtend.put("is_open", strategy.getIsOpen());
                //  不可突破年龄
                if (!Check.isNull(strategy.getNoAgeBreak())) {
                    intelliExtend.put("no_age_break", strategy.getNoAgeBreak());
                }
                //  不可突破性别
                if (!Check.isNull(strategy.getNoGenderBreak())) {
                    intelliExtend.put("no_gender_break", strategy.getNoGenderBreak());
                }
                //  不可突破地域
                if (!Check.isNull(strategy.getNoAreaBreak())) {
                    intelliExtend.put("no_area_break", strategy.getNoAreaBreak());
                }
                // 智能扩量
                target.put("intelli_extend", intelliExtend);
            }

        }
        // APP行为-按分类
        JSONArray appInterest = JSONArray.parseArray(strategy.getAppInterest());
        if (!Check.isNull(appInterest)) {
            target.put("app_interest", appInterest);
        }
        // APP行为-按APP名称
        JSONArray appIds = JSONArray.parseArray(strategy.getAppIds());
        if (!Check.isNull(appIds)) {
            target.put("app_ids", appIds);
        }

        // 人群包定向
        JSONArray populationString = JSONArray.parseArray(strategy.getPopulation());
        if (!Check.isNull(populationString)) {
            target.put("population", populationString);
        }
        // 人群包排除
        JSONArray excludePopulationString = JSONArray.parseArray(strategy.getExcludePopulation());
        if (!Check.isNull(excludePopulationString)) {
            target.put("exclude_population", excludePopulationString);
        }
        // 付费人群包id
        JSONArray paidAudienceString = JSONArray.parseArray(strategy.getPaidAudience());
        if (!Check.isNull(paidAudienceString)) {
            target.put("paid_audience", paidAudienceString);
        }
        if (Check.isNull(strategy.getBehaviorInterest())) {
            target.put("behavior_interest", JSON.parseObject(strategy.getBehaviorInterest()));
        }
        return target;
    }


    private void createCreativeByImage(List<MaterialCutFrame> cutFrameList, CtopOauthToken token, JSONObject creativeParams,
                                       Long campaignId, Long unitId, KuaiShouVideoGet videoItem,
                                       int imageNumber, AiKuaishouAdvertiserStrategy strategy, String uuid, String appVersion) {
        if ((null != cutFrameList && !cutFrameList.isEmpty())) {
            for (int i = 0; i < cutFrameList.size(); i++) {
                String imageCode = cutFrameList.get(i).getSignature();
                String imageUrl = cutFrameList.get(i).getUrl();
                String imageToken = getImageToken(imageUrl, imageCode, token.getAccountId(), token.getAccessToken());
                creativeParams.put("image_token", imageToken);
                createCreative(token, creativeParams, campaignId, unitId, i + 1, videoItem, strategy, uuid, appVersion);
                imageNumber--;
                if (imageNumber <= 0) {
                    break;
                }
            }
        }
    }

    private String getImageToken(String imageUrl, String imageCode, Long accountId, String token) {
        // 根据imageUrl 和 imageCode，获取 imageToken （创建创意用）
        KuaiShouImageGet imageGet = imageGetService.getOneByParams(null, imageCode);
        if ((null == imageGet) || ("".equals(imageGet.getImageToken()))) {
            /**
             * 如果取不到image_token
             * 则调用上传url的方法 kuauiShouImageUpload(url, signature, accountId, oauthToken.getAccessToken());
             */
            return materialUploadService.kuauiShouImageUpload(imageUrl, imageCode, accountId, token);
        }
        return imageGet.getImageToken();
    }

    private JSONObject creativeParams(CtopOauthToken token, Long unitId, KuaiShouVideoGet videoItem, AiKuaishouAdvertiserStrategy strategy) {
        JSONObject creativeParams = new JSONObject();
        creativeParams.put("advertiser_id", token.getAccountId());
        creativeParams.put("unit_id", unitId);
        creativeParams.put("photo_id", videoItem.getPhotoId());
        creativeParams.put("creative_material_type", videoItem.getMaterialType());
        creativeParams.put("action_bar_text", strategy.getActionBarText());
        JSONArray descArr = JSONArray.parseArray(strategy.getDescription());
        int index = new Random().nextInt(descArr.size());
        String description = descArr.getString(index);
        creativeParams.put("description", description);
        // 封面广告语标题
        if (!Check.isNull(strategy.getStickerTitle())) {
            creativeParams.put("sticker_title", strategy.getStickerTitle());
        }
        // 贴纸样式类型
        if (!Check.isNull(strategy.getOverlayType())) {
            creativeParams.put("overlay_type", strategy.getOverlayType());
        }
        // 广告标签
        if (!Check.isNull(strategy.getExposeTag())) {
            creativeParams.put("expose_tag", strategy.getExposeTag());
        }
        // 广告标签2期
        if (Check.isNull(strategy.getNewExposeTag())) {
            creativeParams.put("new_expose_tag", JSON.parseArray(strategy.getNewExposeTag()));
        }
        // 安卓下载中间页ID
        if (Check.isNull(strategy.getSiteId())) {
            creativeParams.put("site_id", strategy.getSiteId());
        }
        if (null != strategy.getClickTrackUrl() && !"".equals(strategy.getClickTrackUrl())) {
            creativeParams.put("click_track_url", strategy.getClickTrackUrl());
        }
        if (null != strategy.getImpressionUrl() && !"".equals(strategy.getImpressionUrl())) {
            creativeParams.put("impression_url", strategy.getImpressionUrl());
        }
        // 第三方有效播放监测链接
        if (!Check.isNull(strategy.getAdPhotoPlayedT3sUrl())) {
            creativeParams.put("ad_photo_played_t3s_url", strategy.getAdPhotoPlayedT3sUrl());
        }
        if (null != strategy.getActionbarClickUrl() && !"".equals(strategy.getActionbarClickUrl())) {
            creativeParams.put("actionbar_click_url", strategy.getActionbarClickUrl());
        }
        if (null != strategy.getCreativeCategory()) {
            creativeParams.put("creative_category", strategy.getCreativeCategory());
        }
        if (null != strategy.getCreativeTag() && !"".equals(strategy.getCreativeTag())) {
            creativeParams.put("creative_tag", JSON.parseArray(strategy.getCreativeTag()));
        }
        return creativeParams;
    }


    private void createCreative(CtopOauthToken token, JSONObject creativeParams, Long campaignId, Long unitId,
                                int creativeCnt, KuaiShouVideoGet videoGet, AiKuaishouAdvertiserStrategy strategy, String uuid, String appVersion) {
        String creativeName = null;
        if (!Check.isNull(appVersion)) {
            creativeName = appVersion + "_" + creativeCnt;
        } else {
            creativeName = "自定义创意_" + creativeCnt;
        }
        creativeParams.put("creative_name", creativeName);
        Map<String, Object> creativeCreateResult = kuaishouInterfaceService.creativeCreate(token.getAccessToken(), token.getAccountId(), creativeParams, 1);
        Integer creativeCode = (Integer) creativeCreateResult.get("code");
        String creativeMessage = (String) creativeCreateResult.get("message");

        if (creativeCode == -1 && "/rest/openapi/v2/creative/create调用已超日限，次日可恢复调用".equals(creativeMessage)) {
            updateService.updateUnitStatus(token.getAccessToken(), token.getAccountId(), unitId, 3, "e9ca23d68d884d4ebb19d07889727dae");
        } else if (creativeCode == -1 && creativeMessage.contains("超过可关联的有效创意的上限")) {
            updateService.updateUnitStatus(token.getAccessToken(), token.getAccountId(), unitId, 3, "e9ca23d68d884d4ebb19d07889727dae");
        } else if (creativeCode == -1 && creativeMessage.contains("视频不存在")) {
            updateService.updateUnitStatus(token.getAccessToken(), token.getAccountId(), unitId, 3, "e9ca23d68d884d4ebb19d07889727dae");
        }

        AiKuaishouCreativeLevelOperationRecord record = new AiKuaishouCreativeLevelOperationRecord();
        BeanUtils.copyProperties(strategy, record);
        record.setCreativeName(creativeName);
        record.setStatus(creativeCode);
        record.setDescription(creativeParams.getString("description"));
        record.setPhotoId(creativeParams.getString("photo_id"));
        record.setMessage(creativeMessage);
        record.setUnitId(unitId);
        record.setAiStrategyUuid(uuid);
        record.setCreateTime(new Date());
        if (creativeCode != 0) {
            creativeLevelOperationRecordService.saveOrUpdate(record);
            log.info("创意创建失败=>message:{}", creativeMessage);
            return;
        }
        Long creativeId = (Long) creativeCreateResult.get("creativeId");
        record.setCreativeId(creativeId);
        creativeLevelOperationRecordService.saveOrUpdate(record);
    }

    /**
     * @param wildcard 计划名称/组名称
     * @param strategy 账户id
     * @return
     */
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IKuaiShouAppListService appListService;


    private String getName(String wildcard, AiKuaishouAdvertiserStrategy strategy, Integer createType, String materialName, String type, Long campaignId, Long appId) {
        if (wildcard.contains("{{应用名称}}") || wildcard.contains("{{应用标记}}")) {
            KuaiShouAppList getAppInfo = appListService.getAppInfo(strategy.getAccountId(), appId);
            if (!Check.isNull(getAppInfo)) {
                if (!wildcard.contains("{{自定义}}")) {
                    if (wildcard.contains("{{应用标记}}")) {
                        wildcard = wildcard.replace("{{应用标记}}", "{{应用标记}}-{{自定义}}");
                    }
                }
                wildcard = wildcard.replace("{{应用名称}}", getAppInfo.getAppName());
                wildcard = wildcard.replace("{{应用标记}}", getAppInfo.getAppVersion());
            } else {
                wildcard = wildcard.replace("{{应用名称}}", "");
                wildcard = wildcard.replace("{{应用标记}}", "");
            }
        }
        if (wildcard.contains("{{创意制作方式}}")) {
            if (strategy.getUnitType() == 4) {
                wildcard = wildcard.replace("{{创意制作方式}}", "自定义");
            } else if (strategy.getUnitType() == 7) {
                wildcard = wildcard.replace("{{创意制作方式}}", "程序化");
            }
        }
        if (wildcard.contains("{{广告位置}}")) {
            String adsence = getAdSenceByParams(strategy.getSceneId());
            wildcard = wildcard.replace("{{广告位置}}", adsence);
        }

        if (wildcard.contains("{{素材名称}}")) {
            if (Check.isNull(materialName)) {
                wildcard = wildcard.replace("{{素材名称}}", "");
            } else {
                wildcard = wildcard.replace("{{素材名称}}", materialName);
            }
        }
        if (wildcard.contains("{{渠道号}}")) {
            KuaiShouAppMultipleBids multipleBids = kuaiShouAppMultipleBidsService.getInfoByAccountAndAppId(strategy.getAccountId(), appId);
            if (!Check.isNull(multipleBids)) {
                wildcard = wildcard.replace("{{渠道号}}", multipleBids.getChannelCode());
            } else {
                wildcard = wildcard.replace("{{渠道号}}", "");
            }
        }
        if (!wildcard.contains("{{自定义}}")) {
            wildcard = wildcard + "{{自定义}}";
        }
        Date date = new Date();
        String nowDate = DateUtils.formatDate(date, "yy-MMdd");
        if (type.equals("plan")) {
            if (wildcard.contains("{{日期}}")) {
                wildcard = wildcard.replace("{{日期}}", nowDate);
            } else {
                wildcard = wildcard + "-" + nowDate;
            }
        } else if ("unit".equals(type)) {
            wildcard = wildcard.replace("{{日期}}", nowDate);
        }
        String targetName = KuaishouCreativeMatTypeEnum.getNameByType(strategy.getUnitType().toString() + createType.toString());
        wildcard = wildcard.replace("{{自定义}}", targetName);
        if (!Check.isNull(campaignId)) {
            Integer count = null;
            if (null != strategy.getSingleAppid() && strategy.getSingleAppid() == 0 && strategy.getMultipleBids() == 0) {
                String redisKey = strategy.getAccountId() + "_" + campaignId;
                Object redisValue = redisUtil.get(redisKey);
                if (Check.isNull(redisValue)) {
                    count = 1;
                    redisUtil.set(redisKey, count);
                } else {
                    count = (Integer) redisValue + 1;
                    redisUtil.set(redisKey, count);
                }
            } else {
                String redisKey = strategy.getAccountId() + "_" + campaignId + nowDate;
                Object redisValue = redisUtil.get(redisKey);
                if (Check.isNull(redisValue)) {
                    count = 1;
                    redisUtil.set(redisKey, count, 100000L);
                } else {
                    count = (Integer) redisValue + 1;
                    redisUtil.set(redisKey, count, 100000L);
                }
            }
            wildcard = wildcard + "-" + count;
        }
        wildcard = wildcard.replace("--", "-");
        if (wildcard.startsWith("-")) {
            wildcard = wildcard.substring(1, wildcard.length());
        }
        if (wildcard.endsWith("-")) {
            wildcard = wildcard.substring(0, wildcard.length() - 1);
        }
        return wildcard;
    }

    private String getAdSenceByParams(String sceneIdString) {
        String adsence = "";
        if (null == sceneIdString || "".equals(sceneIdString)) {
            return adsence;
        }
        JSONArray sceneIdArray = JSON.parseArray(sceneIdString);
        if (null == sceneIdArray || sceneIdArray.isEmpty()) {
            return adsence;
        }
        for (int i = 0; i < sceneIdArray.size(); i++) {
            adsence += KuaishouCreativeAdsenceTypeEnum.getNameByType(sceneIdArray.getInteger(i)) + ",";
        }
        return adsence.substring(0, adsence.length() - 1);
    }


    @Override
    public Boolean getUnitOverrun(Long accountId) {
        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
        String key = accountId + "_" + nowDate + "unit_create_overrun";
        Object redisObj = redisUtil.get(key);
        if (Check.isNull(redisObj)) {
            return false;
        }
        Integer value = (Integer) redisObj;
        if (value == 1) {
            return true;
        } else {
            return false;
        }

    }

}
