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.*;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAppPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouLandpagePackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouPopulationGroupService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
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.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CrossAccountBatchServiceImpl implements ICrossAccountBatchService {

    @Value("${kuaishou.realuser-ip}")
    private String realUserIP;

    @Autowired
    private IKuaiShouGroupService getKuaiShouGroupService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Autowired
    private IKuaiShouOverRunSendMessageService overRunSendMessageService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;

    @Autowired
    private IKuaishouDirectionalPackageService directionalPackageService;
    @Autowired
    private IKuaishouPopulationGroupService populationGroupService;
    @Autowired
    private IKuaishouAppPackageService appPackageService;
    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;

    /**
     * 组装数据  jason
     *
     * @param oauthToken
     * @param createUnitArr
     * @param campaignOne
     * @return
     */
    @Override
    public JSONArray assembleUnitJson(CtopOauthToken oauthToken, JSONArray createUnitArr, JSONObject campaignOne) {
        if (Check.isNull(campaignOne)) {
            return createUnitArr;
        }
        JSONArray campaignIds = campaignOne.getJSONArray("campaignIds"); // 计划ids
        if (Check.isNull(campaignIds)) {
            return createUnitArr;

        }
        JSONObject createUnitJson = this.getCreateUnitJson(campaignOne);// 通用参数组装
        JSONArray unitNames = campaignOne.getJSONArray("unitNames"); // 组名称集合
        if (Check.isNull(unitNames)) {
            return createUnitArr;
        }
        createUnitJson.put("advertiser_id", oauthToken.getAccountId());
        createUnitJson.put("access_token", oauthToken.getAccessToken());
        for (int i = 0; i < campaignIds.size(); i++) {
            Long campaignId = campaignIds.getLong(i);
            if (Check.isNull(campaignId)) {
                continue;
            }
            for (int j = 0; j < unitNames.size(); j++) {
                String unitName = unitNames.getString(j);
                if (!Check.isNull(unitName)) {
                    String s = JSON.toJSONString(createUnitJson, SerializerFeature.DisableCircularReferenceDetect);
                    createUnitJson = JSON.parseObject(s);
                    createUnitJson.remove("campaign_id");
                    createUnitJson.remove("unit_name");
                    createUnitJson.put("campaign_id", campaignId);
                    createUnitJson.put("unit_name", unitName);
                    createUnitArr.add(createUnitJson);
                }
            }
        }
        return createUnitArr;
    }

    /**
     * 组装数据 array
     *
     * @param oauthToken
     * @param createUnitArr
     * @param campaignList
     * @return
     */
    @Override
    public JSONArray assembleUnitArray(CtopOauthToken oauthToken, JSONArray createUnitArr, JSONArray campaignList) {
        for (int i = 0; i < campaignList.size(); i++) {
            JSONObject campaignJson = campaignList.getJSONObject(i);
            if (Check.isNull(campaignJson)) {
                continue;
            }
            Long campaignId = campaignJson.getLong("campaignId");
            Integer check = campaignJson.getInteger("check");
            if (check == 1) { // 计划下组相同
                JSONObject unitIdenticalJson = campaignJson.getJSONObject("unitIdentical");
                if (Check.isNull(unitIdenticalJson)) {
                    continue;
                }
                JSONArray unitNames = unitIdenticalJson.getJSONArray("unitName");
                if (Check.isNull(unitNames)) {
                    continue;
                }

                JSONObject createUnitJson = this.getCreateUnitJson(unitIdenticalJson);// 通用参数组装
                for (int j = 0; j < unitNames.size(); j++) {
                    String s = JSON.toJSONString(createUnitJson, SerializerFeature.DisableCircularReferenceDetect);
                    createUnitJson = JSON.parseObject(s);

                    String unitName = unitNames.getString(j);
                    createUnitJson.put("advertiser_id", oauthToken.getAccountId());
                    createUnitJson.put("access_token", oauthToken.getAccessToken());
                    createUnitJson.remove("campaign_id");
                    createUnitJson.remove("unit_name");
                    createUnitJson.put("campaign_id", campaignId);
                    createUnitJson.put("unit_name", unitName);
                    createUnitArr.add(createUnitJson);
                }
            } else if (check == 2) {// 计划下组不同
                JSONArray unitArray = campaignJson.getJSONArray("unit");
                if (Check.isNull(unitArray)) {
                    continue;
                }
                for (int j = 0; j < unitArray.size(); j++) {
                    JSONObject unitJson = unitArray.getJSONObject(j);
                    if (Check.isNull(unitJson)) {
                        continue;
                    }
                    JSONObject createUnitJson = this.getCreateUnitJson(unitJson);// 通用参数组装
                    createUnitJson.put("advertiser_id", oauthToken.getAccountId());
                    createUnitJson.put("access_token", oauthToken.getAccessToken());
                    createUnitJson.remove("campaign_id");
                    createUnitJson.remove("unit_name");
                    createUnitJson.put("campaign_id", campaignId);
                    createUnitJson.put("unit_name", unitJson.getString("name"));
                    createUnitArr.add(createUnitJson);
                }
            }
        }
        return createUnitArr;
    }

    /**
     * 批量创建广告组
     *
     * @param createUnitArr
     * @return
     */
    @Override
    public JSONArray createUnit(JSONArray createUnitArr) {
        JSONArray returnArr = new JSONArray();
        for (int i = 0; i < createUnitArr.size(); i++) {
            JSONObject createUnitJson = createUnitArr.getJSONObject(i);
            if (Check.isNull(createUnitJson)) {
                continue;
            }
            JSONObject resultJson = adUnitCreate(createUnitJson, 1);
            returnArr.add(resultJson);

        }
        return returnArr;
    }

    /**
     * 组装创建创意数据
     *
     * @param creativeArray
     * @param accountJson
     * @return
     */
    @Override
    public JSONArray assembleCreativeJson(JSONArray creativeArray, JSONObject accountJson) {
        if (Check.isNull(accountJson)) {
            return creativeArray;
        }
        Long accountId = accountJson.getLong("accountId");
        if (Check.isNull(accountId)) {
            return creativeArray;
        }
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        if (Check.isNull(oauthToken)) {
            return creativeArray;
        }
        Long unitId = accountJson.getLong("unitId");
        if (Check.isNull(unitId)) {
            return creativeArray;
        }

        JSONArray photoArr = accountJson.getJSONArray("photoArr");
        if (Check.isNull(photoArr)) {
            return creativeArray;
        }


        String clickTrackUrl = accountJson.getString("clickTrackUrl");
        String impressionUrl = accountJson.getString("impressionUrl");
        String adPhotoPlayedT3sUrl = accountJson.getString("adPhotoPlayedT3sUrl");
        Integer creativeCategory = accountJson.getInteger("creativeCategory");
        JSONArray creativeTag = accountJson.getJSONArray("creativeTag");
        String actionBarText = accountJson.getString("actionBarText");
        String siteId = accountJson.getString("siteId");


        for (int i = 0; i < photoArr.size(); i++) {
            JSONObject photoJson = photoArr.getJSONObject(i);
            if (Check.isNull(photoJson)) {
                continue;
            }
            JSONObject creativeJson = new JSONObject();
            creativeJson.put("advertiser_id", oauthToken.getAccountId());
            creativeJson.put("access_token", oauthToken.getAccessToken());
            creativeJson.put("unit_id", unitId);
            creativeJson.put("unit_name", accountJson.getString("unitName"));
            if (!Check.isNull(clickTrackUrl)) {
                creativeJson.put("click_track_url", clickTrackUrl); //第三方点击检测链接
            }
            if (!Check.isNull(impressionUrl)) {
                creativeJson.put("impression_url", impressionUrl); //第三方开始播放监测链接
            }
            if (!Check.isNull(adPhotoPlayedT3sUrl)) {
                creativeJson.put("ad_photo_played_t3s_url", adPhotoPlayedT3sUrl); //第三方有效播放监测链接
            }
            if (!Check.isNull(photoJson.getString("actionbarClickUrl"))) {
                creativeJson.put("actionbar_click_url", photoJson.getString("actionbarClickUrl")); //第三方点击按钮监测链接
            }
            if (!Check.isNull(creativeCategory)) {
                creativeJson.put("creative_category", creativeCategory); // 创意分类
            }
            if (!Check.isNull((creativeTag))) {
                creativeJson.put("creative_tag", creativeTag); //创意标签
            }

            Long creativeMaterialType = photoJson.getLong("creativeMaterialType");

            JSONArray creatives = new JSONArray();
            String creativeName = photoJson.getString("creativeName");// 创意名称
            if (4 == creativeMaterialType) { // 便利贴组装数据

                JSONArray imageTokens = photoJson.getJSONArray("imageTokens");
                for (int j = 0; j < imageTokens.size(); j++) {
                    String imageToken = imageTokens.getString(j);
                    if (!Check.isNull(imageToken)) {
                        JSONObject createJson = new JSONObject();
                        if (!Check.isNull(photoJson.getString("shortSlogan"))) {
                            createJson.put("short_slogan", photoJson.getString("shortSlogan")); // 便利贴创意短广告语
                        }
                        if (!Check.isNull(creativeMaterialType)) {
                            createJson.put("creative_material_type", creativeMaterialType); // 素材类型
                        }
                        if (!Check.isNull(actionBarText)) {
                            createJson.put("action_bar_text", actionBarText); // 行动号召按钮文案
                        }
                        if (!Check.isNull(photoJson.getString("description"))) {
                            createJson.put("description", photoJson.getString("description")); // 广告语
                        }
                        if (!Check.isNull(photoJson.getString("stickerTitle"))) {
                            createJson.put("sticker_title", photoJson.getString("stickerTitle")); //封面广告语标题
                        }
                        if (!Check.isNull(photoJson.getString("overlayType"))) {
                            createJson.put("overlay_type", photoJson.getString("overlayType")); // 贴纸样式类型
                        }
                        if (!Check.isNull(photoJson.getString("exposeTag"))) {
                            createJson.put("expose_tag", photoJson.getString("exposeTag")); //广告标签
                        }
                        if (!Check.isNull(photoJson.getString("newExposeTag"))) {
                            createJson.put("new_expose_tag", photoJson.getString("newExposeTag")); // 广告标签2期
                        }
                        if (!Check.isNull(siteId)) {
                            createJson.put("site_id", siteId); //安卓下载中间页ID
                        }
                        JSONArray imageTokenArr = new JSONArray();
                        imageTokenArr.add(imageToken);
                        createJson.put("image_tokens", imageTokenArr); // 便利贴创意短广告语
                        if (!Check.isNull(creativeName)) {
                            createJson.put("creative_name", creativeName + "_" + RandomUtil.verifyCodeV2()); // 便利贴创意短广告语
                        }
                        creatives.add(createJson);
                    }
                }
                creativeJson.put("creatives", creatives);
            } else { //  非便利贴组装数据
                JSONArray imageTokenArr = photoJson.getJSONArray("imageTokenArr");
                if (Check.isNull(imageTokenArr)) { // 如果图片为空 说明是首帧创建
                    JSONObject createJson = new JSONObject();
                    if (!Check.isNull(photoJson.getLong("photoId"))) {
                        createJson.put("photo_id", photoJson.getLong("photoId")); // 视频id
                    }
                    createJson.put("creative_name", creativeName); // 创意名称
                    if (!Check.isNull(creativeMaterialType)) {
                        createJson.put("creative_material_type", creativeMaterialType); // 素材类型
                    }
                    if (!Check.isNull(actionBarText)) {
                        createJson.put("action_bar_text", actionBarText); // 行动号召按钮文案
                    }
                    if (!Check.isNull(photoJson.getString("description"))) {
                        createJson.put("description", photoJson.getString("description")); // 广告语
                    }
                    if (!Check.isNull(photoJson.getString("stickerTitle"))) {
                        createJson.put("sticker_title", photoJson.getString("stickerTitle")); //封面广告语标题
                    }
                    if (!Check.isNull(photoJson.getString("overlayType"))) {
                        createJson.put("overlay_type", photoJson.getString("overlayType")); // 贴纸样式类型
                    }
                    if (!Check.isNull(photoJson.getString("exposeTag"))) {
                        createJson.put("expose_tag", photoJson.getString("exposeTag")); //广告标签
                    }
                    if (!Check.isNull(photoJson.getString("newExposeTag"))) {
                        createJson.put("new_expose_tag", photoJson.getString("newExposeTag")); // 广告标签2期
                    }
                    if (!Check.isNull(siteId)) {
                        createJson.put("site_id", siteId); //安卓下载中间页ID
                    }

                    if (!Check.isNull(photoJson.getString("stickerTitle"))) {
                        createJson.put("sticker_title", photoJson.getString("stickerTitle")); //封面广告语标题
                    }

                    creatives.add(createJson);
                } else { // 选择多张图片进行创建
                    for (int j = 0; j < imageTokenArr.size(); j++) {
                        String signature = imageTokenArr.getString(j);
                        if (Check.isNull(signature)) {
                            continue;
                        }
                        JSONObject createJson = new JSONObject();
                        if (!Check.isNull(photoJson.getLong("photoId"))) {
                            createJson.put("photo_id", photoJson.getLong("photoId")); // 视频id
                        }
                        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("account_id", accountId);
                        queryWrapper.eq("signature", signature);
                        queryWrapper.last("limit 1");
                        String imageToken = null;
                        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
                        if (!Check.isNull(imageGet)) {
                            imageToken = imageGet.getImageToken();
                        } else {
                            String url = imageGetService.getUrlByCode(signature);
                            imageToken = uploadService.kuauiShouImageUpload(url, signature, accountId, oauthToken.getAccessToken());
                        }
                        if (!Check.isNull(imageToken)) {
                            createJson.put("image_token", imageToken); // 封面图片 token
                        }
                        String name = creativeName + "_" + RandomUtil.verifyCodeV2();
                        createJson.put("creative_name", name); // 创意名称
                        if (!Check.isNull(creativeMaterialType)) {
                            createJson.put("creative_material_type", creativeMaterialType); // 素材类型
                        }
                        if (!Check.isNull(actionBarText)) {
                            createJson.put("action_bar_text", actionBarText); // 行动号召按钮文案
                        }
                        if (!Check.isNull(photoJson.getString("description"))) {
                            createJson.put("description", photoJson.getString("description")); // 广告语
                        }

                        if (!Check.isNull(photoJson.getString("stickerTitle"))) {
                            createJson.put("sticker_title", photoJson.getString("stickerTitle")); //封面广告语标题
                        }
                        if (!Check.isNull(photoJson.getString("overlayType"))) {
                            createJson.put("overlay_type", photoJson.getString("overlayType")); // 贴纸样式类型
                        }
                        if (!Check.isNull(photoJson.getString("exposeTag"))) {
                            createJson.put("expose_tag", photoJson.getString("exposeTag")); //广告标签
                        }
                        if (!Check.isNull(photoJson.getString("newExposeTag"))) {
                            createJson.put("new_expose_tag", photoJson.getString("newExposeTag")); // 广告标签2期
                        }
                        if (!Check.isNull(siteId)) {
                            createJson.put("site_id", siteId); //安卓下载中间页ID
                        }
                        creatives.add(createJson);
                    }

                }


            }
            creativeJson.put("creatives", creatives);
            creativeArray.add(creativeJson);
        }

        return creativeArray;
    }

    /**
     * 跨账户批量创建计划
     *
     * @param creativeArray
     * @return
     */
    @Override
    public JSONArray createCreative(JSONArray creativeArray) {
        JSONArray returnArr = new JSONArray();
        for (int i = 0; i < creativeArray.size(); i++) {
            JSONObject createUnitJson = creativeArray.getJSONObject(i);
            if (Check.isNull(createUnitJson)) {
                continue;
            }
            JSONObject resultJson = aCreativeCreate(createUnitJson, 1);
            returnArr.add(resultJson);
        }
        return returnArr;
    }

    /**
     * 调用快手创建接口
     *
     * @param requestJson
     * @param count
     * @return
     */

    private JSONObject adUnitCreate(JSONObject requestJson, Integer count) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("参数不能为空");
            }
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AD_UNIT_CREATE;
            Long advertiserId = requestJson.getLong("advertiser_id");
            String accessToken = requestJson.getString("access_token");
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("K-RealUser-IP", realUserIP);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("快手创建广告组返回，accountId:{},返回结果:{}", requestJson.getString("advertiser_id"), resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        Long unitId = dataJson.getLong("unit_id");

                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                getKuaiShouGroupService.getGroupByUnitId(accessToken, advertiserId, unitId);
                            }

                        };
                        thread.start();
                        returnJson.put("code", 0);
                        returnJson.put("accountId", requestJson.getLong("advertiser_id"));
                        returnJson.put("campaignId", requestJson.getLong("campaign_id"));
                        returnJson.put("unitId", unitId);
                        returnJson.put("accountName", requestJson.getString("account_name"));
                        returnJson.put("unitName", requestJson.getString("unit_name"));
                        returnJson.put("sceneId", requestJson.getJSONArray("scene_id").toJSONString());
                        returnJson.put("ocpxActionType", requestJson.getLong("ocpx_action_type"));
                        returnJson.put("bidType", requestJson.getLong("bid_type"));
                        returnJson.put("unitType", requestJson.getInteger("unit_type"));
                        //添加广告组和定向模板、人群包绑定关系
                        Thread thread2 = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject request = new JSONObject();
                                    request.put("accountId", requestJson.getLong("advertiser_id"));
                                    request.put("unitId", unitId);
                                    JSONObject target = requestJson.getJSONObject("target");
                                    if (!Check.isNull(target)) {
                                        request.put("excludePopulation", target.getJSONArray("exclude_population"));
                                        request.put("population", target.getJSONArray("population"));
                                        request.put("paidAudience", target.getJSONArray("paid_audience"));
                                        populationGroupService.createPopulationAndGroupRel(request);
                                    }
                                    if (!Check.isNull(requestJson.getLong("template_id"))) {
                                        request.put("templateId", requestJson.getLong("template_id"));
                                        directionalPackageService.createUnitAndTemplate(request);
                                    }
                                    if (!Check.isNull(requestJson.getLong("app_id"))) {
                                        request.put("appId", requestJson.getLong("app_id"));
                                        appPackageService.createAppAndGroupRel(request);
                                    }

                                } catch (Exception e) {
                                    log.error("添加广告组和定向模板、人群包绑定关系异常，", e);
                                }
                            }
                        };
                        thread2.start();
                    }
                } else {
                    if (code == 500000 && count <= 4) {
                        adUnitCreate(requestJson, count + 1);
                    }
                    log.error("创建广告信息失败,advertiser_id:{},返回信息：{}，入参：{}", advertiserId, resultJson, requestJson);
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                    returnJson.put("accountId", requestJson.getLong("advertiser_id"));
                    returnJson.put("accountName", requestJson.getString("account_name"));
                    returnJson.put("unitName", requestJson.getString("unit_name"));
                }
            } else {
                if (count <= 4) {
                    log.info("创建组失败，重试，入参：{}", requestJson);
                    adUnitCreate(requestJson, count + 1);
                }
                log.error("快手创建广告计划返回内容为空,advertiser_id:{}，入参：{}", advertiserId, requestJson);
                returnJson.put("code", -1);
                returnJson.put("message", "创建广告组异常，返回结果为空");
                returnJson.put("accountName", requestJson.getString("account_name"));
                returnJson.put("accountId", requestJson.getLong("advertiser_id"));
                returnJson.put("unitName", requestJson.getString("unit_name"));

            }
        } catch (Exception e) {
            log.error("创建广告计划失败,advertiser_id:{}", requestJson.getLong("advertiser_id"));
            returnJson.put("code", -1);
            returnJson.put("message", "创建广告组错误,系统异常");
            returnJson.put("accountId", requestJson.getLong("advertiser_id"));
            returnJson.put("accountName", requestJson.getString("account_name"));
            returnJson.put("unitName", requestJson.getString("unit_name"));
            returnJson.put("desc", "Interface exception");

            e.printStackTrace();
        }
        return returnJson;
    }

    /**
     * 创建创意
     *
     * @param
     * @param
     * @param requestJson
     * @param count
     * @return
     */
    private JSONObject aCreativeCreate(JSONObject requestJson, Integer count) {
        JSONObject retuenJson = new JSONObject();
        try {
            Long advertiserId = requestJson.getLong("advertiser_id");
            String accessToken = requestJson.getString("access_token");
            String url = "https://ad.e.kuaishou.com/rest/openapi/v2/creative/batch/update";
            requestJson.put("advertiser_id", advertiserId);
            Map<String, String> header = new HashMap<String, String>();
            header.put("Content-Type", " application/json");
            header.put("Access-Token", accessToken);

            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), header);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("快手创建创意返回：accountId:{}，返回结果{}", requestJson.getLong("advertiser_id"), resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        JSONArray add_creative_ids = dataJson.getJSONArray("add_creative_ids");
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(100);
                                    kuaishouInterfaceService.getCreativeByCreativeIds(accessToken, advertiserId, add_creative_ids);
                             //       createLandPageAndUnit(requestJson, add_creative_ids);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        thread.start();
                        retuenJson.put("code", 0);
                        retuenJson.put("accountId", requestJson.getLong("advertiser_id"));
                        retuenJson.put("unitId", requestJson.getString("unit_id"));
                        retuenJson.put("unitName", requestJson.getString("unit_name"));
                    }
                } else {
                    if (code == 500000 && count <= 4) {
                        aCreativeCreate(requestJson, count + 1);
                    }
                    if (code == 400001 && "/rest/openapi/v2/creative/create调用已超日限，次日可恢复调用".equals(resultJson.getString("message"))) {
                        overRunSendMessageService.creativeOverRunSendMessage(advertiserId, null);
                    }
                    log.error("创建广告创意失败,advertiser_id:{},返回信息：{}，入参：{},重试数:{}", advertiserId, resultJson, requestJson, count + 1);
                    retuenJson.put("code", -1);
                    retuenJson.put("message", resultJson.getString("message"));
                    retuenJson.put("accountId", requestJson.getLong("advertiser_id"));
                    retuenJson.put("unitId", requestJson.getString("unit_id"));
                    retuenJson.put("unitName", requestJson.getString("unit_name"));
                }
            } else {
                if (count <= 4) {
                    aCreativeCreate(requestJson, count + 1);
                }
                log.error("快手创建广告创意返回内容为空,advertiser_id:{}，入参：{}", advertiserId, requestJson);
                retuenJson.put("code", -1);
                retuenJson.put("message", "创建创意失败，返回信息为空");
                retuenJson.put("accountId", requestJson.getLong("advertiser_id"));
                retuenJson.put("unitId", requestJson.getString("unit_id"));
                retuenJson.put("unitName", requestJson.getString("unit_name"));
            }

        } catch (Exception e) {
            log.error("创建广告创意失败,advertiser_id:{}", requestJson.getLong("advertiser_id"));
            retuenJson.put("code", -1);
            retuenJson.put("message", e.getMessage());
            retuenJson.put("accountId", requestJson.getLong("advertiser_id"));
            retuenJson.put("unitId", requestJson.getString("unit_id"));
            retuenJson.put("unitName", requestJson.getString("unit_name"));
            e.printStackTrace();
        }
        return retuenJson;

    }

    //绑定落地页与广告组、创意的关系
    private void createLandPageAndUnit(JSONObject programJson, JSONArray add_creative_ids) {
        JSONArray creatives = programJson.getJSONArray("creatives");
        if (creatives != null && !creatives.isEmpty()) {
            JSONObject jsonObject = creatives.getJSONObject(0);
            Long siteId = jsonObject.getLong("site_id");
            if (!Check.isNull(siteId)) {
                if (!Check.isNull(jsonObject)) {
                    for (Object creativeId : add_creative_ids) {
                        landpagePackageService.createLandPageAndUnit(siteId, Long.valueOf(String.valueOf(creativeId)), jsonObject.getLong("unit_id"), jsonObject.getLong("advertiser_id"));
                    }
                }
            }
        }
    }

    /**
     * 通用组创建数据组装
     *
     * @param campaignOne
     * @return
     */
    private JSONObject getCreateUnitJson(JSONObject campaignOne) {
        JSONObject createUnitJson = new JSONObject();


        if (!Check.isNull(campaignOne.getString("accountName"))) {
            createUnitJson.put("account_name", campaignOne.getString("accountName")); // 优化目标类型
        }

        if (!Check.isNull(campaignOne.getInteger("bidType"))) {
            createUnitJson.put("bid_type", campaignOne.getInteger("bidType")); // 优化目标类型
        }

        if (!Check.isNull(campaignOne.getInteger("useAppMarket"))) {
            createUnitJson.put("use_app_market", campaignOne.getInteger("useAppMarket")); //优先从系统应用商店下载
        }
        if (!Check.isNull(campaignOne.getJSONArray("appStore"))) {
            createUnitJson.put("app_store", campaignOne.getJSONArray("appStore")); //应用商店列表
        }
        if (!Check.isNull(campaignOne.getLong("bid"))) {
            createUnitJson.put("bid", campaignOne.getLong("bid")); //出价

        }
        if (!Check.isNull(campaignOne.getLong("cpaBid"))) {
            createUnitJson.put("cpa_bid", campaignOne.getLong("cpaBid")); //出价

        }
        if (!Check.isNull(campaignOne.getInteger("smartBid"))) {
            createUnitJson.put("smart_bid", campaignOne.getInteger("smartBid")); //优先低成本出价(设置条件)

        }
        if (!Check.isNull(campaignOne.getInteger("ocpxActionType"))) {
            createUnitJson.put("ocpx_action_type", campaignOne.getInteger("ocpxActionType")); //优化目标

        }
        if (!Check.isNull(campaignOne.getInteger("deepConversionType"))) {
            createUnitJson.put("deep_conversion_type", campaignOne.getInteger("deepConversionType")); //深度转化目标

        }
        if (!Check.isNull(campaignOne.getDouble("roiRatio"))) {
            createUnitJson.put("roi_ratio", campaignOne.getDouble("roiRatio")); //付费ROI系数

        }
        if (!Check.isNull(campaignOne.getLong("deepConversionBid"))) {
            createUnitJson.put("deep_conversion_bid", campaignOne.getLong("deepConversionBid")); //深度转化目标出价

        }
        if (!Check.isNull(campaignOne.getJSONArray("sceneId"))) {
            createUnitJson.put("scene_id", campaignOne.getJSONArray("sceneId")); //资源位置

        }
        if (!Check.isNull(campaignOne.getInteger("unitType"))) {
            createUnitJson.put("unit_type", campaignOne.getInteger("unitType")); //创意制作方式

        }
        if (!Check.isNull(campaignOne.getString("beginTime"))) {
            createUnitJson.put("begin_time", campaignOne.getString("beginTime")); //投放开始时间

        }
        if (!Check.isNull(campaignOne.getString("endTime"))) {
            createUnitJson.put("end_time", campaignOne.getString("endTime")); //投放结束时间

        }
        if (!Check.isNull(campaignOne.getString("scheduleTime"))) {
            createUnitJson.put("schedule_time", campaignOne.getString("scheduleTime")); //投放时间段

        }
        if (!Check.isNull(campaignOne.getLong("dayBudget"))) {
            createUnitJson.put("day_budget", campaignOne.getLong("dayBudget")); //单日预算金额

        }
        if (!Check.isNull(campaignOne.getJSONArray("dayBudgetSchedule"))) {
            createUnitJson.put("day_budget_schedule", campaignOne.getJSONArray("dayBudgetSchedule")); //分日预算

        }
        if (!Check.isNull(campaignOne.getInteger("convert_id"))) {
            createUnitJson.put("convert_id", campaignOne.getInteger("convert_id")); //转化目标ID

        }
        if (!Check.isNull(campaignOne.getString("url_type"))) {
            createUnitJson.put("url_type", campaignOne.getString("url_type")); //url类型

        }
        if (!Check.isNull(campaignOne.getString("webUriType"))) {
            createUnitJson.put("web_uri_type", campaignOne.getString("webUriType")); //url类型

        }
        if (!Check.isNull(campaignOne.getString("url"))) {
            createUnitJson.put("url", campaignOne.getString("url")); // 投放链接

        }
        if (!Check.isNull(campaignOne.getString("schemaUri"))) {
            createUnitJson.put("schema_uri", campaignOne.getString("schemaUri")); // 调起链接

        }
        if (!Check.isNull(campaignOne.getString("appId"))) {
            createUnitJson.put("app_id", campaignOne.getString("appId")); // 应用ID

        }
        if (!Check.isNull(campaignOne.getInteger("showMode"))) {
            createUnitJson.put("show_mode", campaignOne.getInteger("showMode")); // 创意展现方式

        }
        if (!Check.isNull(campaignOne.getInteger("speed"))) {
            createUnitJson.put("speed", campaignOne.getInteger("speed")); // 投放方式

        }
        if (!Check.isNull(campaignOne.getInteger("siteType"))) {
            createUnitJson.put("site_type", campaignOne.getInteger("siteType")); //预约广告

        }
        if (!Check.isNull(campaignOne.getInteger("giftData"))) {
            createUnitJson.put("gift_data", campaignOne.getInteger("giftData")); //游戏礼包码

        }
        if (!Check.isNull(campaignOne.getBoolean("videoLandingPage"))) {
            createUnitJson.put("video_landing_page", campaignOne.getBoolean("videoLandingPage")); //游戏礼包码

        }
        if (!Check.isNull(campaignOne.getBoolean("autoTarget"))) {
            createUnitJson.put("auto_target", campaignOne.getBoolean("autoTarget")); //智能定向

        }
        if (!Check.isNull(campaignOne.getBoolean("smartCover"))) {
            createUnitJson.put("smart_cover", campaignOne.getBoolean("smartCover")); //是否开启智能抽帧

        }
        if (!Check.isNull(campaignOne.getBoolean("assetMining"))) {
            createUnitJson.put("asset_mining", campaignOne.getBoolean("assetMining")); //是否开启历史素材挖掘

        }

        if (!Check.isNull(campaignOne.getLong("templateId"))) {
            createUnitJson.put("template_id", campaignOne.getLong("templateId")); //定向模板id
        }

        return createUnitJson;
    }


}
