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.IMaterialCutFrameService;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaiShouCreateService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouLandpagePackageService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
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 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;

@Service
@Slf4j
public class KuaiShouCreateServiceImpl implements IKuaiShouCreateService {
    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private IKuaiShouGroupService groupService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IMaterialCutFrameService cutFrameService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;
    @Autowired
    private IKuaiShouGroupTemplateService groupTemplateService;
    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;

    @Value("${ai.callback.callback-unit-url}")
    private String unitUrl;
    @Value("${ai.callback.callback-creative-url}")
    private String creativeUrl;

    /**
     * 创建 组 && 创意
     *
     * @param oauthToken
     * @param campaign_id
     * @param group_list
     */
    @Override
    public void createUnitAndCreative(CtopOauthToken oauthToken, Long campaign_id, JSONArray group_list) {
        JSONArray returnArr = new JSONArray();
        for (int i = 0; i < group_list.size(); i++) {
            JSONObject groupCreateJson = group_list.getJSONObject(i);
            if (Check.isNull(groupCreateJson)) {
                continue;
            }
            String group_uuid = groupCreateJson.getString("group_uuid");
            try {

                Integer unit_type = groupCreateJson.getInteger("unit_type");
                if (Check.isNull(unit_type)) {
                    throw new Exception("请选择创意制作方式");
                }
                if (unit_type == 4) { //  自定义创意
                    if (Check.isNull(groupCreateJson.getJSONArray("creative_list"))) {
                        throw new Exception("组下面创意信息不能为空");
                    }
                } else if (unit_type == 7) { // 程序化创意
                    if (Check.isNull(groupCreateJson.getJSONObject("programCreative"))) {
                        throw new Exception("组下程序化创意信息不能为空");
                    }
                }
                JSONObject createJson = new JSONObject();
                createJson.put("unit_type", groupCreateJson.getInteger("unit_type")); //创意制作方式
                createJson.put("advertiser_id", oauthToken.getAccountId());
                createJson.put("campaign_id", campaign_id);
                createJson.put("unit_name", groupCreateJson.getString("unit_name")); // 组名称
                createJson.put("bid_type", groupCreateJson.getString("bid_type")); // 出价类型
                if (!Check.isNull(groupCreateJson.getInteger("use_app_market"))) {
                    createJson.put("use_app_market", groupCreateJson.getInteger("use_app_market")); // 优先从系统应用商店下载
                }
                if (!Check.isNull(groupCreateJson.getJSONArray("app_store"))) {
                    createJson.put("app_store", groupCreateJson.getJSONArray("app_store")); //应用商店列表
                }
                if (!Check.isNull(groupCreateJson.getLong("bid"))) {
                    createJson.put("bid", groupCreateJson.getLong("bid")); //出价
                }
                if (!Check.isNull(groupCreateJson.getLong("cpa_bid"))) {
                    createJson.put("cpa_bid", groupCreateJson.getLong("cpa_bid")); //出价
                }
                if (!Check.isNull(groupCreateJson.getInteger("smart_bid"))) {
                    createJson.put("smart_bid", groupCreateJson.getInteger("smart_bid")); //优先低成本
                }
                if (!Check.isNull(groupCreateJson.getInteger("ocpx_action_type"))) {
                    createJson.put("ocpx_action_type", groupCreateJson.getInteger("ocpx_action_type")); //优化目标
                }
                if (!Check.isNull(groupCreateJson.getInteger("deep_conversion_type"))) {
                    createJson.put("deep_conversion_type", groupCreateJson.getInteger("deep_conversion_type")); //深度转化目标
                }
                if (!Check.isNull(groupCreateJson.getDouble("roi_ratio"))) {
                    createJson.put("roi_ratio", groupCreateJson.getDouble("roi_ratio")); //付费ROI系数
                }
                if (!Check.isNull(groupCreateJson.getLong("deep_conversion_bid"))) {
                    createJson.put("deep_conversion_bid", groupCreateJson.getLong("deep_conversion_bid")); //深度转化目标出价
                }

                Integer sceneId = null;
                if (!Check.isNull(groupCreateJson.getJSONArray("scene_id"))) {
                    sceneId = groupCreateJson.getJSONArray("scene_id").getInteger(0);
                    createJson.put("scene_id", groupCreateJson.getJSONArray("scene_id")); //资源位置
                }

                if (!Check.isNull(groupCreateJson.getString("begin_time"))) {
                    createJson.put("begin_time", groupCreateJson.getString("begin_time")); //投放开始时间
                }
                if (!Check.isNull(groupCreateJson.getString("end_time"))) {
                    createJson.put("end_time", groupCreateJson.getString("end_time")); //投放结束时间
                }
                if (!Check.isNull(groupCreateJson.getString("schedule_time"))) {
                    createJson.put("schedule_time", groupCreateJson.getString("schedule_time")); //投放时间段
                }
                if (!Check.isNull(groupCreateJson.getLong("day_budget"))) {
                    createJson.put("day_budget", groupCreateJson.getLong("day_budget")); //投放时间段
                }
                if (!Check.isNull(groupCreateJson.getInteger("convert_id"))) {
                    createJson.put("convert_id", groupCreateJson.getInteger("convert_id")); //投放时间段
                }
                if (!Check.isNull(groupCreateJson.getInteger("url_type"))) {
                    createJson.put("url_type", groupCreateJson.getInteger("url_type")); //url类型
                }
                if (!Check.isNull(groupCreateJson.getInteger("web_uri_type"))) {
                    createJson.put("web_uri_type", groupCreateJson.getInteger("web_uri_type")); //url类型
                }
                if (!Check.isNull(groupCreateJson.getString("url"))) {
                    createJson.put("url", groupCreateJson.getString("url")); //url类型
                }
                if (!Check.isNull(groupCreateJson.getString("schema_uri"))) {
                    createJson.put("schema_uri", groupCreateJson.getString("schema_uri")); //调起链接
                }
                if (!Check.isNull(groupCreateJson.getLong("app_id"))) {
                    createJson.put("app_id", groupCreateJson.getLong("app_id")); //应用ID
                }
                if (!Check.isNull(groupCreateJson.getInteger("show_mode"))) {
                    createJson.put("show_mode", groupCreateJson.getInteger("show_mode")); //创意展现方式
                }
                if (!Check.isNull(groupCreateJson.getInteger("speed"))) {
                    createJson.put("speed", groupCreateJson.getInteger("speed")); //投放方式
                }
                if (!Check.isNull(groupCreateJson.getInteger("site_type"))) {
                    createJson.put("site_type", groupCreateJson.getInteger("site_type")); //预约广告
                }
                if (!Check.isNull(groupCreateJson.getInteger("target_action_type")) || !Check.isNull(groupCreateJson.getString("code"))) {
                    JSONObject gift_data = new JSONObject();
                    if (!Check.isNull(groupCreateJson.getInteger("target_action_type"))) {
                        gift_data.put("target_action_type", groupCreateJson.getInteger("target_action_type"));
                    }
                    if (!Check.isNull(groupCreateJson.getString("code"))) {
                        gift_data.put("code", groupCreateJson.getString("code"));
                    }
                    createJson.put("gift_data", gift_data); //游戏礼包码
                }
                if (!Check.isNull(groupCreateJson.getBoolean("video_landing_page"))) {
                    createJson.put("video_landing_page", groupCreateJson.getBoolean("video_landing_page")); //是否使用落地页前置功能
                }
                if (!Check.isNull(groupCreateJson.getBoolean("auto_target"))) {
                    createJson.put("auto_target", groupCreateJson.getBoolean("auto_target")); //智能定向
                }
                if (!Check.isNull(groupCreateJson.getBoolean("auto_create_photo"))) {
                    createJson.put("auto_create_photo", groupCreateJson.getBoolean("auto_create_photo")); //是否开启自动生成视频
                }
                if (!Check.isNull(groupCreateJson.getLong("item_id"))) {
                    createJson.put("item_id", groupCreateJson.getLong("item_id")); //电商关联Id (小店通)
                }
                if (!Check.isNull(groupCreateJson.getLong("merchant_item_put_type"))) {
                    createJson.put("merchant_item_put_type", groupCreateJson.getLong("merchant_item_put_type")); //电商广告投放类型（小店通）
                }
                if (!Check.isNull(groupCreateJson.getLong("fiction_id"))) {
                    createJson.put("fiction_id", groupCreateJson.getLong("fiction_id")); //小说ID
                }

                if (unit_type == 7) {
                    if (!Check.isNull(groupCreateJson.getBoolean("smart_cover"))) {
                        createJson.put("smart_cover", groupCreateJson.getBoolean("smart_cover")); //是否开启智能抽帧
                    }
                    if (!Check.isNull(groupCreateJson.getBoolean("asset_mining"))) {
                        createJson.put("asset_mining", groupCreateJson.getBoolean("asset_mining")); //程序化创意2.0素材挖掘
                    }
                }
                if (!Check.isNull(groupCreateJson.getLong("template_id"))) {
                    if (sceneId != 5) {
                        createJson.put("template_id", groupCreateJson.getLong("template_id")); //定向模板id
                    } else { // 联盟广告位 需要根据模板id 获取定向数据
                        JSONObject unionJson = groupTemplateService.getUnionJson(groupCreateJson.getLong("template_id"));
                        Integer code = unionJson.getInteger("code");
                        if (code == 0) {
                            JSONObject target = unionJson.getJSONObject("target");
                            createJson.put("target", target);
                        } else {
                            throw new Exception("联盟广告位定向模板错误");
                        }
                    }
                } else {
                    JSONObject target = getTarget(groupCreateJson, sceneId);
                    if (!Check.isNull(target)) {
                        createJson.put("target", target); // 定向数据
                    }
                }
                Map<String, Object> unitMap = iKuaishouInterfaceService.adUnitCreate(oauthToken.getAccessToken(), oauthToken.getAccountId(), createJson, 1);
                JSONObject returnJson = new JSONObject();
                returnJson.put("group_uuid", group_uuid);
                if ((Integer) unitMap.get("code") == 0) {
                    Long unitId = (Long) unitMap.get("unitId");
                    returnJson.put("unit_id", unitId);
                    returnJson.put("code", 0);
                    returnJson.put("message", "广告组创建成功");
                    KuaiShouGroup group = groupService.selectGroupByUnitId(oauthToken.getAccountId(), unitId);
                    if (!Check.isNull(group)) {
                        returnJson.put("group_create_time", group.getGroupCreateTime());
                    }
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            if (unit_type == 4) { //  自定义2.0创意
                                createCreative(oauthToken, unitId, groupCreateJson.getJSONArray("creative_list"));
                            } else if (unit_type == 7) { // 程序化创意
                                createProgramCreative(oauthToken, unitId, groupCreateJson.getJSONObject("programCreative"));
                            }
                        }
                    };
                    thread.start();
                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", unitMap.get("message"));

                }
                returnArr.add(returnJson);
            } catch (Exception e) {
                JSONObject returnJson = new JSONObject();
                returnJson.put("group_uuid", group_uuid);
                returnJson.put("code", -1);
                returnJson.put("message", e.getMessage());
                returnArr.add(returnJson);
            }
        }
        callback(unitUrl, returnArr, "unit");
    }


    /**
     * 创建自定义广告创意
     *
     * @param oauthToken
     * @param unit_id
     * @param creative_list
     */
    private void createCreative(CtopOauthToken oauthToken, Long unit_id, JSONArray creative_list) {
        JSONArray returnArr = new JSONArray();
        for (int i = 0; i < creative_list.size(); i++) {
            JSONObject creativeJson = creative_list.getJSONObject(i);
            if (Check.isNull(creativeJson)) {
                continue;
            }
            String creative_uuid = creativeJson.getString("creative_uuid");
            try {
                JSONObject createJson = new JSONObject();
                createJson.put("advertiser_id", oauthToken.getAccountId());
                createJson.put("unit_id", unit_id);
                createJson.put("creative_name", creativeJson.getString("creative_name")); // 创意名称
                if (!Check.isNull(creativeJson.getLong("photo_id"))) {
                    createJson.put("photo_id", creativeJson.getLong("photo_id"));  // 视频ID
                }
                //        KuaiShouVideoGet video = videoGetService.getVideoByPhotoId(creativeJson.getLong("photo_id"));
                if (!Check.isNull(creativeJson.getInteger("creative_material_type"))) {
                    createJson.put("creative_material_type", creativeJson.getInteger("creative_material_type"));  // 素材类型
                }
                if (!Check.isNull(creativeJson.getString("action_bar_text"))) {
                    createJson.put("action_bar_text", creativeJson.getString("action_bar_text"));  // 行动号召按钮文案
                }
                if (!Check.isNull(creativeJson.getString("description"))) {
                    createJson.put("description", creativeJson.getString("description"));  // 广告语
                }
                if (!Check.isNull(creativeJson.getString("sticker_title"))) {
                    createJson.put("sticker_title", creativeJson.getString("sticker_title"));  // 封面广告语标题
                }
                if (!Check.isNull(creativeJson.getString("overlay_type"))) {
                    createJson.put("overlay_type", creativeJson.getString("overlay_type"));  // 贴纸样式类型
                }
                if (!Check.isNull(creativeJson.getString("expose_tag"))) {
                    createJson.put("expose_tag", creativeJson.getString("expose_tag"));  // 广告标签
                }
                if (!Check.isNull(creativeJson.getJSONArray("new_expose_tag"))) {
                    createJson.put("new_expose_tag", creativeJson.getJSONArray("new_expose_tag"));  // 广告标签2期
                }
                if (!Check.isNull(creativeJson.getLong("site_id"))) {
                    createJson.put("site_id", creativeJson.getLong("site_id"));  // 安卓下载中间页ID
                }
                if (!Check.isNull(creativeJson.getString("click_track_url"))) {
                    createJson.put("click_track_url", creativeJson.getString("click_track_url"));  // 第三方点击检测链接
                }
                if (!Check.isNull(creativeJson.getString("impression_url"))) {
                    createJson.put("impression_url", creativeJson.getString("impression_url"));  // 第三方开始播放监测链接
                }
                if (!Check.isNull(creativeJson.getString("ad_photo_played_t3s_url"))) {
                    createJson.put("ad_photo_played_t3s_url", creativeJson.getString("ad_photo_played_t3s_url"));  // 第三方有效播放监测链接
                }
                if (!Check.isNull(creativeJson.getString("actionbar_click_url"))) {
                    createJson.put("actionbar_click_url", creativeJson.getString("actionbar_click_url"));  // 第三方点击按钮监测链接
                }
                if (!Check.isNull(creativeJson.getInteger("creative_category"))) {
                    createJson.put("creative_category", creativeJson.getInteger("creative_category"));  // 创意分类
                }
                if (!Check.isNull(creativeJson.getJSONArray("creative_tag"))) {
                    createJson.put("creative_tag", creativeJson.getJSONArray("creative_tag"));  // 创意标签
                }
                String image_md5 = creativeJson.getString("image_md5");
                String imageToken = null;
                if (!Check.isNull(image_md5)) {
                    imageToken = getImageToken(image_md5, oauthToken.getAccountId(), oauthToken.getAccessToken());
                }
                if (!Check.isNull(imageToken)) {
                    Integer is_sticky = creativeJson.getInteger("is_sticky"); // 是否便利贴
                    if (is_sticky != 1) {
                        createJson.put("image_token", imageToken); // 自定义创意封面token
                    } else {
                        JSONArray image_tokens = new JSONArray();
                        image_tokens.add(imageToken);
                        createJson.put("image_tokens", image_tokens); // 便利贴图片素材token
                        if (!Check.isNull(creativeJson.getString("short_slogan"))) {
                            createJson.put("short_slogan", creativeJson.getString("short_slogan"));  // 便利贴创意短广告语
                        }
                    }
                }
                Map<String, Object> creativeMap = iKuaishouInterfaceService.creativeCreate(oauthToken.getAccessToken(), oauthToken.getAccountId(), createJson, 1);
                JSONObject returnJson = new JSONObject();
                returnJson.put("creative_uuid", creative_uuid);
                returnJson.put("unit_id", unit_id);
                returnJson.put("type", 1);
                if ((Integer) creativeMap.get("code") == 0) {
                    Long creativeId = (Long) creativeMap.get("creativeId");
                    returnJson.put("creative_id", creativeId);
                    returnJson.put("code", 0);
                    returnJson.put("message", "广告创意创建成功");
                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", creativeMap.get("message"));
                }
                returnArr.add(returnJson);
            } catch (Exception e) {
                e.printStackTrace();
                JSONObject returnJson = new JSONObject();
                returnJson.put("creative_uuid", creative_uuid);
                returnJson.put("message", e.getMessage());
                returnJson.put("code", -1);
                returnJson.put("unit_id", unit_id);
                returnJson.put("type", 1);
                returnArr.add(returnJson);
            }
        }
        callback(creativeUrl, returnArr, "creative");

    }


    /**
     * 创建程序化创意
     *
     * @param oauthToken
     * @param unit_id
     * @param programCreativeJson
     */
    private void createProgramCreative(CtopOauthToken oauthToken, Long unit_id, JSONObject programCreativeJson) {
        JSONArray returnArray = new JSONArray();
        String creative_uuid = programCreativeJson.getString("creative_uuid");
        try {
            JSONObject programJson = new JSONObject();
            programJson.put("advertiser_id", oauthToken.getAccountId());
            programJson.put("unit_id", unit_id);
            if (!Check.isNull(programCreativeJson.getString("package_name"))) {
                programJson.put("package_name", programCreativeJson.getString("package_name"));
            }
            if (!Check.isNull(programCreativeJson.getJSONArray("horizontal_photo_ids"))) {
                programJson.put("horizontal_photo_ids", programCreativeJson.getJSONArray("horizontal_photo_ids"));
            }
            if (!Check.isNull(programCreativeJson.getJSONArray("vertical_photo_ids"))) {
                programJson.put("vertical_photo_ids", programCreativeJson.getJSONArray("vertical_photo_ids"));
            }
            JSONArray cover_image_tokens = new JSONArray();
            JSONArray image_md5s = programCreativeJson.getJSONArray("image_md5s");
            if (!Check.isNull(image_md5s)) {
                for (int i = 0; i < image_md5s.size(); i++) {
                    String image_md5 = (String) image_md5s.get(i);
                    if (!Check.isNull(image_md5)) {
                        String imageToken = getImageToken(image_md5, oauthToken.getAccountId(), oauthToken.getAccessToken());
                        if (!Check.isNull(imageToken)) {
                            cover_image_tokens.add(imageToken);
                        }
                    }
                }
                programJson.put("cover_image_tokens", cover_image_tokens);
            } else {
                programJson.put("cover_image_tokens", new JSONArray());
            }
            if (!Check.isNull(programCreativeJson.getLong("site_id"))) {
                programJson.put("site_id", programCreativeJson.getLong("site_id"));
            }
            if (!Check.isNull(programCreativeJson.getJSONArray("sticker_styles"))) {
                programJson.put("sticker_styles", programCreativeJson.getJSONArray("sticker_styles"));
            }
            if (!Check.isNull(programCreativeJson.getJSONArray("cover_slogans"))) {
                programJson.put("cover_slogans", programCreativeJson.getJSONArray("cover_slogans"));
            }
            if (!Check.isNull(programCreativeJson.getString("action_bar"))) {
                programJson.put("action_bar", programCreativeJson.getString("action_bar"));
            }
            if (!Check.isNull(programCreativeJson.getJSONArray("captions"))) {
                programJson.put("captions", programCreativeJson.getJSONArray("captions"));
            }
            if (!Check.isNull(programCreativeJson.getString("click_url"))) {
                programJson.put("click_url", programCreativeJson.getString("click_url"));
            }
            if (!Check.isNull(programCreativeJson.getString("actionbar_click_url"))) {
                programJson.put("actionbar_click_url", programCreativeJson.getString("actionbar_click_url"));
            }
            if (!Check.isNull(programCreativeJson.getInteger("creative_category"))) {
                programJson.put("creative_category", programCreativeJson.getInteger("creative_category"));
            }
            if (!Check.isNull(programCreativeJson.getJSONArray("creative_tag"))) {
                programJson.put("creative_tag", programCreativeJson.getJSONArray("creative_tag"));
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", oauthToken.getAccessToken());
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PROGRAM_CREATE;
            String result = HttpUtils.kuaiShouhttpPostRequest(url, programJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("创建程序化创意返回结果：{}", resultJson);
            JSONObject returnJson = new JSONObject();
            returnJson.put("creative_uuid", creative_uuid);
            returnJson.put("unit_id", unit_id);
            returnJson.put("type", 2);
            if (!Check.isNull(resultJson)) {
                if (resultJson.getInteger("code") == 0) {
                    returnJson.put("code", 0);
                    returnJson.put("message", "程序化创意创建成功");
                    createLandPageAndUnit(programJson, resultJson.getJSONObject("data"));
                } else {
                    log.error("创建程序化创意失败，accountId：{}，返回结果：{}，入参：{}", oauthToken.getAccountId(), resultJson.getString("message"), programCreativeJson);
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                }
            }
            returnArray.add(returnJson);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject returnJson = new JSONObject();
            returnJson.put("creative_uuid", creative_uuid);
            returnJson.put("message", e.getMessage());
            returnJson.put("code", -1);
            returnJson.put("unit_id", unit_id);
            returnJson.put("type", 2);
            returnArray.add(returnJson);
        }
        callback(creativeUrl, returnArray, "program_create");
    }

    //绑定落地页与广告组、创意的关系
    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();
        }
    }

    /**
     * 回调
     *
     * @param url
     * @param requestArr
     * @param type
     */
    private void callback(String url, JSONArray requestArr, String type) {
        JSONObject requestJson = new JSONObject();
        requestJson.put("callbackData", requestArr);
        String s = HttpUtils2.httpPostRequest(url, requestJson, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (!Check.isNull(jsonObject)) {
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                log.info("{}，回调成功", type);
            } else {
                log.info("{}，回调失败，入参：{}", type, requestJson);
            }
        } else {
            log.info("{}，回调返回结果为空，入参：{}", type, requestJson);
        }
    }

    /**
     * 根据封面MD5 获取imageToken
     *
     * @param md5
     * @param accountId
     * @param accessToken
     * @return
     */
    private String getImageToken(String md5, Long accountId, String accessToken) {
        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 {
            MaterialCutFrame cutFrame = cutFrameService.selectByMd5(md5);
            if (!Check.isNull(cutFrame)) {
                imageToken = uploadService.kuauiShouImageUpload(cutFrame.getUrl(), md5, accountId, accessToken);
            }
        }
        return imageToken;
    }

    /**
     * 获取定向包
     *
     * @param unitJson
     * @return
     */
    private JSONObject getTarget(JSONObject unitJson, Integer sceneId) {
        JSONObject target = new JSONObject();
        if (!Check.isNull(unitJson.getJSONArray("region"))) {
            target.put("region", unitJson.getJSONArray("region")); // 地域
        }
        if (!Check.isNull(unitJson.getJSONArray("district_ids"))) {
            target.put("district_ids", unitJson.getJSONArray("district_ids")); // 商圈定向
        }
        if (!Check.isNull(unitJson.getInteger("user_type"))) {
            target.put("user_type", unitJson.getInteger("user_type")); // 用户类型
        }
        if (!Check.isNull(unitJson.getInteger("age_min")) || !Check.isNull(unitJson.getInteger("age_max"))) {
            JSONObject age = new JSONObject();
            age.put("min", unitJson.getInteger("age_min"));
            age.put("max", unitJson.getInteger("age_max"));
            target.put("age", age); //自定义年龄段
        }
        if (!Check.isNull(unitJson.getJSONArray("ages_range"))) {
            target.put("ages_range", unitJson.getJSONArray("ages_range")); // 固定年龄段
        }
        if (!Check.isNull(unitJson.getInteger("gender"))) {
            target.put("gender", unitJson.getInteger("gender")); // 性别
        }
        if (!Check.isNull(unitJson.getInteger("platform_os"))) {
            target.put("platform_os", unitJson.getInteger("platform_os")); // 操作系统
        }
        if (!Check.isNull(unitJson.getInteger("android_osv"))) {
            target.put("android_osv", unitJson.getInteger("android_osv")); // Android版本
        }
        if (!Check.isNull(unitJson.getInteger("ios_osv"))) {
            target.put("ios_osv", unitJson.getInteger("ios_osv")); // Android版本
        }
        if (!Check.isNull(unitJson.getInteger("network"))) {
            target.put("network", unitJson.getInteger("network")); // 网络环境
        }
        if (!Check.isNull(unitJson.getJSONArray("device_brand"))) {
            target.put("device_brand", unitJson.getJSONArray("device_brand")); // 设备品牌
        }
        if (!Check.isNull(unitJson.getJSONArray("device_price"))) {
            target.put("device_price", unitJson.getJSONArray("device_price")); // 设备价格
        }
        if (sceneId != 5) {
            if (!Check.isNull(unitJson.getInteger("business_interest_type"))) {
                target.put("business_interest_type", unitJson.getInteger("business_interest_type")); // 商业兴趣类型
            }
            if (!Check.isNull(unitJson.getJSONArray("business_interest"))) {
                target.put("business_interest", unitJson.getJSONArray("business_interest")); // 商业兴趣
            }
            if (!Check.isNull(unitJson.getJSONArray("fans_star"))) {
                target.put("fans_star", unitJson.getJSONArray("fans_star")); // 网红粉丝
            }
            if (!Check.isNull(unitJson.getJSONArray("interest_video"))) {
                target.put("interest_video", unitJson.getJSONArray("interest_video")); // 兴趣视频用户
            }
        }
        if (!Check.isNull(unitJson.getJSONArray("app_interest"))) {
            target.put("app_interest", unitJson.getJSONArray("app_interest")); // APP行为-按分类
        }
        if (!Check.isNull(unitJson.getJSONArray("app_ids"))) {
            target.put("app_ids", unitJson.getJSONArray("app_ids")); // APP行为-按APP名称
        }
        if (sceneId != 5) {
            if (!Check.isNull(unitJson.getInteger("filter_converted_level"))) {
                target.put("filter_converted_level", unitJson.getInteger("filter_converted_level")); // APP行为-按APP名称
            }
        }
        if (!Check.isNull(unitJson.getJSONArray("population"))) {
            target.put("population", unitJson.getJSONArray("population")); // 人群包定向
        }
        if (!Check.isNull(unitJson.getJSONArray("exclude_population"))) {
            target.put("exclude_population", unitJson.getJSONArray("exclude_population")); // 人群包排除
        }
        if (!Check.isNull(unitJson.getJSONArray("paid_audience"))) {
            target.put("paid_audience", unitJson.getJSONArray("paid_audience")); // 付费人群包id
        }
        if (sceneId != 5) {
            if (!Check.isNull(unitJson.getInteger("is_open")) && unitJson.getInteger("is_open") == 1) {
                JSONObject intelli_extend = new JSONObject();
                intelli_extend.put("is_open", unitJson.getInteger("is_open")); // 开启智能扩量
                if (!Check.isNull(unitJson.getInteger("no_age_break"))) {
                    intelli_extend.put("no_age_break", unitJson.getInteger("no_age_break")); //  不可突破年龄
                }
                if (!Check.isNull(unitJson.getInteger("no_gender_break"))) {
                    intelli_extend.put("no_gender_break", unitJson.getInteger("no_gender_break")); //  不可突破性别
                }
                if (!Check.isNull(unitJson.getInteger("no_area_break"))) {
                    intelli_extend.put("no_area_break", unitJson.getInteger("no_area_break")); //  不可突破地域
                }
                target.put("intelli_extend", intelli_extend); // 智能扩量
            }
        }
        //-------------兴趣行为定向
        JSONObject behaviorInterest = new JSONObject();
        JSONObject behavior = new JSONObject();
        JSONObject interest = new JSONObject();
        if (!Check.isNull(unitJson.getJSONArray("keyword"))) {
            behavior.put("keyword", unitJson.getJSONArray("keyword"));
        }
        if (!Check.isNull(unitJson.getJSONArray("label"))) {
            behavior.put("label", unitJson.getJSONArray("label"));
        }
        if (!Check.isNull(unitJson.getInteger("strengthType"))) {
            behavior.put("strength_type", unitJson.getInteger("strengthType"));
        }
        if (!Check.isNull(unitJson.getInteger("timeType"))) {
            behavior.put("time_type", unitJson.getInteger("timeType"));
        }
        if (!Check.isNull(unitJson.getJSONArray("sceneType"))) {
            behavior.put("scene_type", unitJson.getJSONArray("sceneType"));
        }
        if (!Check.isNull(unitJson.getJSONArray("interestLabel"))) {
            interest.put("label", unitJson.getJSONArray("interestLabel"));
        }
        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);
        }
        return target;
    }
}
