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

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.KuaiShouGroupTemplate;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplateTarget;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupTemplateMapper;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 创建组模板
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-12-15
 */
@Service
@Slf4j
public class KuaiShouGroupTemplateServiceImpl extends ServiceImpl<KuaiShouGroupTemplateMapper, KuaiShouGroupTemplate> implements IKuaiShouGroupTemplateService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private KuaiShouGroupTemplateMapper groupTemplateMapper;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Autowired
    private IKuaishouTemplateTargetService templateTargetService;

    static ExecutorService executorService = Executors.newFixedThreadPool(5);

    /**
     * 提交创建任务
     *
     * @param requestJson
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject submitUnitTask(JSONObject requestJson) throws Exception {
        Long accountId = requestJson.getLong("accountId");
        if (Check.isNull(accountId)) {
            throw new Exception("accountId不能为空");
        }
        Long campaignId = requestJson.getLong("campaignId");
        if (Check.isNull(campaignId)) {
            throw new Exception("campaignId不能为空");
        }
        Integer createCount = requestJson.getInteger("createCount");
        if (Check.isNull(createCount)) {
            throw new Exception("创建数不能为空不能为空");
        }
        JSONArray photoArr = requestJson.getJSONArray("photoArr");
        if (Check.isNull(photoArr)) {
            throw new Exception("请选择需要创建的视频");
        }

        Integer createType = requestJson.getInteger("createType"); // 创建类型 0 单品 1 混搭
        if (Check.isNull(createType)) {
            throw new Exception("请选择创意创建方式混搭、单品");
        }

        if (createType == 0 && createCount != photoArr.size()) {
            throw new Exception("单品视频数量必须和创建数量保持一致");
        }

        if (createType == 1 && createCount * 15 != photoArr.size()) {
            throw new Exception("混搭视频数量必须和创建数量保持倍数关系");
        }

        JSONObject returnJson = new JSONObject();
        String userId = requestJson.getString("userId");
        String unitName = requestJson.getString("unitName");
        Long template_id = requestJson.getLong("templateId");
        Integer bid_type = requestJson.getInteger("bidType");
        Integer use_app_market = requestJson.getInteger("useAppMarket");
        JSONArray app_store = requestJson.getJSONArray("appStore");
        Long bid = requestJson.getLong("bid");
        Long cpa_bid = requestJson.getLong("cpaBid");
        Integer ocpx_action_type = requestJson.getInteger("ocpxActionType");
        Integer deep_conversion_type = requestJson.getInteger("deepConversionType");
        Long deep_conversion_bid = requestJson.getLong("deepConversionBid");
        JSONArray scene_id = requestJson.getJSONArray("sceneId");
        Integer unit_type = requestJson.getInteger("unitType");
        String begin_time = requestJson.getString("beginTime");
        String end_time = requestJson.getString("endTime");
        String schedule_time = requestJson.getString("scheduleTime");
        Long day_budget = requestJson.getLong("dayBudget");
        Long convert_id = requestJson.getLong("convertId");
        Integer url_type = requestJson.getInteger("urlType");
        String url = requestJson.getString("url");
        Long app_id = requestJson.getLong("appId");
        Integer show_mode = requestJson.getInteger("showMode");
        Integer speed = requestJson.getInteger("speed");
        String click_track_url = requestJson.getString("clickTrackUrl");
        String actionbar_click_url = requestJson.getString("actionbarClickUrl");
        Integer creative_category = requestJson.getInteger("creativeCategory");
        JSONArray creative_tag = requestJson.getJSONArray("creativeTag");
        String creative_name = requestJson.getString("creativeName");
        String action_bar_text = requestJson.getString("actionBarText");
        String description = requestJson.getString("description");
        String site_id = requestJson.getString("siteId");
        String schema_uri = requestJson.getString("schemaUri");
        Integer startNumber = 0;
        if (unitName.contains("{{序号}}")) {
            if (!Check.isNull(requestJson.getInteger("startNumber"))) {
                startNumber = requestJson.getInteger("startNumber");
            }
        }
        Integer imageCount = requestJson.getInteger("imageCount");

        List<KuaiShouGroupTemplate> templates = new ArrayList<>();
        for (int i = 0; i < createCount; i++) {
            KuaiShouGroupTemplate template = new KuaiShouGroupTemplate();
            template.setCreateType(createType);
            if (createType == 0) { // 创建方式为单品
                Long photoId = photoArr.getLong(i);
                template.setPhotoId(photoId);
            } else if (createType == 1) { // 创建方式为混搭
                JSONArray photoIds = getPhotoIds(photoArr, i);
                if (Check.isNull(photoIds)) {
                    log.error("根据下标未获取到详细信息");
                    continue;
                }
                template.setPhotoIds(photoIds.toJSONString());
            }
            String name = "";
            if (!unitName.contains("{{序号}}")) {
                name = unitName + "_" + i;
            } else {
                if (i == 0) {
                    name = unitName.replace("{{序号}}", String.valueOf(startNumber));
                } else {
                    name = unitName.replace("{{序号}}", String.valueOf(startNumber + i));
                }
            }

            template.setUnitName(name);
            template.setAccountId(accountId);
            template.setUserId(userId);
            template.setCampaignId(campaignId);

            if (!Check.isNull(template_id)) {
                template.setTemplateId(template_id);
            }
            if (!Check.isNull(bid_type)) {
                template.setBidType(bid_type);
            }
            if (!Check.isNull(use_app_market)) {
                template.setUseAppMarket(use_app_market);
            }
            if (!Check.isNull(app_store)) {
                template.setAppStore(app_store.toJSONString());
            }
            if (!Check.isNull(bid)) {
                template.setBid(bid);
            }
            if (!Check.isNull(cpa_bid)) {
                template.setCpaBid(cpa_bid);
            }
            if (!Check.isNull(ocpx_action_type)) {
                template.setOcpxActionType(ocpx_action_type);
            }
            if (!Check.isNull(deep_conversion_type)) {
                template.setDeepConversionType(deep_conversion_type);
            }
            if (!Check.isNull(deep_conversion_bid)) {
                template.setDeepConversionBid(deep_conversion_bid);
            }
            if (!Check.isNull(scene_id)) {
                template.setSceneId(scene_id.toJSONString());
            }
            if (!Check.isNull(unit_type)) {
                template.setUnitType(unit_type);
            }
            if (!Check.isNull(begin_time)) {
                template.setBeginTime(begin_time);
            }
            if (!Check.isNull(end_time)) {
                template.setEndTime(end_time);
            }
            if (!Check.isNull(schedule_time)) {
                template.setScheduleTime(schedule_time);
            }
            if (!Check.isNull(day_budget)) {
                template.setDayBudget(day_budget);
            }
            if (!Check.isNull(convert_id)) {
                template.setConvertId(convert_id);
            }
            if (!Check.isNull(url_type)) {
                template.setUrlType(url_type);
            }
            if (!Check.isNull(url)) {
                template.setUrl(url);
            }
            if (!Check.isNull(schema_uri)) {
                template.setSchemaUri(schema_uri);
            }
            if (!Check.isNull(app_id)) {
                template.setAppId(app_id);
            }
            if (!Check.isNull(show_mode)) {
                template.setShowMode(show_mode);
            }
            if (!Check.isNull(speed)) {
                template.setSpeed(speed);
            }
            if (!Check.isNull(click_track_url)) {
                template.setClickTrackUrl(click_track_url);
            }
            if (!Check.isNull(actionbar_click_url)) {
                template.setActionbarClickUrl(actionbar_click_url);
            }
            if (!Check.isNull(creative_category)) {
                template.setCreativeCategory(creative_category);
            }
            if (!Check.isNull(creative_tag)) {
                template.setCreativeTag(creative_tag.toJSONString());
            }
            if (!Check.isNull(creative_name)) {
                template.setCreativeName(creative_name);
            }
            if (!Check.isNull(action_bar_text)) {
                template.setActionBarText(action_bar_text);
            }
            if (!Check.isNull(description)) {
                template.setDescription(description);
            }
            if (!Check.isNull(description)) {
                template.setDescription(description);
            }
            if (!Check.isNull(site_id)) {
                template.setSiteId(site_id);
            }
            template.setImageCount(imageCount);
            template.setTaskStatus(0);
            template.setCreativeReviewDetail("创意待创建");
            template.setCreativeStatus(0);
            templates.add(template);
        }
        boolean b = this.saveBatch(templates);
        if (b) {
            returnJson.put("code", 0);
            returnJson.put("size", templates.size());
        } else {
            returnJson.put("code", -1);
            returnJson.put("message", "提交任务失败");
        }

        return returnJson;
    }

    private JSONArray getPhotoIds(JSONArray photoArr, Integer index) {
        JSONArray array = new JSONArray();
        Integer minIndex;
        Integer maxIndex;
        if (index == 0) {
            maxIndex = (index + 1) * 15 - 1;
            minIndex = index;
        } else {
            maxIndex = (index + 1) * 15 - 1;
            minIndex = index * 15;
        }
        for (int i = 0; i < photoArr.size(); i++) {
            if (minIndex > maxIndex) {
                break;
            }
            Long photoId = photoArr.getLong(minIndex);
            array.add(photoId);
            minIndex++;
        }
        return array;
    }


    /**
     * 创建组
     */
    @Override
    public void createUnit(KuaiShouGroupTemplate template) {
        Long accountId = template.getAccountId();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        KuaiShouGroupTemplate updateTemplate = new KuaiShouGroupTemplate();
        if (Check.isNull(token)) {
            updateTemplate.setTaskStatus(3);
            updateTemplate.setReviewDetail("未获取到授权信息");
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("未获取到授权信息");
            updateById(updateTemplate);
            return;
        }
        JSONObject createUnitJson = new JSONObject();
        JSONArray sceneIdArr = JSONArray.parseArray(template.getSceneId());
        if (Check.isNull(sceneIdArr)) {
            updateTemplate.setTaskStatus(3);
            updateTemplate.setReviewDetail("scene_id不能为空");
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("组创建失败");
            updateById(updateTemplate);
            return;
        }
        createUnitJson.put("scene_id", sceneIdArr); //资源位置
        Integer sceneId = (Integer) sceneIdArr.get(0);
        if (sceneId != 5) {
            if (!Check.isNull(template.getTemplateId())) {
                createUnitJson.put("template_id", template.getTemplateId());
            }
        } else {
            if (!Check.isNull(template.getTemplateId())) {
                JSONObject unionJson = getUnionJson(template.getTemplateId());
                if (unionJson.getInteger("code") != 0) {
                    updateTemplate.setTaskStatus(3);
                    updateTemplate.setReviewDetail(unionJson.getString("message"));
                    updateTemplate.setCreativeStatus(3);
                    updateTemplate.setCreativeReviewDetail("组创建失败");
                    updateById(updateTemplate);
                    return;
                } else {
                    createUnitJson.put("target", unionJson.getJSONObject("target"));
                }
            }
        }
        createUnitJson.put("campaign_id", template.getCampaignId());
        createUnitJson.put("unit_name", template.getUnitName());
        if (!Check.isNull(template.getBidType())) {
            createUnitJson.put("bid_type", template.getBidType()); // 优化目标类型
        }
        if (!Check.isNull(template.getUseAppMarket())) {
            createUnitJson.put("use_app_market", template.getUseAppMarket()); //优先从系统应用商店下载
        }
        if (!Check.isNull(template.getAppStore())) {
            createUnitJson.put("app_store", JSONArray.parseArray(template.getAppStore())); //应用商店列表
        }
        if (!Check.isNull(template.getBid())) {
            createUnitJson.put("bid", template.getBid()); //出价
        }
        if (!Check.isNull(template.getCpaBid())) {
            createUnitJson.put("cpa_bid", template.getCpaBid()); //出价
        }
        if (!Check.isNull(template.getOcpxActionType())) {
            createUnitJson.put("ocpx_action_type", template.getOcpxActionType()); //优化目标
        }
        if (!Check.isNull(template.getDeepConversionType())) {
            createUnitJson.put("deep_conversion_type", template.getDeepConversionType()); //深度转化目标
        }
        if (!Check.isNull(template.getDeepConversionBid())) {
            createUnitJson.put("deep_conversion_bid", template.getDeepConversionBid()); //深度转化目标出价
        }
        if (!Check.isNull(template.getUnitType())) {
            createUnitJson.put("unit_type", template.getUnitType()); //创意制作方式
        }
        if (!Check.isNull(template.getBeginTime())) {
            createUnitJson.put("begin_time", template.getBeginTime()); //投放开始时间
        }
        if (!Check.isNull(template.getEndTime())) {
            createUnitJson.put("end_time", template.getEndTime()); //投放结束时间
        }
        if (!Check.isNull(template.getScheduleTime())) {
            createUnitJson.put("schedule_time", template.getScheduleTime()); //投放时间段
        }
        if (!Check.isNull(template.getDayBudget())) {
            createUnitJson.put("day_budget", template.getDayBudget()); //单日预算金额
        }
        if (!Check.isNull(template.getConvertId())) {
            createUnitJson.put("convert_id", template.getConvertId()); //转化目标ID
        }
        if (!Check.isNull(template.getUrlType())) {
            createUnitJson.put("url_type", template.getUrlType()); //url类型
        }
        if (!Check.isNull(template.getUrl())) {
            createUnitJson.put("url", template.getUrl()); // 投放链接
        }
        if (!Check.isNull(template.getSchemaUri())) {
            createUnitJson.put("schema_uri", template.getSchemaUri()); // 吊起链接
        }

        if (!Check.isNull(template.getAppId())) {
            createUnitJson.put("app_id", template.getAppId()); // 应用ID
        }
        if (!Check.isNull(template.getShowMode())) {
            createUnitJson.put("show_mode", template.getShowMode()); // 创意展现方式
        }
        if (!Check.isNull(template.getSpeed())) {
            createUnitJson.put("speed", template.getSpeed()); // 投放方式
        }
        Map<String, Object> groupMap = iKuaishouInterfaceService.adUnitCreate(token.getAccessToken(), accountId, createUnitJson, 1);
        updateTemplate = new KuaiShouGroupTemplate();
        updateTemplate.setId(template.getId());
        Integer code = (Integer) groupMap.get("code");
        if (code == 0) {
            updateTemplate.setTaskStatus(2);
            Long unit = (Long) groupMap.get("unitId");
            updateTemplate.setUnitId((unit));
            Thread thread = new Thread() {
                @Override
                public void run() {
                    createCreative(token.getAccessToken(), unit, template);
                }
            };
            thread.start();
        } else {
            updateTemplate.setTaskStatus(3);
            updateTemplate.setReviewDetail((String) groupMap.get("message"));
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("组创建失败");
        }
        updateById(updateTemplate);
        try {
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据模板id 获取联盟定向
     *
     * @return
     */
    @Override
    public JSONObject getUnionJson(Long templateId) {
        JSONObject returnJson = new JSONObject();
        QueryWrapper<KuaishouTemplateTarget> targetQueryWrapper = new QueryWrapper<>();
        targetQueryWrapper.eq("template_id", templateId);
        targetQueryWrapper.last("limit 1");
        KuaishouTemplateTarget templateTarget = templateTargetService.getOne(targetQueryWrapper);
        if (Check.isNull(templateTarget)) {
            returnJson.put("code", -1);
            returnJson.put("message", "根据模板id未获取到模板详情");
            return returnJson;
        }
        JSONObject target = new JSONObject();
        if (!Check.isNull(templateTarget.getRegion())) {
            target.put("region", JSONArray.parseArray(templateTarget.getRegion()));
        }

        if (!Check.isNull(templateTarget.getMax()) && !Check.isNull(templateTarget.getMin())) {
            JSONObject ageJson = new JSONObject();
            if (!Check.isNull(templateTarget.getMax())) {
                ageJson.put("max", templateTarget.getMax());
            }
            if (!Check.isNull(templateTarget.getMin())) {
                ageJson.put("min", templateTarget.getMin());
            }
            target.put("age", ageJson);
        }
        if (!Check.isNull(templateTarget.getAgesRange())) {
            target.put("ages_range", JSONArray.parseArray(templateTarget.getAgesRange()));
        }

        if (!Check.isNull(templateTarget.getGender())) {
            target.put("gender", templateTarget.getGender());
        }

        if (!Check.isNull(templateTarget.getPlatformOs())) {
            target.put("platform_os", templateTarget.getPlatformOs());
        }

        if (!Check.isNull(templateTarget.getAndroidOsv())) {
            target.put("android_osv", templateTarget.getAndroidOsv());
        }

        if (!Check.isNull(templateTarget.getIosOsv())) {
            target.put("ios_osv", templateTarget.getIosOsv());
        }

        if (!Check.isNull(templateTarget.getNetwork())) {
            target.put("network", templateTarget.getNetwork());
        }

        if (!Check.isNull(templateTarget.getDeviceBrand())) {
            target.put("device_brand", JSONArray.parseArray(templateTarget.getDeviceBrand()));
        }

        if (!Check.isNull(templateTarget.getDevicePrice())) {
            target.put("device_price", JSONArray.parseArray(templateTarget.getDevicePrice()));
        }

        if (!Check.isNull(templateTarget.getAppInterest())) {
            target.put("app_interest", JSONArray.parseArray(templateTarget.getAppInterest()));
        }

        if (!Check.isNull(templateTarget.getAppIds())) {
            target.put("app_ids", JSONArray.parseArray(templateTarget.getAppIds()));
        }

        if (!Check.isNull(templateTarget.getPopulation())) {
            target.put("population", JSONArray.parseArray(templateTarget.getPopulation()));
        }

        if (!Check.isNull(templateTarget.getExcludePopulation())) {
            target.put("exclude_population", JSONArray.parseArray(templateTarget.getExcludePopulation()));
        }

        if (!Check.isNull(templateTarget.getPaidAudience())) {
            target.put("paid_audience", JSONArray.parseArray(templateTarget.getPaidAudience()));
        }
        //-------------兴趣行为定向
    /*    JSONObject behaviorInterest = new JSONObject();
        JSONObject behavior = new JSONObject();
        JSONObject interest = new JSONObject();*/
 /*       if (!Check.isNull(templateTarget.getKeyword())) {
            behavior.put("keyword", JSONArray.parseArray(templateTarget.getKeyword()));
        }
        if (!Check.isNull(templateTarget.getLabel())) {
            behavior.put("label", JSONArray.parseArray(templateTarget.getLabel()));
        }
        if (!Check.isNull(templateTarget.getStrengthType())) {
            behavior.put("strength_type", templateTarget.getStrengthType());
        }
        if (!Check.isNull(templateTarget.getTimeType())) {
            behavior.put("time_type", templateTarget.getTimeType());
        }
        if (!Check.isNull(templateTarget.getSceneType())) {
            behavior.put("scene_type", JSONArray.parseArray(templateTarget.getSceneType()));
        }
        if (!Check.isNull(templateTarget.getInterestLabel())) {
            interest.put("label", JSONArray.parseArray(templateTarget.getInterestLabel()));
        }
        if (!Check.isNull(behavior)) {
            behaviorInterest.put("behavior", behavior);
        }
        if (!Check.isNull(interest)) {
            behaviorInterest.put("interest", interest);
        }
        if (!Check.isNull(behaviorInterest)) {
            target.put("behavior_interest", behaviorInterest);
        }*/
        returnJson.put("target", target);
        returnJson.put("code", 0);
        return returnJson;
    }

    @Override
    public List<Long> getIdList() {
        return groupTemplateMapper.getIdList();
    }

    /**
     * 获取当天api创建创意数
     *
     * @param accountId
     * @param date
     * @return
     */
    @Override
    public Integer getApiCreateCount(Long accountId, String date) {
        return groupTemplateMapper.getApiCreateCount(accountId, date);
    }

    /**
     * 根据photoId 获取视频、封面链接
     *
     * @param photoId
     * @return
     */
    @Override
    public JSONObject getUrlByPhotoId(Long photoId) {
        return groupTemplateMapper.getUrlByPhotoId(photoId.toString());
    }

    /**
     * 创建创意
     *
     * @param accessToken
     * @param unitId
     * @param template
     */
    @Override
    public void createCreative(String accessToken, Long unitId, KuaiShouGroupTemplate template) {
        KuaiShouGroupTemplate updateTemplate = new KuaiShouGroupTemplate();
        updateTemplate.setId(template.getId());
        updateTemplate.setCreativeStatus(1);
        updateTemplate.setCreativeReviewDetail("创意创建中");
        this.updateById(updateTemplate);
        JSONObject createJson = new JSONObject();
        createJson.put("unit_id", unitId);
        if (!Check.isNull(template.getClickTrackUrl())) {
            createJson.put("click_track_url", template.getClickTrackUrl());
        }
        if (!Check.isNull(template.getActionbarClickUrl())) {
            createJson.put("actionbar_click_url", template.getActionbarClickUrl());
        }
        if (!Check.isNull(template.getCreativeCategory())) {
            createJson.put("creative_category", template.getCreativeCategory());
        }
        if (!Check.isNull(template.getCreativeTag())) {
            createJson.put("creative_tag", JSONArray.parseArray(template.getCreativeTag()));
        }

        JSONArray creatives = new JSONArray();
        Integer createType = template.getCreateType();
        if (createType == 0) { // 单品
            Long photoId = template.getPhotoId();
            JSONObject videoMd5Json = groupTemplateMapper.getMd5ByPhotoId(String.valueOf(photoId));
            if (Check.isNull(videoMd5Json)) {
                log.error("未获取到素材详细信息,accountId:{},unitId:{}", template.getAccountId(), unitId);
                updateTemplate.setCreativeStatus(3);
                updateTemplate.setCreativeReviewDetail("未获取到素材信息");
                this.updateById(updateTemplate);
                return;
            }
            Integer materialType = videoMd5Json.getInteger("materialType");
            String videoMd5 = videoMd5Json.getString("md5");
            List<JSONObject> imageList = groupTemplateMapper.getImageListByMd5(videoMd5, template.getImageCount());
            if (Check.isNull(imageList)) {
                JSONObject json = new JSONObject();
                json.put("creative_name", template.getCreativeName());
                json.put("photo_id", template.getPhotoId());
                json.put("creative_material_type", materialType);
                json.put("action_bar_text", template.getActionBarText());
                json.put("description", template.getDescription());
                if (!Check.isNull(template.getSiteId())) {
                    json.put("site_id", template.getSiteId());
                }
                creatives.add(json);
            } else {
                for (int i = 0; i < imageList.size(); i++) {
                    JSONObject imageJson = imageList.get(i);
                    if (Check.isNull(imageJson)) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    String imageMd5 = imageJson.getString("md5");
                    String imageToken = getImageToken(imageMd5, template.getAccountId(), accessToken, imageJson.getString("url"));
                    if (Check.isNull(imageToken)) {
                        continue;
                    }
                    json.put("image_token", imageToken);
                    json.put("creative_name", template.getCreativeName() + "_" + i);
                    json.put("photo_id", template.getPhotoId());
                    json.put("creative_material_type", materialType);
                    json.put("action_bar_text", template.getActionBarText());
                    json.put("description", template.getDescription());
                    if (!Check.isNull(template.getSiteId())) {
                        json.put("site_id", template.getSiteId());
                    }
                    creatives.add(json);
                }
            }
        } else if (createType == 1) {  // 混搭
            JSONArray array = JSONArray.parseArray(template.getPhotoIds());
            if (Check.isNull(array)) {
                updateTemplate.setCreativeStatus(3);
                updateTemplate.setCreativeReviewDetail("未获取到混搭素材信息");
                this.updateById(updateTemplate);
                return;
            }
            for (int i = 0; i < array.size(); i++) {
                Long photoId = array.getLong(i);
                JSONObject videoJson = groupTemplateMapper.getMd5ByPhotoId(String.valueOf(photoId));
                if (Check.isNull(videoJson)) {
                    log.error("未获取到素材详细信息,accountId:{},unitId:{}", template.getAccountId(), unitId);
                    updateTemplate.setCreativeStatus(3);
                    updateTemplate.setCreativeReviewDetail("未获取到素材信息");
                    this.updateById(updateTemplate);
                    return;
                }
                String videoMd5 = videoJson.getString("md5");
                Integer materialType = videoJson.getInteger("materialType");
                JSONObject json = new JSONObject();
                JSONObject imageJson = groupTemplateMapper.getImageJsonByMd5(videoMd5);
                if (!Check.isNull(imageJson)) {
                    String imageToken = getImageToken(imageJson.getString("md5"), template.getAccountId(), accessToken, imageJson.getString("url"));
                    if (!Check.isNull(imageToken)) {
                        json.put("image_token", imageToken);
                    }
                }
                json.put("creative_name", template.getCreativeName() + "_" + i);
                json.put("photo_id", photoId);
                json.put("creative_material_type", materialType);
                json.put("action_bar_text", template.getActionBarText());
                json.put("description", template.getDescription());
                if (!Check.isNull(template.getSiteId())) {
                    json.put("site_id", template.getSiteId());
                }
                creatives.add(json);
            }
        }
        createJson.put("creatives", creatives);
        Map<String, Object> creativeMap = iKuaishouInterfaceService.batchCreativeCreate(accessToken, template.getAccountId(), createJson, 1, template.getUserId());
        Integer code = (Integer) creativeMap.get("code");
        if (code == 0) {
            updateTemplate.setCreativeStatus(2);
            updateTemplate.setCreativeReviewDetail("创意创建成功");
            updateTemplate.setCreateCreativeCount((Integer) creativeMap.get("count"));
        } else {
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail((String) creativeMap.get("message"));
        }
        this.updateById(updateTemplate);
    }


    private String getImageToken(String md5, Long accountId, String accessToken, String url) {

        String imageToken = null;
        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("signature", md5);
        queryWrapper.last("limit 1");
        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
        if (!Check.isNull(imageGet)) {
            imageToken = imageGet.getImageToken();
        } else {
            imageToken = uploadService.kuauiShouImageUpload(url, md5, accountId, accessToken);
        }


        return imageToken;

    }
}
