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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.kuaishou.modules.batch.entity.*;
import cn.com.ctop.kuaishou.modules.batch.mapper.*;
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.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.valueOf;

@Slf4j
@Service
public class BatchServiceImpl implements IBatchService {

    @Value("${oss.replace.download}")
    private String downloadUrl;

    @Autowired
    private BatchMapper batchMapper;
    @Autowired
    private KuaiShouCampaignMapper campaignMapper;
    @Autowired
    private UserAllocationMapper userAllocationMapper;
    @Autowired
    private IKuaiShouUpdateService updateService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private KuaiShouCreativeMapper creativeMapper;
    @Autowired
    private KuaiShouGroupMapper kuaiShouGroupMapper;
    @Autowired
    private KuaiShouGroupTargetMapper targetMapper;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;


    /**
     * 获取总花费
     *
     * @param accountId
     * @return
     */
    @Override
    public BigDecimal getCost(Long accountId) {
        BigDecimal dailyCost = batchMapper.getDailyCost(accountId);
        BigDecimal hourlyCost = batchMapper.getHourCost(accountId, DateUtils.formatDate(new Date()));
        BigDecimal totalCost = dailyCost.add(hourlyCost);
        return totalCost;
    }

    /**
     * 获取总计划预算
     *
     * @param accountId
     * @return
     */
    @Override
    public BigDecimal getBudget(Long accountId) {
        return batchMapper.getBudget(accountId);
    }


    /**
     * 获取计划信息
     *
     * @param accountId
     * @param campaignId
     * @return
     */
    @Override
    public KuaiShouCampaign getCampaignInfo(Long accountId, Long campaignId) {
        QueryWrapper<KuaiShouCampaign> campaignQueryWrapper = new QueryWrapper<>();
        campaignQueryWrapper.eq("account_id", accountId);
        campaignQueryWrapper.eq("campaign_id", campaignId);
        campaignQueryWrapper.orderByDesc("create_time");
        campaignQueryWrapper.last("limit 1");
        KuaiShouCampaign campaign = campaignMapper.selectOne(campaignQueryWrapper);
        return campaign;
    }

    /**
     * 获取项目最高出价
     *
     * @param accountId
     * @return
     */

    @Override
    public BigDecimal getProjectMaxBid(Long accountId) {
        QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
        userAllocationQueryWrapper.eq("account_id", accountId);
        userAllocationQueryWrapper.eq("media_id", "2");
        userAllocationQueryWrapper.orderByDesc("create_time");
        userAllocationQueryWrapper.last("limit 1");
        UserAllocation userAllocation = userAllocationMapper.selectOne(userAllocationQueryWrapper);
        if (!Check.isNull(userAllocation)) {
            return batchMapper.getProjectMaxBidByProject(userAllocation.getProjectId());
        }
        return new BigDecimal(0);
    }


    /**
     * 校验广告组名称是否重复
     *
     * @param campaignId
     * @param unitName
     * @return
     */


    @Override
    public Boolean checkUnitName(Long campaignId, String unitName) {
        QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("campaign_id", campaignId);
        groupQueryWrapper.eq("unit_name", unitName);
        groupQueryWrapper.orderByDesc("create_time");
        groupQueryWrapper.last("limit 1");
        KuaiShouGroup kuaiShouGroup = kuaiShouGroupMapper.selectOne(groupQueryWrapper);
        if (!Check.isNull(kuaiShouGroup)) {
            return false;
        }
        return true;
    }


    /**
     * 批量创建广告组
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject createUnit(JSONObject requestJson, CtopOauthToken oauthToken) throws Exception {
        JSONObject unitJson = new JSONObject();
        Long campaignId = requestJson.getLong("campaignId");
        if (Check.isNull(campaignId)) {
            throw new Exception("请选择广告计划");
        }

        String type = requestJson.getString("type");
        if ("copy".equals(type) && !Check.isNull(type)) {
            unitJson.put("campaign_id", requestJson.getLong("copyToCampaignId"));
        } else {
            unitJson.put("campaign_id", campaignId);
        }


        // 资源位置
        JSONArray scene_id = requestJson.getJSONArray("sceneId");
        if (!Check.isNull(scene_id)) {
            unitJson.put("scene_id", scene_id);
        }
        Integer sceneId = valueOf(scene_id.get(0).toString());
        // 资源创作方式
        Integer unitType = requestJson.getInteger("unitType");
        if (!Check.isNull(unitType)) {
            unitJson.put("unit_type", unitType);
        }

        // 转化目标id
        if (!Check.isNull(requestJson.getInteger("convertId"))) {
            unitJson.put("convert_id", requestJson.getInteger("convertId"));
        }

        // 优先从系统应用商店下载
        if (!Check.isNull(requestJson.getInteger("useAppMarket"))) {
            unitJson.put("use_app_market", requestJson.getInteger("useAppMarket"));
        }

        // 应用商店列表
        if (!Check.isNull(requestJson.getJSONArray("appStore"))) {
            unitJson.put("app_store", requestJson.getJSONArray("appStore"));
        }

        //投放开始时间
        if (!Check.isNull(requestJson.getString("beginTime"))) {
            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
            boolean beginTimeBoolean = DateUtils.compare(requestJson.getString("beginTime"), nowDate);
            if (beginTimeBoolean) {
                unitJson.put("begin_time", nowDate);
            } else {
                unitJson.put("begin_time", requestJson.getString("beginTime"));
            }
        }
        // 投放结束时间
        if (!Check.isNull(requestJson.getString("endTime"))) {
            unitJson.put("end_time", requestJson.getString("endTime"));
        }
        // 投放时间段
        if (!Check.isNull(requestJson.getString("scheduleTime"))) {
            unitJson.put("schedule_time", requestJson.getString("scheduleTime"));
        }
        // 广告组单日预算
        if (!Check.isNull(requestJson.getLong("dayBudget"))) {
            unitJson.put("day_budget", requestJson.getLong("dayBudget"));
        }
        // url类型
        if (!Check.isNull(requestJson.getInteger("urlType"))) {
            unitJson.put("url_type", requestJson.getInteger("urlType"));
        }
        // url
        if (!Check.isNull(requestJson.getString("url"))) {
            unitJson.put("url", requestJson.getString("url"));
        }
        // appId
        if (!Check.isNull(requestJson.getLong("appId"))) {
            unitJson.put("app_id", requestJson.getLong("appId"));
        }
        // 创意展现方式
        if (!Check.isNull(requestJson.getInteger("showMode"))) {
            unitJson.put("show_mode", requestJson.getInteger("showMode"));
        }
        if (!Check.isNull(requestJson.getInteger("speed"))) {
            unitJson.put("speed", requestJson.getInteger("speed"));
        }


        // -----------------用户定向-----------
        JSONObject targetJson = new JSONObject();

        // 地域
        if (!Check.isNull(requestJson.getJSONArray("region"))) {
            targetJson.put("region", requestJson.getJSONArray("region"));
        }

        // 自定义年龄段
        JSONArray ageArr = requestJson.getJSONArray("age");
        if (!Check.isNull(ageArr)) {
            JSONObject ageJson = new JSONObject();
            ageJson.put("min", ageArr.get(0));
            ageJson.put("max", ageArr.get(1));
            targetJson.put("age", ageJson);
        }
        // 固定年龄段
        if (!Check.isNull(requestJson.getJSONArray("agesRange"))) {
            targetJson.put("ages_range", requestJson.getJSONArray("agesRange"));
        }
        // 性别
        if (!Check.isNull(requestJson.getInteger("gender"))) {
            targetJson.put("gender", requestJson.getInteger("gender"));
        }
        //操作系统
        if (!Check.isNull(requestJson.getInteger("platformOs"))) {
            targetJson.put("platform_os", requestJson.getInteger("platformOs"));
        }
        //Android版本
        if (!Check.isNull(requestJson.getInteger("androidOsv"))) {
            targetJson.put("android_osv", requestJson.getInteger("androidOsv"));
        }
        // iOS版本
        if (!Check.isNull(requestJson.getInteger("iosOsv"))) {
            targetJson.put("ios_osv", requestJson.getInteger("iosOsv"));
        }
        //网络环境
        if (!Check.isNull(requestJson.getInteger("network"))) {
            targetJson.put("network", requestJson.getInteger("network"));
        }
        //设备品牌
        if (!Check.isNull(requestJson.getJSONArray("deviceBrand"))) {
            targetJson.put("device_brand", requestJson.getJSONArray("deviceBrand"));
        }
        //设备价格
        if (!Check.isNull(requestJson.getJSONArray("devicePrice"))) {
            targetJson.put("device_price", requestJson.getJSONArray("devicePrice"));
        }

        if (sceneId != 5) {
            //过滤已转化人群纬度
            if (!Check.isNull(requestJson.getInteger("filterConvertedLevel"))) {
                targetJson.put("filter_converted_level", requestJson.getInteger("filterConvertedLevel"));
            }
            //商业兴趣类型
            if (!Check.isNull(requestJson.getInteger("businessInterestType"))) {
                targetJson.put("business_interest_type", requestJson.getInteger("businessInterestType"));
            }
            // 商业兴趣
            if (!Check.isNull(requestJson.getJSONArray("businessInterest"))) {
                targetJson.put("business_interest", requestJson.getJSONArray("businessInterest"));
            }
            //网红粉丝
            if (!Check.isNull(requestJson.getJSONArray("fansStar"))) {
                targetJson.put("fans_star", requestJson.getJSONArray("fansStar"));
            }
            //兴趣视频用户
            if (!Check.isNull(requestJson.getJSONArray("interestVideo"))) {
                targetJson.put("interest_video", requestJson.getJSONArray("interestVideo"));
            }
        }
        // APP行为-按分类
        if (!Check.isNull(requestJson.getJSONArray("appInterest"))) {
            targetJson.put("app_interest", requestJson.getJSONArray("appInterest"));
        }
        // APP行为-按APP名称
        if (!Check.isNull(requestJson.getJSONArray("appIds"))) {
            targetJson.put("app_ids", requestJson.getJSONArray("appIds"));
        }
        // 人群包定向
        if (!Check.isNull(requestJson.getJSONArray("population"))) {
            targetJson.put("population", requestJson.getJSONArray("population"));
        }
        // 人群包排除
        if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
            targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
        }


        if (!Check.isNull(requestJson.getJSONArray("thirdPlatformCode"))) {
            targetJson.put("third_platform_code", requestJson.getJSONArray("thirdPlatformCode"));
        }

        if (sceneId != 5) {
            JSONObject intelliExtendJson = new JSONObject();

            // 开启智能扩量
            if (!Check.isNull(requestJson.getInteger("isOpen"))) {
                intelliExtendJson.put("is_open", requestJson.getInteger("isOpen"));
            }
            //不可突破年龄
            if (!Check.isNull(requestJson.getInteger("noAgeBreak"))) {
                intelliExtendJson.put("no_age_break", requestJson.getInteger("noAgeBreak"));
            }
            //不可突破性别
            if (!Check.isNull(requestJson.getInteger("noGenderBreak"))) {
                intelliExtendJson.put("no_gender_break", requestJson.getInteger("noGenderBreak"));
            }
            // 不可突破地域
            if (!Check.isNull(requestJson.getInteger("noAreaBreak"))) {
                intelliExtendJson.put("no_area_break", requestJson.getInteger("noAreaBreak"));
            }
            if (!Check.isNull(intelliExtendJson)) {
                targetJson.put("intelli_extend", intelliExtendJson);
            }
        }

        unitJson.put("target", targetJson);
        JSONArray groupArr = requestJson.getJSONArray("groupArr");
        if (Check.isNull(groupArr)) {
            throw new Exception("请输入需要创建的广告组");
        }


        JSONObject returnJson = new JSONObject();
        // 创建条数
        returnJson.put("total", groupArr.size());
        JSONArray successArr = new JSONArray();
        JSONArray failArr = new JSONArray();


        for (int i = 0; i < groupArr.size(); i++) {
            JSONObject groupJson = groupArr.getJSONObject(i);
            if (!Check.isNull(groupJson)) {

                // 出价
                if (!Check.isNull(groupJson.getLong("bid"))) {
                    unitJson.put("bid", groupJson.getLong("bid"));
                }
                // 出价类型
                Integer bidType = groupJson.getInteger("bidType");
                if (!Check.isNull(bidType)) {
                    unitJson.put("bid_type", bidType);
                }
                // 深度转化出价
                if (!Check.isNull(groupJson.getLong("cpaBid"))) {
                    unitJson.put("cpa_bid", groupJson.getLong("cpaBid"));
                }
                // 深度转化目标出价
                if (!Check.isNull(groupJson.getLong("deepConversionBid"))) {
                    unitJson.put("deep_conversion_bid", groupJson.getLong("deepConversionBid"));
                }
                // 深度转化目标
                if (!Check.isNull(groupJson.getInteger("deepConversionType"))) {
                    unitJson.put("deep_conversion_type", groupJson.getInteger("deepConversionType"));
                }
                // 优化目标
                Integer ocpx_action_type = groupJson.getInteger("ocpxActionType");
                if (!Check.isNull(ocpx_action_type)) {
                    unitJson.put("ocpx_action_type", ocpx_action_type);
                }
                String unitName = groupJson.getString("unitName");
                if (!Check.isNull(unitName)) {
                    unitJson.put("unit_name", unitName);
                }

                Map<String, Object> returnUnitMap = kuaishouInterfaceService.adUnitCreate(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitJson, 1);
                if (!Check.isNullMap(returnUnitMap)) {
                    Integer code = (Integer) returnUnitMap.get("code");
                    if (code == 0) {
                        JSONObject successJson = new JSONObject();
                        Long unitId = (Long) returnUnitMap.get("unitId");
                        successJson.put("unitId", unitId);
                        successJson.put("unitName", unitName);
                        successJson.put("sceneId", scene_id);
                        successJson.put("ocpxActionType", ocpx_action_type);
                        successJson.put("unitType", unitType);
                        successArr.add(successJson);

                        if (!Check.isNull(type) && "copy".equals(type)) {
                            Long copyUnitId = requestJson.getLong("copyUnitId");
                            if (!Check.isNull(unitId) && !Check.isNull(copyUnitId)) {
                                Thread thread = new Thread() {
                                    @Override
                                    public void run() {
                                        try {
                                            JSONObject otherJson = requestJson.getJSONObject("otherJson"); // 是否修改应用
                                            copyCreative(oauthToken.getAccountId(), unitId, copyUnitId, otherJson);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                                thread.start();
                            }
                        }
                    } else {
                        JSONObject failJson = new JSONObject();
                        failJson.put("unitName", unitName);
                        failJson.put("failMessage", returnUnitMap.get("message"));
                        failArr.add(failJson);
                    }

                }

            }

        }

        returnJson.put("success", successArr);
        returnJson.put("fail", failArr);
        return returnJson;
    }


    /**
     * 批量创建广告组
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject copyUpdateUnit(JSONObject requestJson, CtopOauthToken oauthToken) {

        JSONObject returnJson = new JSONObject();

        try {
            JSONObject unitJson = new JSONObject();
            Long campaignId = requestJson.getLong("campaignId");
            if (Check.isNull(campaignId)) {
                throw new Exception("请选择广告计划");
            }

            String type = requestJson.getString("type");
            if ("copy".equals(type) && !Check.isNull(type)) {
                unitJson.put("campaign_id", requestJson.getLong("copyToCampaignId"));
            } else {
                unitJson.put("campaign_id", campaignId);
            }
            // 资源位置
            JSONArray scene_id = requestJson.getJSONArray("sceneId");
            if (!Check.isNull(scene_id)) {
                unitJson.put("scene_id", scene_id);
            }
            Integer sceneId = valueOf(scene_id.get(0).toString());

            // 资源创作方式
            if (!Check.isNull(requestJson.getInteger("unitType"))) {
                unitJson.put("unit_type", requestJson.getInteger("unitType"));
            }

            // 转化目标id
            if (!Check.isNull(requestJson.getInteger("convertId"))) {
                unitJson.put("convert_id", requestJson.getInteger("convertId"));
            }

            // 优先从系统应用商店下载
            if (!Check.isNull(requestJson.getInteger("useAppMarket"))) {
                unitJson.put("use_app_market", requestJson.getInteger("useAppMarket"));
            }

            // 应用商店列表
            if (!Check.isNull(requestJson.getJSONArray("appStore"))) {
                unitJson.put("app_store", requestJson.getJSONArray("appStore"));
            }

            //投放开始时间
            if (!Check.isNull(requestJson.getString("beginTime"))) {
                String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                boolean beginTimeBoolean = DateUtils.compare(requestJson.getString("beginTime"), nowDate);
                if (beginTimeBoolean) {
                    unitJson.put("begin_time", nowDate);
                } else {
                    unitJson.put("begin_time", requestJson.getString("beginTime"));
                }
            }
            // 投放结束时间
            if (!Check.isNull(requestJson.getString("endTime"))) {
                unitJson.put("end_time", requestJson.getString("endTime"));
            }
            // 投放时间段
            if (!Check.isNull(requestJson.getString("scheduleTime"))) {
                unitJson.put("schedule_time", requestJson.getString("scheduleTime"));
            }
            // 广告组单日预算
            if (!Check.isNull(requestJson.getLong("dayBudget"))) {
                unitJson.put("day_budget", requestJson.getLong("dayBudget"));
            }
            // url类型
            if (!Check.isNull(requestJson.getInteger("urlType"))) {
                unitJson.put("url_type", requestJson.getInteger("urlType"));
            }
            // url
            if (!Check.isNull(requestJson.getString("url"))) {
                unitJson.put("url", requestJson.getString("url"));
            }
            // appId
            if (!Check.isNull(requestJson.getLong("appId"))) {
                unitJson.put("app_id", requestJson.getLong("appId"));
            }
            // 创意展现方式
            if (!Check.isNull(requestJson.getInteger("showMode"))) {
                unitJson.put("show_mode", requestJson.getInteger("showMode"));
            }
            if (!Check.isNull(requestJson.getInteger("speed"))) {
                unitJson.put("speed", requestJson.getInteger("speed"));
            }


            // -----------------用户定向-----------
            JSONObject targetJson = new JSONObject();

            // 地域
            if (!Check.isNull(requestJson.getJSONArray("region"))) {
                targetJson.put("region", requestJson.getJSONArray("region"));
            }

            // 自定义年龄段
            JSONArray ageArr = requestJson.getJSONArray("age");
            if (!Check.isNull(ageArr)) {
                JSONObject ageJson = new JSONObject();
                ageJson.put("min", ageArr.get(0));
                ageJson.put("max", ageArr.get(1));
                targetJson.put("age", ageJson);
            }
            // 固定年龄段
            if (!Check.isNull(requestJson.getJSONArray("agesRange"))) {
                targetJson.put("ages_range", requestJson.getJSONArray("agesRange"));
            }
            // 性别
            if (!Check.isNull(requestJson.getInteger("gender"))) {
                targetJson.put("gender", requestJson.getInteger("gender"));
            }
            //操作系统
            if (!Check.isNull(requestJson.getInteger("platformOs"))) {
                targetJson.put("platform_os", requestJson.getInteger("platformOs"));
            }
            //Android版本
            if (!Check.isNull(requestJson.getInteger("androidOsv"))) {
                targetJson.put("android_osv", requestJson.getInteger("androidOsv"));
            }
            // iOS版本
            if (!Check.isNull(requestJson.getInteger("iosOsv"))) {
                targetJson.put("ios_osv", requestJson.getInteger("iosOsv"));
            }
            //网络环境
            if (!Check.isNull(requestJson.getInteger("network"))) {
                targetJson.put("network", requestJson.getInteger("network"));
            }

            //设备品牌
            if (!Check.isNull(requestJson.getJSONArray("deviceBrand"))) {
                targetJson.put("device_brand", requestJson.getJSONArray("deviceBrand"));
            }

            //设备价格
            if (!Check.isNull(requestJson.getJSONArray("devicePrice"))) {
                targetJson.put("device_price", requestJson.getJSONArray("devicePrice"));
            }
            if (sceneId != 5) {
                if (!Check.isNull(requestJson.getInteger("filterConvertedLevel"))) {
                    targetJson.put("filter_converted_level", requestJson.getInteger("filterConvertedLevel"));
                }
                //商业兴趣类型
                if (!Check.isNull(requestJson.getInteger("businessInterestType"))) {
                    targetJson.put("business_interest_type", requestJson.getInteger("businessInterestType"));
                }
                // 商业兴趣
                if (!Check.isNull(requestJson.getJSONArray("businessInterest"))) {
                    targetJson.put("business_interest", requestJson.getJSONArray("businessInterest"));
                }
                //网红粉丝
                if (!Check.isNull(requestJson.getJSONArray("fansStar"))) {
                    targetJson.put("fans_star", requestJson.getJSONArray("fansStar"));
                }
                //兴趣视频用户
                if (!Check.isNull(requestJson.getJSONArray("interestVideo"))) {
                    targetJson.put("interest_video", requestJson.getJSONArray("interestVideo"));
                }
            }
            // APP行为-按分类
            if (!Check.isNull(requestJson.getJSONArray("appInterest"))) {
                targetJson.put("app_interest", requestJson.getJSONArray("appInterest"));
            }
            // APP行为-按APP名称
            if (!Check.isNull(requestJson.getJSONArray("appIds"))) {
                targetJson.put("app_ids", requestJson.getJSONArray("appIds"));
            }
            // 人群包定向
            if (!Check.isNull(requestJson.getJSONArray("population"))) {
                targetJson.put("population", requestJson.getJSONArray("population"));
            }
            // 人群包排除
            if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
                targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
            }

            if (!Check.isNull(requestJson.getJSONArray("thirdPlatformCode"))) {
                targetJson.put("third_platform_code", requestJson.getJSONArray("thirdPlatformCode"));
            }
            JSONObject intelliExtendJson = new JSONObject();
            if (sceneId != 5) {
                // 开启智能扩量
                if (!Check.isNull(requestJson.getInteger("isOpen"))) {
                    intelliExtendJson.put("is_open", requestJson.getInteger("isOpen"));
                }
                //不可突破年龄
                if (!Check.isNull(requestJson.getInteger("noAgeBreak"))) {
                    intelliExtendJson.put("no_age_break", requestJson.getInteger("noAgeBreak"));
                }
                //不可突破性别
                if (!Check.isNull(requestJson.getInteger("noGenderBreak"))) {
                    intelliExtendJson.put("no_gender_break", requestJson.getInteger("noGenderBreak"));
                }
                // 不可突破地域
                if (!Check.isNull(requestJson.getInteger("noAreaBreak"))) {
                    intelliExtendJson.put("no_area_break", requestJson.getInteger("noAreaBreak"));
                }
                if (!Check.isNull(intelliExtendJson)) {
                    targetJson.put("intelli_extend", intelliExtendJson);
                }
            }
            unitJson.put("target", targetJson);
            JSONObject groupJson = requestJson.getJSONObject("groupArr");
            if (Check.isNull(groupJson)) {
                throw new Exception("请输入需要创建的广告组");
            }

            // 是否修改应用
            JSONObject otherJson = requestJson.getJSONObject("otherJson");

            if (!Check.isNull(groupJson)) {

                // 出价
                if (!Check.isNull(groupJson.getLong("bid"))) {
                    unitJson.put("bid", groupJson.getLong("bid"));
                }
                // 出价类型
                Integer bidType = groupJson.getInteger("bidType");
                if (!Check.isNull(bidType)) {
                    unitJson.put("bid_type", bidType);
                }
                // 深度转化出价
                if (!Check.isNull(groupJson.getLong("cpaBid"))) {
                    unitJson.put("cpa_bid", groupJson.getLong("cpaBid"));
                }
                // 深度转化目标出价
                if (!Check.isNull(groupJson.getLong("deepConversionBid"))) {
                    unitJson.put("deep_conversion_bid", groupJson.getLong("deepConversionBid"));
                }
                // 深度转化目标
                if (!Check.isNull(groupJson.getInteger("deepConversionType"))) {
                    unitJson.put("deep_conversion_type", groupJson.getInteger("deepConversionType"));
                }
                // 优化目标
                Integer ocpx_action_type = groupJson.getInteger("ocpxActionType");
                if (!Check.isNull(ocpx_action_type)) {
                    unitJson.put("ocpx_action_type", ocpx_action_type);
                }
                String unitName = groupJson.getString("unitName");
                if (!Check.isNull(unitName)) {
                    unitJson.put("unit_name", unitName);
                }

                Map<String, Object> returnUnitMap = kuaishouInterfaceService.adUnitCreate(oauthToken.getAccessToken(), oauthToken.getAccountId(), unitJson, 1);

                if (!Check.isNullMap(returnUnitMap)) {
                    Integer code = (Integer) returnUnitMap.get("code");
                    if (code == 0) {

                        Long unitId = (Long) returnUnitMap.get("unitId");
                        returnJson.put("code", 0);
                        returnJson.put("unitId", unitId);

                        if (!Check.isNull(type) && "copy".equals(type)) {
                            Long copyUnitId = requestJson.getLong("copyUnitId");
                            if (!Check.isNull(unitId) && !Check.isNull(copyUnitId)) {
                                Thread thread = new Thread() {
                                    @Override
                                    public void run() {
                                        try {
                                            copyCreative(oauthToken.getAccountId(), unitId, copyUnitId, otherJson);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                                thread.start();
                            }
                        }
                    } else {
                        returnJson.put("code", -1);
                        returnJson.put("unitName", unitName);
                        returnJson.put("message", returnUnitMap.get("message"));
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", "系统异常");
        }


        return returnJson;
    }


    /**
     * 复制组
     *
     * @param
     * @throws Exception
     */


    @Override
    public JSONObject copyUnit(KuaiShouGroup group, Long copyToCampaignId, CtopOauthToken oauthToken, JSONObject otherJson) {
        JSONObject returnJson = new JSONObject();
        try {
            JSONObject unitJson = new JSONObject();
            unitJson.put("campaign_id", copyToCampaignId);
            // 资源位置
            JSONArray scene_id = JSONArray.parseArray(group.getSceneId());
            if (!Check.isNull(scene_id)) {
                unitJson.put("scene_id", scene_id);
            }
            Integer sceneId = valueOf(scene_id.get(0).toString());
            // 资源创作方式
            if (!Check.isNull(group.getUnitType())) {
                if (!Check.isNull(group.getUnitType())) {
                    unitJson.put("unit_type", group.getUnitType());
                }
                //投放开始时间
                if (!Check.isNull(group.getBeginTime())) {
                    String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                    boolean beginTimeBoolean = DateUtils.compare(group.getBeginTime(), nowDate);
                    if (beginTimeBoolean) {
                        unitJson.put("begin_time", nowDate);
                    } else {
                        unitJson.put("begin_time", group.getBeginTime());
                    }
                }
                // 优先从系统应用商店下载
                if (!Check.isNull(group.getUseAppMarket())) {
                    unitJson.put("use_app_market", group.getUseAppMarket());
                }

                // 应用商店列表
                if (!Check.isNull(group.getAppStore())) {
                    unitJson.put("app_store", JSONArray.parseArray(group.getAppStore()));
                }

                // 转化目标id
                if (!Check.isNull(group.getConvertId())) {
                    unitJson.put("convert_id", group.getConvertId());
                }
                // 投放结束时间
                if (!Check.isNull(group.getEndTime())) {
                    unitJson.put("end_time", group.getEndTime());
                }
                // 投放时间段
                if (!Check.isNull(group.getScheduleTime())) {
                    unitJson.put("schedule_time", group.getScheduleTime());
                }
                // 广告组单日预算
                if (!Check.isNull(group.getDayBudget())) {
                    unitJson.put("day_budget", group.getDayBudget());
                }
                // url类型
                if (!Check.isNull(group.getUrlType())) {
                    unitJson.put("url_type", group.getUrlType());
                }
                // url
                if (!Check.isNull(group.getUrl())) {
                    unitJson.put("url", group.getUrl());
                }
                // appId
                if (!Check.isNull(group.getAppId())) {
                    unitJson.put("app_id", group.getAppId());
                }
                // 创意展现方式
                if (!Check.isNull(group.getShowMode())) {
                    unitJson.put("show_mode", group.getShowMode());
                }
                if (!Check.isNull(group.getSpeed())) {
                    unitJson.put("speed", group.getSpeed());
                }
                QueryWrapper<KuaiShouGroupTarget> targetQueryWrapper = new QueryWrapper<>();
                targetQueryWrapper.eq("account_id", group.getAccountId());
                targetQueryWrapper.eq("unit_id", group.getUnitId());
                targetQueryWrapper.last("limit 1");
                KuaiShouGroupTarget groupTarget = targetMapper.selectOne(targetQueryWrapper);
                if (!Check.isNull(groupTarget)) {
                    // -----------------用户定向-----------
                    JSONObject targetJson = new JSONObject();

                    // 地域
                    if (!Check.isNull(groupTarget.getRegion())) {
                        targetJson.put("region", JSONArray.parseArray(groupTarget.getRegion()));
                    }

                    // 自定义年龄段
                    Integer ageMin = groupTarget.getAgeMin();
                    Integer ageMax = groupTarget.getAgeMax();


                    JSONObject ageJson = new JSONObject();
                    if (!Check.isNull(ageMin)) {
                        ageJson.put("min", ageMin);
                    }
                    if (!Check.isNull(ageMax)) {
                        ageJson.put("max", ageMax);
                    }

                    targetJson.put("age", ageJson);

                    // 固定年龄段
                    if (!Check.isNull(groupTarget.getAgesRange())) {
                        targetJson.put("ages_range", JSONArray.parseArray(groupTarget.getAgesRange()));
                    }
                    // 性别
                    if (!Check.isNull(groupTarget.getGender())) {
                        targetJson.put("gender", groupTarget.getGender());
                    }
                    //操作系统
                    if (!Check.isNull(groupTarget.getPlatformOs())) {
                        targetJson.put("platform_os", groupTarget.getPlatformOs());
                    }
                    //Android版本
                    if (!Check.isNull(groupTarget.getAndroidOsv())) {
                        targetJson.put("android_osv", groupTarget.getAndroidOsv());
                    }
                    // iOS版本
                    if (!Check.isNull(groupTarget.getIosOsv())) {
                        targetJson.put("ios_osv", groupTarget.getIosOsv());
                    }
                    //网络环境
                    if (!Check.isNull(groupTarget.getNetwork())) {
                        targetJson.put("network", groupTarget.getNetwork());
                    }
                    //设备品牌
                    if (!Check.isNull(groupTarget.getDeviceBrand())) {
                        targetJson.put("device_brand", JSONArray.parseArray(groupTarget.getDeviceBrand()));
                    }
                    //设备价格
                    if (!Check.isNull(groupTarget.getDevicePrice())) {
                        targetJson.put("device_price", JSONArray.parseArray(groupTarget.getDevicePrice()));
                    }
                    if (sceneId != 5) {
                        if (!Check.isNull(groupTarget.getFilterConvertedLevel())) {
                            targetJson.put("filter_converted_level", groupTarget.getFilterConvertedLevel());
                        }

                        //商业兴趣类型
                        if (!Check.isNull(groupTarget.getBusinessInterestType())) {
                            targetJson.put("business_interest_type", groupTarget.getBusinessInterestType());
                        }
                        // 商业兴趣
                        if (!Check.isNull(groupTarget.getBusinessInterest())) {
                            targetJson.put("business_interest", JSONArray.parseArray(groupTarget.getBusinessInterest()));
                        }
                        //网红粉丝
                        if (!Check.isNull(groupTarget.getFansStar())) {
                            targetJson.put("fans_star", JSONArray.parseArray(groupTarget.getFansStar()));
                        }
                        //兴趣视频用户
                        if (!Check.isNull(groupTarget.getInterestVideo())) {
                            targetJson.put("interest_video", JSONArray.parseArray(groupTarget.getInterestVideo()));
                        }
                        // APP行为-按分类
                        if (!Check.isNull(groupTarget.getAppInterest())) {
                            targetJson.put("app_interest", JSONArray.parseArray(groupTarget.getAppInterest()));
                        }
                    }
                    // APP行为-按APP名称
                    if (!Check.isNull(groupTarget.getAppIds())) {
                        targetJson.put("app_ids", JSONArray.parseArray(groupTarget.getAppIds()));
                    }
                    // 人群包定向
                    if (!Check.isNull(groupTarget.getPopulation())) {
                        targetJson.put("population", JSONArray.parseArray(groupTarget.getPopulation()));
                    }
                    // 人群包排除
                    if (!Check.isNull(groupTarget.getExcludePopulation())) {
                        targetJson.put("exclude_population", JSONArray.parseArray(groupTarget.getExcludePopulation()));
                    }

                    if (!Check.isNull(groupTarget.getThirdPlatformCode())) {
                        targetJson.put("third_platform_code", groupTarget.getThirdPlatformCode());
                    }
                    if (sceneId != 5) {
                        JSONObject intelliExtendJson = new JSONObject();
                        // 开启智能扩量
                        if (!Check.isNull(groupTarget.getIsOpen())) {
                            intelliExtendJson.put("is_open", groupTarget.getIsOpen());
                        }
                        //不可突破年龄
                        if (!Check.isNull(groupTarget.getNoAgeBreak())) {
                            intelliExtendJson.put("no_age_break", groupTarget.getNoAgeBreak());
                        }
                        //不可突破性别
                        if (!Check.isNull(groupTarget.getNoGenderBreak())) {
                            intelliExtendJson.put("no_gender_break", groupTarget.getNoGenderBreak());
                        }
                        // 不可突破地域
                        if (!Check.isNull(groupTarget.getNoAreaBreak())) {
                            intelliExtendJson.put("no_area_break", groupTarget.getNoAreaBreak());
                        }
                        if (!Check.isNull(intelliExtendJson)) {
                            targetJson.put("intelli_extend", intelliExtendJson);
                        }
                    }

                    unitJson.put("target", targetJson);
                }
                // 出价
                if (!Check.isNull(group.getBid())) {
                    unitJson.put("bid", group.getBid());
                }
                // 出价类型
                Integer bidType = group.getBidType();
                if (!Check.isNull(bidType)) {
                    unitJson.put("bid_type", bidType);
                }
                // 深度转化出价
                if (!Check.isNull(group.getCpaBid())) {
                    unitJson.put("cpa_bid", group.getCpaBid());
                }
                // 深度转化目标出价
                if (!Check.isNull(group.getDeepConversionBid())) {
                    unitJson.put("deep_conversion_bid", group.getDeepConversionBid());
                }
                // 深度转化目标
                if (!Check.isNull(group.getDeepConversionType())) {
                    unitJson.put("deep_conversion_type", group.getDeepConversionType());
                }
                // 优化目标
                Integer ocpx_action_type = group.getOcpxActionType();
                if (!Check.isNull(ocpx_action_type)) {
                    unitJson.put("ocpx_action_type", ocpx_action_type);
                }
                String unitName = group.getUnitName();
                if (!Check.isNull(unitName)) {
                    unitJson.put("unit_name", unitName);
                }

                Map<String, Object> returnUnitMap = kuaishouInterfaceService.adUnitCreate(oauthToken.getAccessToken(), group.getAccountId(), unitJson, 1);
                if (!Check.isNullMap(returnUnitMap)) {
                    Integer code = (Integer) returnUnitMap.get("code");
                    if (code == 0) {
                        Long copyUnitId = (Long) returnUnitMap.get("unitId");
                        returnJson.put("unitId", copyUnitId);

                        returnJson.put("unitName", unitName);
                        returnJson.put("code", 0);
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    copyCreative(group.getAccountId(), copyUnitId, group.getUnitId(), otherJson);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        thread.start();
                    } else {
                        returnJson.put("code", -1);
                        returnJson.put("unitName", unitJson.getString("unitName"));
                        returnJson.put("message", returnUnitMap.get("message"));
                    }

                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", "快手接口返回数据为空");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }

        return returnJson;

    }


    /**
     * 复制创意
     *
     * @param accountId
     * @param unitId
     */
    @Override
    public void copyCreative(Long accountId, Long unitId, Long copyUnitId, JSONObject otherJson) throws Exception {
        // 查询当前复制组下的所有非程序化创意
        QueryWrapper<KuaiShouCreative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("unit_id", copyUnitId);
        List<KuaiShouCreative> creativeList = creativeMapper.selectList(queryWrapper);
        if (!Check.isNull(creativeList)) {
            for (KuaiShouCreative creative : creativeList) {
                if (Check.isNull(creative.getPhotoId())) {
                    continue;
                }
                CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
                if (Check.isNull(oauthToken)) {
                    throw new Exception("未获取到账户信息");
                }
                JSONObject creativeJson = new JSONObject();
                creativeJson.put("advertiser_id", accountId);
                creativeJson.put("unit_id", unitId);

                Integer creativeMaterialType = creative.getCreativeMaterialType();
                if (Check.isNull(creativeMaterialType)) {
                    continue;
                }
                creativeJson.put("creative_material_type", creativeMaterialType);
                String click_track_url = creative.getClickTrackUrl();


                String action_bar_text = creative.getActionBarText();
                JSONArray successArr = new JSONArray();
                JSONArray failArr = new JSONArray();
                String description = creative.getDescription();
                String name = creative.getCreativeName();
                creativeJson.put("action_bar_text", action_bar_text);
                creativeJson.put("description", description.trim());
                creativeJson.put("creative_name", name);
                String imageToken = null;
                if (!Check.isNull(creative.getStickerTitle()) && !Check.isNull(creative.getOverlayType())) {
                    imageToken = creative.getOverlayBgImageToken();
                } else {
                    imageToken = creative.getImageToken();
                }


                //封面广告语标题
                if (!Check.isNull(creative.getStickerTitle())) {
                    creativeJson.put("sticker_title", creative.getStickerTitle());
                }
                // 贴纸样式类型
                if (!Check.isNull(creative.getOverlayType())) {
                    creativeJson.put("overlay_type", creative.getOverlayType());
                }


                // 第三方有效播放监测链接
                if (!Check.isNull(creative.getAdPhotoPlayedT3sUrl())) {
                    creativeJson.put("ad_photo_played_t3s_url", creative.getAdPhotoPlayedT3sUrl());
                }
                // 第三方点击按钮监测链接
                if (!Check.isNull(creative.getActionbarClickUrl())) {
                    creativeJson.put("actionbar_click_url", creative.getActionbarClickUrl());
                }

                /**
                 * 创意标签
                 */
                if (!Check.isNull(creative.getCreativeCategory()) && !Check.isNull(!Check.isNull(creative.getCreativeTag()))) {
                    creativeJson.put("creative_category", creative.getCreativeCategory());
                    creativeJson.put("creative_tag", JSONArray.parseArray(creative.getCreativeTag()));
                }
                if (!Check.isNull(otherJson)) {
                    Boolean isUpdate = otherJson.getBoolean("isUpdate"); // 是否修改落地页
                    if (isUpdate) {
                        if (!Check.isNull(otherJson.getLong("siteId"))) {
                            creativeJson.put("site_id", otherJson.getLong("siteId"));
                        }
                    } else {
                        if (!Check.isNull(creative.getSiteId())) {
                            creativeJson.put("site_id", creative.getSiteId());
                        }
                    }

                    Boolean isUpdateTrackUrl = otherJson.getBoolean("isUpdateTrackUrl"); // 是否修改监测链接
                    if (isUpdateTrackUrl) {
                        String clickTrackUrl = otherJson.getString("clickTrackUrl");
                        if (!Check.isNull(clickTrackUrl)) {
                            if (creativeMaterialType == 4) {
                                creativeJson.put("image_tokens", JSONArray.parseArray(creative.getImageTokens()));
                                creativeJson.put("short_slogan", creative.getShortSlogan());
                                // 第三方开始播放监测链接
                                creativeJson.put("impression_url", clickTrackUrl);
                            } else {
                                String photo_id = creative.getPhotoId();
                                creativeJson.put("photo_id", photo_id);
                                creativeJson.put("image_token", imageToken);
                                creativeJson.put("click_track_url", clickTrackUrl);

                            }
                        } else {
                            if (creativeMaterialType == 4) {
                                creativeJson.put("image_tokens", JSONArray.parseArray(creative.getImageTokens()));
                                creativeJson.put("short_slogan", creative.getShortSlogan());
                                // 第三方开始播放监测链接
                                if (!Check.isNull(click_track_url)) {
                                    creativeJson.put("impression_url", click_track_url);
                                }

                                if (!Check.isNull(creative.getImpressionUrl())) {
                                    creativeJson.put("impression_url", creative.getImpressionUrl());
                                }
                            } else {
                                String photo_id = creative.getPhotoId();
                                creativeJson.put("photo_id", photo_id);
                                creativeJson.put("image_token", imageToken);
                                if (!Check.isNull(click_track_url)) {
                                    creativeJson.put("click_track_url", click_track_url);
                                }
                            }
                        }
                    } else {
                        if (creativeMaterialType == 4) {
                            creativeJson.put("image_tokens", JSONArray.parseArray(creative.getImageTokens()));
                            creativeJson.put("short_slogan", creative.getShortSlogan());
                            // 第三方开始播放监测链接
                            if (!Check.isNull(click_track_url)) {
                                creativeJson.put("impression_url", click_track_url);
                            }

                            if (!Check.isNull(creative.getImpressionUrl())) {
                                creativeJson.put("impression_url", creative.getImpressionUrl());
                            }
                        } else {
                            String photo_id = creative.getPhotoId();
                            creativeJson.put("photo_id", photo_id);
                            creativeJson.put("image_token", imageToken);

                            if (!Check.isNull(click_track_url)) {
                                creativeJson.put("click_track_url", click_track_url);
                            }
                        }
                    }
                } else {
                    if (!Check.isNull(creative.getSiteId())) {
                        creativeJson.put("site_id", creative.getSiteId());
                    }

                    if (creativeMaterialType == 4) {
                        creativeJson.put("image_tokens", JSONArray.parseArray(creative.getImageTokens()));
                        creativeJson.put("short_slogan", creative.getShortSlogan());
                        // 第三方开始播放监测链接
                        if (!Check.isNull(click_track_url)) {
                            creativeJson.put("impression_url", click_track_url);
                        }

                        if (!Check.isNull(creative.getImpressionUrl())) {
                            creativeJson.put("impression_url", creative.getImpressionUrl());
                        }
                    } else {
                        String photo_id = creative.getPhotoId();
                        creativeJson.put("photo_id", photo_id);
                        creativeJson.put("image_token", imageToken);
                        if (!Check.isNull(click_track_url)) {
                            creativeJson.put("click_track_url", click_track_url);
                        }
                    }
                }
                // 安卓下载中间页
                Map<String, Object> returnCreativeMap = kuaishouInterfaceService.creativeCreate(oauthToken.getAccessToken(), accountId, creativeJson, 1);
                if (!Check.isNullMap(returnCreativeMap)) {
                    Integer code = (Integer) returnCreativeMap.get("code");
                    if (code == 0) {
                        JSONObject successJson = new JSONObject();
                        successJson.put("creativeName", name);
                        successArr.add(successJson);
                    } else {
                        JSONObject failJson = new JSONObject();
                        failJson.put("creativeName", name);
                        failJson.put("failMessage", returnCreativeMap.get("message"));
                        failArr.add(failJson);
                    }
                }
            }
        }
    }


    /**
     * 获取广告组信息
     *
     * @param accountId
     * @param unitId
     * @return
     */


    @Override
    public KuaiShouGroup getUnitInfo(Long accountId, Long unitId) {
        QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("account_id", accountId);
        groupQueryWrapper.eq("unit_id", unitId);
        groupQueryWrapper.orderByDesc("create_time");
        groupQueryWrapper.last("limit 1");
        KuaiShouGroup group = groupMapper.selectOne(groupQueryWrapper);
        return group;
    }


    /**
     * 创建创意
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject createCreative(JSONObject requestJson) throws Exception {
        if (Check.isNull(requestJson)) {
            throw new Exception("入参为空");
        }

        Long accountId = requestJson.getLong("accountId");
        if (Check.isNull(accountId)) {
            throw new Exception("请输入需创建账号");
        }

        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        if (Check.isNull(oauthToken)) {
            throw new Exception("未获取到账户信息");
        }
        Long unitId = requestJson.getLong("unitId");
        if (Check.isNull(unitId)) {
            throw new Exception("请选择广告组");
        }
        JSONObject creativeJson = new JSONObject();
        creativeJson.put("advertiser_id", accountId);
        creativeJson.put("unit_id", unitId);

        // 素材类型

        String action_bar_text = requestJson.getString("actionBarText");
        String click_track_url = requestJson.getString("clickTrackUrl");
        String site_id = requestJson.getString("siteId");
        Integer creativeCategory = requestJson.getInteger("creativeCategory");// 创意分类
        JSONArray creativeTag = requestJson.getJSONArray("creativeTag");
        JSONObject returnJson = new JSONObject();
        JSONArray successArr = new JSONArray();
        JSONArray failArr = new JSONArray();
        JSONArray dataJsons = requestJson.getJSONArray("dataJson");
        Integer content = requestJson.getInteger("content");
        if (!Check.isNull(dataJsons)) {
            for (int i = 0; i < dataJsons.size(); i++) {
                JSONObject dataJson = dataJsons.getJSONObject(i);
                String creativeMaterialType = dataJson.getString("creativeMaterialType");
                String shortSlogan = dataJson.getString("shortSlogan");
                String overlayType = dataJson.getString("overlayType");
                String stickerTitle = dataJson.getString("stickerTitle");
                if (!Check.isNull(dataJsons)) {
                    String description = dataJson.getString("description");
                    String photo_id = dataJson.getString("photoId");
                    JSONArray imageArr = dataJson.getJSONArray("imageArr");
                    if (!Check.isNull(imageArr)) {
                        for (int j = 0; j < imageArr.size(); j++) {
                            JSONObject imageJson = imageArr.getJSONObject(j);
                            if (!Check.isNull(imageJson)) {
                                content += 1;
                                String name = imageJson.getString("name") + content;
                                creativeJson.put("action_bar_text", action_bar_text);
                                creativeJson.put("description", description.trim());
                                creativeJson.put("creative_name", name);
                                creativeJson.put("photo_id", photo_id);

                                if (!Check.isNull(site_id)) {
                                    creativeJson.put("site_id", site_id);
                                }
                                if (!Check.isNull(creativeMaterialType)) {
                                    creativeJson.put("creative_material_type", creativeMaterialType);
                                }

                                if (!Check.isNull(overlayType)) {
                                    creativeJson.put("overlay_type", overlayType);
                                }
                                if (!Check.isNull(stickerTitle)) {
                                    creativeJson.put("sticker_title", stickerTitle);
                                }

                                if (!Check.isNull(creativeCategory) && !Check.isNull(creativeTag)) {
                                    creativeJson.put("creative_category", creativeCategory);
                                    creativeJson.put("creative_tag", creativeTag);
                                }

                                if ("4".equals(creativeMaterialType)) {
                                    if (!Check.isNull(shortSlogan)) {
                                        creativeJson.put("short_slogan", shortSlogan);
                                    }
                                }
                                String imageToken = null;
                                String signature = imageJson.getString("signature");
                                if (!Check.isNull(signature)) {
                                    QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("account_id", accountId);
                                    queryWrapper.eq("signature", signature);
                                    queryWrapper.last("limit 1");
                                    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)) {
                                        JSONObject failJson = new JSONObject();
                                        failJson.put("creativeName", name);
                                        failJson.put("failMessage", "获取图片文件失败");
                                        failArr.add(failJson);
                                        continue;
                                    }
                                }
                                if ("4".equals(creativeMaterialType)) {
                                    JSONArray tokenArr = new JSONArray();
                                    tokenArr.add(imageToken);
                                    creativeJson.put("image_tokens", tokenArr);
                                    creativeJson.put("click_track_url", click_track_url);
                                    creativeJson.put("impression_url", click_track_url);
                                } else {
                                    creativeJson.put("image_token", imageToken);
                                    creativeJson.put("click_track_url", click_track_url);
                                }
                                Map<String, Object> returnUnitMap = kuaishouInterfaceService.creativeCreate(oauthToken.getAccessToken(), accountId, creativeJson, 1);
                                if (!Check.isNullMap(returnUnitMap)) {
                                    Integer code = (Integer) returnUnitMap.get("code");
                                    if (code == 0) {
                                        JSONObject successJson = new JSONObject();
                                        successJson.put("creativeName", name);
                                        successArr.add(successJson);
                                    } else {
                                        JSONObject failJson = new JSONObject();
                                        failJson.put("creativeName", name);
                                        failJson.put("failMessage", returnUnitMap.get("message"));
                                        failArr.add(failJson);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        returnJson.put("success", successArr);
        returnJson.put("fail", failArr);
        return returnJson;
    }


    @Override
    public Map<String, Object> batchCreateCreative(JSONObject requestJson) throws Exception {
        if (Check.isNull(requestJson)) {
            throw new Exception("入参为空");
        }

        Long accountId = requestJson.getLong("accountId");
        if (Check.isNull(accountId)) {
            throw new Exception("请输入需创建账号");
        }

        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        if (Check.isNull(oauthToken)) {
            throw new Exception("未获取到账户信息");
        }

        Long unitId = requestJson.getLong("unitId");
        if (Check.isNull(unitId)) {
            throw new Exception("请选择广告组");
        }

        JSONObject creativeJson = new JSONObject();
        creativeJson.put("advertiser_id", accountId);
        creativeJson.put("unit_id", unitId);
        String click_track_url = requestJson.getString("clickTrackUrl");
        String actionbar_click_url = requestJson.getString("actionbarClickUrl");
        // 素材类型
        String action_bar_text = requestJson.getString("actionBarText");
        String site_id = requestJson.getString("siteId");
        Integer creativeCategory = requestJson.getInteger("creativeCategory");// 创意分类
        JSONArray creativeTag = requestJson.getJSONArray("creativeTag");
        JSONArray dataJsons = requestJson.getJSONArray("dataJson");
        Integer content = requestJson.getInteger("content");
        if (!Check.isNull(dataJsons)) {
            JSONArray creatives = new JSONArray();
            for (int i = 0; i < dataJsons.size(); i++) {
                JSONObject dataJson = dataJsons.getJSONObject(i);
                String creativeMaterialType = dataJson.getString("creativeMaterialType");
                String shortSlogan = dataJson.getString("shortSlogan");
                String overlayType = dataJson.getString("overlayType");
                String stickerTitle = dataJson.getString("stickerTitle");
                String description = dataJson.getString("description");
                String photo_id = dataJson.getString("photoId");
                JSONArray imageArr = dataJson.getJSONArray("imageArr");
                if (!Check.isNull(imageArr)) {
                    for (int j = 0; j < imageArr.size(); j++) {
                        JSONObject imageJson = imageArr.getJSONObject(j);
                        if (!Check.isNull(imageJson)) {
                            JSONObject creative = new JSONObject();
                            content += 1;
                            String name = imageJson.getString("name") + content;
                            creative.put("action_bar_text", action_bar_text);
                            creative.put("description", description.trim());
                            creative.put("creative_name", name);
                            creative.put("photo_id", photo_id);
                            if (!Check.isNull(site_id)) {
                                creative.put("site_id", site_id);
                            }
                            if (!Check.isNull(creativeMaterialType)) {
                                creative.put("creative_material_type", creativeMaterialType);
                            }
                            if (!Check.isNull(overlayType)) {
                                creative.put("overlay_type", overlayType);
                            }
                            if (!Check.isNull(stickerTitle)) {
                                creative.put("sticker_title", stickerTitle);
                            }
                            if (!Check.isNull(creativeCategory) && !Check.isNull(creativeTag)) {
                                creativeJson.put("creative_category", creativeCategory);
                                creativeJson.put("creative_tag", creativeTag);
                            }
                            if ("4".equals(creativeMaterialType)) {
                                if (!Check.isNull("shortSlogan")) {
                                    creative.put("short_slogan", shortSlogan);
                                }
                            }
                            String imageToken = null;
                            String signature = imageJson.getString("signature");
                            if (!Check.isNull(signature)) {
                                QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("account_id", accountId);
                                queryWrapper.eq("signature", signature);
                                queryWrapper.last("limit 1");
                                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)) {
                                    continue;
                                }
                            }
                            if ("4".equals(creativeMaterialType)) {
                                JSONArray tokenArr = new JSONArray();
                                tokenArr.add(imageToken);
                                creative.put("image_tokens", tokenArr);
                                creativeJson.put("click_track_url", click_track_url);
                                creativeJson.put("impression_url", click_track_url);
                            } else {
                                creative.put("image_token", imageToken);
                                creativeJson.put("click_track_url", click_track_url);
                            }
                            if (!Check.isNull(actionbar_click_url)) {
                                creativeJson.put("actionbar_click_url", actionbar_click_url);
                            }

                            creatives.add(creative);
                        }
                    }
                }


            }

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

        Map<String, Object> returnUnitMap = kuaishouInterfaceService.batchCreativeCreate(oauthToken.getAccessToken(), accountId, creativeJson, 1, null);
        return returnUnitMap;
    }

    @Override
    public JSONObject getCategoryWhite(Long accountId, String accessToken) {
        try {
            String url = "https://ad.e.kuaishou.com/rest/openapi/v1/advertiser/white_list";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", accessToken);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("advertiser_id", accountId);
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {
                        return data;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }


    /**
     * 获取创意信息
     *
     * @param accountId
     * @param creativeId
     * @return
     */
    @Override
    public KuaiShouCreative getCreativeInfo(Long accountId, Long creativeId) {
        QueryWrapper<KuaiShouCreative> creativeQueryWrapper = new QueryWrapper<>();
        creativeQueryWrapper.eq("account_id", accountId);
        creativeQueryWrapper.eq("creative_id", creativeId);
        creativeQueryWrapper.orderByDesc("create_time");
        creativeQueryWrapper.last("limit 1");
        KuaiShouCreative creative = creativeMapper.selectOne(creativeQueryWrapper);
        return creative;
    }


    /**
     * 修改计划信息
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject updateCampaign(JSONObject requestJson) throws Exception {
        Long accountId = requestJson.getLong("accountId");
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        if (Check.isNull(oauthToken)) {
            throw new Exception("未获取到账户信息");
        }

        JSONObject campaignJson = new JSONObject();
        campaignJson.put("advertiser_id", accountId);
        Long campaignId = requestJson.getLong("campaignId");
        if (Check.isNull(campaignId)) {
            throw new Exception("请选择广告计划");
        }
        campaignJson.put("campaign_id", campaignId);
        if (!Check.isNull(requestJson.getString("campaignName"))) {
            campaignJson.put("campaign_name", requestJson.getString("campaignName"));
        }
        if (!Check.isNull(requestJson.getString("dayBudget"))) {
            campaignJson.put("day_budget", requestJson.getString("dayBudget"));
        }
        JSONObject returnJson = updateService.updateCampaign(oauthToken.getAccessToken(), campaignJson);
        return returnJson;
    }


    /**
     * 修改广告组
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject updateUnit(JSONObject requestJson, CtopOauthToken token) throws Exception {
        JSONObject returnJson = new JSONObject();
        try {

            JSONObject unitJson = new JSONObject();
            unitJson.put("advertiser_id", token.getAccountId());
            QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper();
            queryWrapper.eq("account_id", token.getAccountId());


            Long unitId = requestJson.getLong("unitId");
            if (Check.isNull(unitId)) {
                throw new Exception("请选择广告组");
            }
            unitJson.put("unit_id", unitId);
            queryWrapper.eq("unit_id", unitId);
            queryWrapper.last("limit 1");
            KuaiShouGroup kuaiShouGroup = groupMapper.selectOne(queryWrapper);
            if (Check.isNull(kuaiShouGroup)) {
                throw new Exception("未获取到组信息");
            }
            String sceneId = kuaiShouGroup.getSceneId();
            if (Check.isNull(sceneId)) {
                throw new Exception("未获取资源位置");
            }

            //  JSONObject jsonObject = JSONArr(sceneId);
            Integer scene = (Integer) JSONArray.parseArray(sceneId).get(0);

            // 广告组名称
            if (!Check.isNull(requestJson.getString("unitName"))) {
                unitJson.put("unit_name", requestJson.getString("unitName"));
            }

            // 资源位置
            JSONArray scene_id = requestJson.getJSONArray("sceneId");
            if (!Check.isNull(scene_id)) {
                unitJson.put("scene_id", scene_id);
            }


            // 出价
            if (!Check.isNull(requestJson.getLong("bid"))) {
                unitJson.put("bid", requestJson.getLong("bid"));
            }
            // 深度转化出价
            if (!Check.isNull(requestJson.getLong("cpaBid"))) {
                unitJson.put("cpa_bid", requestJson.getLong("cpaBid"));
            }
            // 深度转化目标出价
            if (!Check.isNull(requestJson.getLong("deepConversionBid"))) {
                unitJson.put("deep_conversion_bid", requestJson.getLong("deepConversionBid"));
            }
            //投放开始时间
            if (!Check.isNull(requestJson.getString("beginTime"))) {

                String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                boolean beginTimeBoolean = DateUtils.compare(requestJson.getString("beginTime"), nowDate);
                if (beginTimeBoolean) {
                    unitJson.put("begin_time", nowDate);
                } else {
                    unitJson.put("begin_time", requestJson.getString("beginTime"));
                }


            }
            // 投放结束时间
            if (!Check.isNull(requestJson.getString("endTime"))) {
                unitJson.put("end_time", requestJson.getString("endTime"));
            }
            // 投放时间段
            if (!Check.isNull(requestJson.getString("scheduleTime"))) {
                unitJson.put("schedule_time", requestJson.getString("scheduleTime"));
            }
            // 广告组单日预算
            if (!Check.isNull(requestJson.getLong("dayBudget"))) {
                unitJson.put("day_budget", requestJson.getLong("dayBudget"));
            }
            // url类型
            if (!Check.isNull(requestJson.getInteger("urlType"))) {
                unitJson.put("url_type", requestJson.getInteger("urlType"));
            }
            // url
            if (!Check.isNull(requestJson.getString("url"))) {
                unitJson.put("url", requestJson.getString("url"));
            }
            // appId
            if (!Check.isNull(requestJson.getLong("appId"))) {
                unitJson.put("app_id", requestJson.getLong("appId"));
            }

            // 创意展现方式
            if (!Check.isNull(requestJson.getInteger("showMode"))) {
                unitJson.put("show_mode", requestJson.getInteger("showMode"));
            }
            //投放方式
            if (!Check.isNull(requestJson.getInteger("speed"))) {
                unitJson.put("speed", requestJson.getInteger("speed"));
            }

            // 优先从系统应用商店下载
            if (!Check.isNull(requestJson.getInteger("useAppMarket"))) {
                unitJson.put("use_app_market", requestJson.getInteger("useAppMarket"));
            }

            // 应用商店列表
            if (!Check.isNull(requestJson.getJSONArray("appStore"))) {
                unitJson.put("app_store", requestJson.getJSONArray("appStore"));
            }

            // 转化目标
            if (!Check.isNull(requestJson.getInteger("convertId"))) {
                unitJson.put("convert_id", requestJson.getInteger("convertId"));
            }


            // -----------------用户定向-----------
            JSONObject targetJson = new JSONObject();

            // 地域
            if (!Check.isNull(requestJson.getJSONArray("region"))) {
                targetJson.put("region", requestJson.getJSONArray("region"));
            }

            // 自定义年龄段
            JSONArray ageArr = requestJson.getJSONArray("age");
            if (!Check.isNull(ageArr)) {
                JSONObject ageJson = new JSONObject();
                ageJson.put("min", ageArr.get(0));
                ageJson.put("max", ageArr.get(1));
                targetJson.put("age", ageJson);
            }
            // 固定年龄段
            if (!Check.isNull(requestJson.getJSONArray("agesRange"))) {
                targetJson.put("ages_range", requestJson.getJSONArray("agesRange"));
            }
            // 性别
            if (!Check.isNull(requestJson.getInteger("gender"))) {
                targetJson.put("gender", requestJson.getInteger("gender"));
            }
            //操作系统
            if (!Check.isNull(requestJson.getInteger("platformOs"))) {
                targetJson.put("platform_os", requestJson.getInteger("platformOs"));
            }
            //Android版本
            if (!Check.isNull(requestJson.getInteger("androidOsv"))) {
                targetJson.put("android_osv", requestJson.getInteger("androidOsv"));
            }
            // iOS版本
            if (!Check.isNull(requestJson.getInteger("iosOsv"))) {
                targetJson.put("ios_osv", requestJson.getInteger("iosOsv"));
            }
            //网络环境
            if (!Check.isNull(requestJson.getInteger("network"))) {
                targetJson.put("network", requestJson.getInteger("network"));
            }
            // 设备品牌
            if (!Check.isNull(requestJson.getJSONArray("deviceBrand"))) {
                targetJson.put("device_brand", requestJson.getJSONArray("deviceBrand"));
            }
            // 设备价格
            if (!Check.isNull(requestJson.getJSONArray("devicePrice"))) {
                targetJson.put("device_price", requestJson.getJSONArray("devicePrice"));
            }

            if (!Check.isNull(requestJson.getJSONArray("appInterest"))) {
                targetJson.put("app_interest", requestJson.getJSONArray("appInterest"));
            }
            // APP行为-按APP名称
            if (!Check.isNull(requestJson.getJSONArray("appIds"))) {
                targetJson.put("app_ids", requestJson.getJSONArray("appIds"));
            }

            if (!Check.isNull(requestJson.getJSONArray("population"))) {
                targetJson.put("population", requestJson.getJSONArray("population"));
            }
            // 人群包排除
            if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
                targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
            }

            if (!Check.isNull(requestJson.getJSONArray("thirdPlatformCode"))) {
                targetJson.put("third_platform_code", requestJson.getJSONArray("thirdPlatformCode"));
            }

            if (scene != 5) {
                if (!Check.isNull(requestJson.getInteger("filterConvertedLevel"))) {
                    targetJson.put("filter_converted_level", requestJson.getInteger("filterConvertedLevel"));
                }

                //商业兴趣类型
                if (!Check.isNull(requestJson.getInteger("businessInterestType"))) {
                    targetJson.put("business_interest_type", requestJson.getInteger("businessInterestType"));
                }
                // 商业兴趣
                if (!Check.isNull(requestJson.getJSONArray("businessInterest"))) {
                    targetJson.put("business_interest", requestJson.getJSONArray("businessInterest"));
                }
                //网红粉丝
                if (!Check.isNull(requestJson.getJSONArray("fansStar"))) {
                    targetJson.put("fans_star", requestJson.getJSONArray("fansStar"));
                }
                //兴趣视频用户
                if (!Check.isNull(requestJson.getJSONArray("interestVideo"))) {
                    targetJson.put("interest_video", requestJson.getJSONArray("interestVideo"));
                }
            }

            if (scene != 5) {
                JSONObject intelliExtendJson = new JSONObject();

                // 开启智能扩量
                if (!Check.isNull(requestJson.getInteger("isOpen"))) {
                    intelliExtendJson.put("is_open", requestJson.getInteger("isOpen"));
                }
                //不可突破年龄
                if (!Check.isNull(requestJson.getInteger("noAgeBreak"))) {
                    intelliExtendJson.put("no_age_break", requestJson.getInteger("noAgeBreak"));
                }
                //不可突破性别
                if (!Check.isNull(requestJson.getInteger("noGenderBreak"))) {
                    intelliExtendJson.put("no_gender_break", requestJson.getInteger("noGenderBreak"));
                }
                // 不可突破地域
                if (!Check.isNull(requestJson.getInteger("noAreaBreak"))) {
                    intelliExtendJson.put("no_area_break", requestJson.getInteger("noAreaBreak"));
                }
                if (!Check.isNull(intelliExtendJson)) {
                    targetJson.put("intelli_extend", intelliExtendJson);
                }
            }


            unitJson.put("target", targetJson);

            returnJson = updateService.updateUnit(token.getAccessToken(), unitJson);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    /**
     * 修改广告创意
     *
     * @param requestJson
     * @return
     */
    @Override
    public JSONObject updateCreative(JSONObject requestJson, CtopOauthToken token) throws Exception {
        if (Check.isNull(requestJson)) {
            throw new Exception("入参为空");
        }
        JSONObject creativeJson = new JSONObject();
        creativeJson.put("advertiser_id", token.getAccountId());
        Long creativeId = requestJson.getLong("creativeId");
        if (Check.isNull(creativeId)) {
            throw new Exception("请选择广告创意");
        }
        creativeJson.put("creative_id", creativeId);
        // 创意名称
        if (!Check.isNull(requestJson.get("creativeName"))) {
            creativeJson.put("creative_name", requestJson.get("creativeName"));
        }
        //封面
        if (!Check.isNull(requestJson.get("photoId"))) {
            creativeJson.put("photo_id", requestJson.get("photoId"));
        }
        // 视频id
        if (!Check.isNull(requestJson.get("imageToken"))) {
            creativeJson.put("image_token", requestJson.get("imageToken"));
        }
        // 行动号召按钮
        if (!Check.isNull(requestJson.get("actionBarText"))) {
            creativeJson.put("action_bar_text", requestJson.get("actionBarText"));
        }
        // 广告语
        if (!Check.isNull(requestJson.get("description"))) {
            creativeJson.put("description", requestJson.getString("description").trim());
        }
        // 封面标题
        if (!Check.isNull(requestJson.get("stickerTitle"))) {
            creativeJson.put("sticker_title", requestJson.get("stickerTitle"));
        }
        // 贴纸样式
        if (!Check.isNull(requestJson.get("overlayType"))) {
            creativeJson.put("overlay_type", requestJson.get("overlayType"));
        }
        // 第三方检测链接
        if (!Check.isNull(requestJson.get("clickTrackUrl"))) {
            creativeJson.put("click_track_url", requestJson.get("clickTrackUrl"));
        }
        // 后贴片 第三方检测链接
        if (!Check.isNull(requestJson.get("adPhotoPlayedT3sUrl"))) {
            creativeJson.put("ad_photo_played_t3s_url", requestJson.get("adPhotoPlayedT3sUrl"));
        }
        // 后贴片 第三方检测链接
        if (!Check.isNull(requestJson.get("impressionUrl"))) {
            creativeJson.put("impression_url", requestJson.get("impressionUrl"));
        }
        JSONObject returnJson = updateService.updateCreative(token.getAccessToken(), creativeJson);
        return returnJson;
    }


    /**
     * 获取联盟白名单
     *
     * @param accountId
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject getWhiteList(Long accountId, String accessToken) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/v1/advertiser/white_list";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("advertiser_id", accountId);
        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        log.info("获取联盟白名单，accountId:{},data:{}", accountId, resultJson);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return resultJson.getJSONObject("data");
            }
        }
        return null;
    }


    /**
     * 获取可选的贴纸样式
     *
     * @param accountId
     * @param accessToken
     * @return
     */
    @Override
    public JSONArray getCreativeWordStyles(Long accountId, String accessToken) {
        try {
            String url = "https://ad.e.kuaishou.com/rest/openapi/v1/tool/creative_word/styles";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", accessToken);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("advertiser_id", accountId);
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    return resultJson.getJSONArray("data");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取创意分类
     *
     * @param accountId
     * @param accessToken
     * @return
     */
    @Override
    public JSONArray getCreativeCategory(Long accountId, String accessToken) {
        try {
            String url = "https://ad.e.kuaishou.com/rest/openapi/v1/creative/creative_category/list";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", accessToken);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("advertiser_id", accountId);
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {
                        JSONArray details = data.getJSONArray("details");
                        if (!Check.isNull(details)) {
                            JSONArray returnArr = new JSONArray();
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject firstJson = details.getJSONObject(i);

                                Integer parent_id = firstJson.getInteger("parent_id");
                                if (0 == parent_id) {
                                    JSONArray LevelArr = getSecond(firstJson.getString("category_id"), details);
                                    firstJson.put("child", LevelArr);
                                    returnArr.add(firstJson);
                                }
                            }
                            return returnArr;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private JSONArray getSecond(String categoryId, JSONArray details) {
        JSONArray secondArr = new JSONArray();
        for (int i = 0; i < details.size(); i++) {
            JSONObject secondJson = details.getJSONObject(i);
            if (categoryId.equals(secondJson.getString("parent_id"))) {
                JSONArray thirdArr = getThird(secondJson.getString("category_id"), details);
                secondJson.put("child", thirdArr);
                secondArr.add(secondJson);
            }
        }
        return secondArr;
    }


    private JSONArray getThird(String categoryId, JSONArray details) {
        JSONArray thirdArr = new JSONArray();
        for (int i = 0; i < details.size(); i++) {
            JSONObject thirdJson = details.getJSONObject(i);
            String parent_id = thirdJson.getString("parent_id");
            if (categoryId.equals(parent_id)) {
                thirdArr.add(thirdJson);
            }
        }
        return thirdArr;
    }
}


